(Untitled)

Microsoft Site Server 3.0 SDK

Microsoft® Site Server is a comprehensive Web site environment that works with Microsoft® Windows NT® Server and Microsoft® Internet Information Server (IIS) version 4.0. It enables you to build cost-effective Web solutions for the advanced management and targeted delivery of information. This SDK describes the COM/Automation objects provided by the Site Server system.

You can also access this SDK on the Web, part of the Microsoft Platform SDK, to get late breaking information and updates.

To get an understanding of the essential architectures, concepts, and terms, developers should first read about the components they want to work with in the main Site Server documentation. This SDK assumes a familiarity with VBScript, or JScript, and Microsoft Windows® Scripting Host. The primary language used for syntax and examples is VBScript.

The components of this SDK are as follows:

Component | Description
Content Deployment | Program content replication involving content deployment, Internet retrieval, and component deployment.
Push | Program the Microsoft Active Channel Server to automate the process of information delivery using channels.
Personalization and Membership | Program the management of customer relationships, memberships, and personalized information.
Search | Program the building of search catalogs used for searches on your Web site.
Ad Server | Commerce Edition Only—Program the delivery of advertisements to dynamically built web pages.
Commerce and Wallet | Commerce Edition Only—Program custom order processing components, and client payment components for the Microsoft® Wallet control.

© 1997-1998 Microsoft Corporation. All rights reserved.


(Untitled)

Legal Information

This document is provided for informational purposes only and Microsoft Corporation makes no warranties, either express or implied, in this document. The entire risk of the use or the results of the use of this document remains with the user. The names of companies, products, people, characters, and/or data mentioned herein are fictitious and are in no way intended to represent any real individual, company, product, or event, unless otherwise noted. Complying with all applicable copyright laws is the responsibility of the user. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, without the express written permission of Microsoft Corporation. If, however, your only means of access is electronic, permission to print one copy is hereby granted.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.

ActiveX, BackOffice, DirectX, JScript, Microsoft, Microsoft Press, MS, MS-DOS, Visual Basic, Visual C++, Windows, Win32, Win32s, and Windows NT are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. OS/2 is a registered trademark licensed to Microsoft Corporation.

Java is a trademark of Sun Microsystems, Inc.

Silicon Graphics is a registered trademark and OpenGL is a trademark of Silicon Graphics, Inc.

Other product and company names mentioned herein may be the trademarks of their respective owners.


Content Deployment Programmer's Guide

Content Deployment enables replication of files, directories, and other components for these configurations:

  • From one directory to another on the same server.

  • From one server to another on an intranet, or on the Internet.

  • From one server to multiple servers on an intranet, or on the Internet.

There are three project types that specify the method of the replication: Content Deployment, Internet Retrieval, and Component Deployment.

These project types are fully described in the main Site Server documentation, as is how to run them by using Microsoft Media Console (MMC) or WebAdmin. Alternatively, developers can program Content Deployment objects to have the same functionality tailored to their needs. This Content Deployment SDK contains reference information for programming these objects in VBScript.


Object Overview

To program Content Deployment, you must first create either a ReplicationServer object or a ReplicationClient object. You use the ReplicationClient object to replicate a few files, and the ReplicationServer object to replicate all the files.

For example, suppose your corporation has a Human Resources Web site with links to many files and graphics. You decide to add a Web page to display the company's current stock price. You add a link and graphic to the main HR Web page and create a new subdirectory to hold the stock price Web page and its graphics. Because you don't want to create a new project for just these new additions and changes, you use the ReplicationClient object.

If you make so many changes to the entire HR Web site that you have trouble remembering which files have changed or you just want to make sure you update everything, you use ReplicationServer object.

Use the ReplicationProject object to specify the project type, perform rollbacks, change deployment and destination locations, set up access control lists (ACL), and perform other administrative tasks. The ReplicationSchedule object provides flexible replication scheduling to the hour and minute.

The ReplicationInstance and ReplicationItem objects give information on the replication’s status, results, and items. The ReplicationRoute object deploys copies of required projects on the participating servers; and the ReplicationPostingAcceptor object provides control over replication delivery on the destination servers.

The Content Deployment objects are summarized alphabetically in the following table:

Object | Description
ReplicationClient | Replicates individual files without the Content Deployment server.
ReplicationClientError | Provides ReplicationClient error information.
ReplicationEventSinkConfig | Defines the configuration of an event sink.
ReplicationInstance | Provides information about individual replications.
ReplicationItem | Provides access to individual replication items.
ReplicationPostingAcceptor | Provides access to replication delivery on the destination servers.
ReplicationProject | Provides methods and properties to administer projects.
ReplicationRoute | Provides methods and properties to administer replication routes.
ReplicationSchedule | Provides access to the schedule of when and how often replications are run.
ReplicationServer | Provides methods and properties to administer the Content Deployment server.


(Untitled)

© 1997-1998 Microsoft Corporation. All rights reserved.


ReplicationClient

Use the ReplicationClient object to have finer control over replications. You can create your own replication scheme by using the ReplicationClient methods and properties with ReplicationItem objects (see ReplicationProject.EnumItems).

Content Deployment replications operate on entire directories. The ReplicationClient object lets you replicate specific files on demand. This provides more granular control over the replication process and, since it is single-file based, provides much more detailed error reporting through the ReplicationClientError object.

You get access to a ReplicationClient object by calling CreateObject, as follows:

Set RepClient = CreateObject("CrsApi.ReplicationClient")

Once you have access to the ReplicationClient object, you must call the Initialize method, unless the object is created through a ReplicationProject object, in which case you need not call Initialize.

Use the Connect method and the Disconnect method in conjunction with the SendFile and DeleteFile methods when you need to update more than one or two files. If you only need to update one or two files, use just the SendFile method or DeleteFile method without the Connect and Disconnect methods (they perform their own connections and disconnections to the destination server if the Content Deployment server isn't connected to a destination server).

To update a number of files

  1. Use the Connect method to establish a connection to the destination server.

  2. Use the SendFile method to send a file to the destination server or the DeleteFile method to delete a file from the destination server.

  3. Use the Disconnect method to sever the connection to the destination server.

If your Content Deployment server is connected to the destination server and transaction processing is turned on at the destination server, file operations are not applied until you call either the Disconnect method or the Commit method.

You can issue an Abort method at any time during a transaction to cancel all pending transactions.

The Content Deployment component will not allow you to use both the ReplicationClient and ReplicationServer objects at the same time to run the same project. If you try to use both, Content Deployment issues the error code CRS_ERROR_PROJECT_ALREADY_RUNNING.


ReplicationClientError

Use the ReplicationClientError object to get extended information about any ReplicationClient errors that have occurred during a replication process.

You get access to the ReplicationClientError object by calling the ReplicationClient.GetExtendedErrorInfo method. GetExtendedErrorInfo returns an array of ReplicationClientError objects. Since the array is empty when no error information is available, be sure to do bounds checking before accessing the array.


ReplicationEventSink

The ReplicationEventSink object receives event notifications from the Content Deployment component. If you want to receive events, you can write a COM DLL that implements this object, and then register it with the Content Deployment component.


ReplicationEventSinkConfig

Use the ReplicationEventSinkConfig object's properties to configure Content Deployment event sinks.

You get access to the ReplicationEventSinkConfig object by using either the ReplicationServer.AddEventSink method or the ReplicationServer.EnumEventSinks method.


ReplicationInstance

Use the ReplicationInstance object to query the state, status, and results of a replication, such as the number of bytes or files sent or received.

You get access to the ReplicationInstance object by calling either the ReplicationProject.EnumReplications method or the ReplicationServer.EnumReplications method.


ReplicationItem

Use the ReplicationItem object to gather information on replicated files.

You get access to the ReplicationItem object by calling the ReplicationProject.EnumItems method.


ReplicationPostingAcceptor

Use the ReplicationPostingAcceptor object to access replication delivery on the destination servers.

You get access to a ReplicationPostingAcceptor object by calling the ReplicationServer.OpenPA method.


ReplicationProject

Use the ReplicationProject object to manipulate individual projects on a Content Deployment server.

You get access to a ReplicationProject object by calling either the ReplicationServer.OpenProject method or the ReplicationServer.EnumProjects method.


ReplicationRoute

Use the ReplicationRoute object to manipulate individual replication routes.

You get access to the ReplicationRoute object by calling either the ReplicationServer.AddRoute method to create a new route or the ReplicationServer.EnumRoutes method to access an existing route.


ReplicationSchedule

Use the ReplicationSchedule object to administer the schedule of when and how often replications are run.

You get access to a ReplicationSchedule object by calling either the ReplicationProject.AddSchedule method to create a new schedule or the ReplicationProject.EnumSchedules method to access an existing schedule.


ReplicationServer

The ReplicationServer object is the primary interface between your application and the Content Deployment component. The ReplicationServer object allows you to manage routes, projects and transactions, as well as start, stop, and pause the Content Deployment Service.

You get access to a ReplicationServer object by calling Server.CreateObject, as follows:

Set RepServer = CreateObject("CrsApi.ReplicationServer")

Once you have access to the ReplicationServer object, you must call the ReplicationServer.Initialize method before attempting to access any other ReplicationServer methods or properties.


Samples

The following sample Active Server Pages, along with a Default.htm that runs them, are in the Content Deployment Samples folder.

ASP File | Description
Default.htm | Web page with buttons to run the other ASP files.
Code.asp | Routines to initialize the server and display errors.
EditServ.asp | Lists the server parameters.
EnumRep.asp | Lists the replications.
ProjCreate.asp | Creates an example project
ProjDel.asp | Deletes the example project.
ProjList.asp | Lists the projects.
ProjStats.asp | Gets the statistics for the current projects.
RteCreate.asp | Creates an example route.
RteDel.asp | Deletes the example route.
RteList.asp | Lists the routes.
ServCtrl.asp | Starts, stops, pauses, or continues the service.


Content Deployment Programmer's Reference

This section describes the VBScript programming interface to the Microsoft Site Server Content Deployment feature. It describes the objects, including methods and properties, that are provided.


Adapting WSH Examples for ASP

Although the object reference examples are written for the Windows Scripting Host (WSH), you can easily adapt them for Active Server Pages (ASP). The first step is to wrap your VBScript code in the ASP delimiters (<% and %>), as in the following example:

WSH File | ASP File
Option Explicit On Error Resume Next dim ReplClient Set ReplClient = CreateObject("CrsApi.ReplicationClient") ... 'Do some replications 'Release Client object ReplClient = Nothing | <% Option Explicit On Error Resume Next dim ReplClient set ReplClient = CreateObject("CrsApi.ReplicationClient") ... 'Do some replications 'Release Client object ReplClient = Nothing %>

Also, to produce output, you must change the Wscript.Echo methods to Response.Write methods.

Note Since ASP files default to the VBScript programming language, you need not supply a language qualifier to your VBScript ASP pages. If you use a different language, such as JScript, you must amend the first line of the previous ASP example to the following:

<% SCRIPT LANGUAGE="JScript"

ASP files offer some additional functionality over WSH files. For example, you can create an include file in which can place commonly-used code, such as the following defined constants, which are all of the defined states for the ReplicationInstance.State property:

const REPL_STATE_EMPTY      = 0
const REPL_STATE_STARTING   = 1
const REPL_STATE_RUNNING    = 2
const REPL_STATE_COMPLETE   = 3
const REPL_STATE_ABORTED    = 4
const REPL_STATE_CANCELED   = 5
const REPL_STATE_RECEIVING  = 6
const REPL_STATE_PENDING    = 7

You can then include this file in an ASP file with a line of code similar to the following, where CDinclude.inc is the name of the include file (it can be any legal file name and need not have the .inc file extension):

<!--include file = "CDinclude.inc"-->

Note You must explicitly cast any whole number value that you assign to a global parameter to a 32-bit (long) integer with CLng(), as shown in the following example, which sets the Depth parameter (the depth of the replication) to 3 for project MyProject:

const OPEN_EXISTING_PROJECT  = 2

dim ReplServer, Proj, Depth

set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

set Proj = ReplServer.OpenProject("MyProject", OPEN_EXISTING_PROJECT)

Depth = Clng(3)
Proj.Put("Depth", Depth)

'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing


Content Deployment Objects

The following table briefly describes the Content Deployment objects.

Object | Description
ReplicationClient | Replicates individual files without the Content Deployment server.
ReplicationClientError | Provides ReplicationClient error information.
ReplicationEventSinkConfig | Defines the configuration of an event sink.
ReplicationInstance | Provides information about individual replications.
ReplicationItem | Provides access to individual replication items.
ReplicationPostingAcceptor | Provides access to replication delivery on the destination servers.
ReplicationProject | Provides methods and properties to administer projects.
ReplicationRoute | Provides methods and properties to administer replication routes.
ReplicationSchedule | Provides access to the schedule of when and how often replications are run.
ReplicationServer | Provides methods and properties to administer the Content Deployment server.

You must have at least Site Server Publishing operator privileges to call a method or read a property. In some cases you must have Site Server Publishing administrator privileges. These latter cases are noted in the Remarks section of the method or property.


ReplicationClient

The ReplicationClient object provides finer control when replicating individual files. The ReplicationClient object does not use the Content Deployment server to perform replications. The following table briefly describes the ReplicationClient object's methods and properties.

Method | Description
Abort | Cancels pending transactions on each destination server defined for the project
Commit | Applies transactions on each destination server defined for the project
Connect | Initiates a connection to each destination server defined for the project
DeleteFile | Deletes a file on each destination server defined for the project
Disconnect | Disconnects from all destination servers defined for the project
GetExtendedErrorInfo | Returns additional error information.
Initialize | Initializes the ReplicationClient object
SendFile | Sends a file to each destination server defined for the project
SendFiles | Sends an array of files to each destination server defined for the project
Property | Description
ACLs | Access Control Lists
FastMode | Whether the replication is run in fast mode
Force | Whether to force replication
NumDestinations | Total number of destination servers
SkipLockedFiles | Whether to try to send locked files to each destination server defined for the project

Note You cannot use ReplicationClient's methods or properties to replicate files to the same host or to replicate a metabase project.


CLSID and ProgID

ReplicationClient CLSID

B24F0373-9692-11D0-BAD5-00C04FD7082F

ReplicationClient ProgID

CrsApi.ReplicationClient

ReplicationClient is a dual-interface COM object.


Creating a ReplicationClient Object

You create a new ReplicationClient object by calling the CreateObject method, as in the following example, where ReplClient is the name you give to the new ReplicationClient object:

dim ReplClient
Set ReplClient = CreateObject("CrsApi.ReplicationClient")

... 'Do some replications
'Release Client object
set ReplClient = Nothing

Once you have access to the ReplicationClient object, you must call the Initialize method, unless the object is created through a ReplicationProject object, in which case you need not call Initialize.


ReplicationClient Methods

© 1997-1998 Microsoft Corporation. All rights reserved.


Abort Method

This method cancels any pending transactions on the destination servers during the current connection.

Syntax

ReplicationClient.Abort

Remarks

Use this method to interrupt any replication session (a session where you call the Connect method to initiate the session, perform replications with either the SendFile method or the DeleteFile method, and sever the connection with the Disconnect method). This method has no effect if the Content Deployment server is running in “connectionless” mode (you are issuing individual SendFile and DeleteFile method calls where they transparently perform the connect and disconnect operations).

This method sets ReplicationInstance.State property to REPL_STATE_ABORTED.

Example

The following example connects to the destination servers and deletes a file. If the deletion fails, it cancels any pending operations and exits.

Option Explicit
On Error Resume Next

dim ReplClient
set ReplClient = CreateObject("CrsApi.ReplicationClient")
ReplClient.Initialize("Project1")

'You can roll your own replication scheme by:
'1. Getting a list of ReplicationItem objects with the
' ReplicationProject.EnumItemsEnumItems method.
'2. Iterate through the list, replicating files
' (Item objects whose Attribute property does not have the
'  Directory bit set).
'The following code skips these preliminary steps.

do while True
  Err.Clear
  ReplClient.Connect
  if Err.Number > 0 then
    Wscript.Echo "Error connecting to destination servers."
    exit do
  end if

  ReplClient.DeleteFile("oldfile.htm")
  if Err.Number > 0 then
    Wscript.Echo "Error deleting oldfile.htm"
    ReplClient.Abort
    exit do
  end if

  ReplClient.SendFile("newfile.htm")
  if Err.Number > 0 then
    Wscript.Echo "Error sending newfile.htm"
    ReplClient.Abort
    exit do
  end if

  'Normally you would be checking for CRS_ERROR_NO_MORE_ITEMS
  exit do
loop
'Release Client object
set ReplClient = Nothing

See Also

ReplicationClient.Commit


Commit Method

This method applies transactions on each destination server defined for the project.

Syntax

ReplicationClient.Commit

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

Use this method to apply any pending replications in a replication session (a session where you call the Connect method to initiate the session, perform replications with either the SendFile method or the DeleteFile method, and sever the connection with the Disconnect method). This method has no effect if the Content Deployment server is running in “connectionless” mode (you are issuing individual SendFile and DeleteFile method calls where they transparently do the connect and disconnect operations).

Example

The following example opens project named Project1, deletes a file, sends a file, and commits the transactions.

Option Explicit
On Error Resume Next

dim Client
set Client = CreateObject("CrsApi.ReplicationClient")
Client.Initialize("Project1")

Client.Connect

Client.DeleteFile("oldfile.htm")
Client.SendFile("newfile.htm")

Client.Commit
...
Client.Disconnect

'Release Client object
set Client = Nothing

See Also

ReplicationClient.Abort


Connect Method

This method initiates connections to each destination server defined for the project.

Syntax

ReplicationClient.Connect

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

If you use the SendFile and DeleteFile methods without the Connect and Disconnect methods, SendFile and DeleteFile each perform their own connecting and disconnecting to the destination server. Connect and Disconnect let you avoid this overhead, which can be significant when updating more than a few files.

Example

The following example connects to Project1, sends some files, and disconnects.

Option Explicit
On Error Resume Next

dim Client
set Client = CreateObject("CrsApi.ReplicationClient")
Client.Initialize("Project1")
Client.Connect
Client.SendFile("newfile.htm")
...
Client.Disconnect

'Release Client object
set Client = Nothing

See Also

ReplicationClient.Disconnect


DeleteFile Method

This method deletes a file on each destination server defined for the project, using the replication settings defined for the ReplicationClient object.

Syntax

ReplicationClient.DeleteFile(File)

Parameters

File

The file to delete. The file path should not include the full path (the path should only be relative to the project).

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

If a connection is already established, this method deletes the remote file. If there is no connection to a destination server, this method connects, deletes the remote file, and then disconnects. If transaction processing is turned on at the destination servers, the destination servers do not delete the file until the Content Deployment replication server issues either a Commit method or a Disconnect method.

Example

The following example deletes the file Oldfile.htm on the Project1 destination servers.

Option Explicit
On Error Resume Next

dim Client
set Client = CreateObject("CrsApi.ReplicationClient")
Client.Initialize("Project1")
Client.DeleteFile("oldfile.htm")

'Release Client object
set Client = Nothing

See Also

ReplicationClient.SendFile, ReplicationClient.GetExtendedErrorInfo


Disconnect Method

This method closes the connections to the destination servers defined for the project.

Syntax

ReplicationClient.Disconnect

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

Disconnect does an implicit Commit operation, so you need not call Commit after a Disconnect.

If you use the SendFile and DeleteFile methods without the Connect and Disconnect methods, SendFile and DeleteFile each perform their own connecting and disconnecting to the destination server. Connect and Disconnect let you avoid this overhead, which can be significant when updating more than a few files.

Example

The following example deletes the file Oldfile.htm and sends the file Newfile.htm on the Project1 destination servers.

Option Explicit
On Error Resume Next

dim Client
set Client = CreateObject("CrsApi.ReplicationClient")
Client.Initialize("Project1")
Client.Connect
Client.DeleteFile("oldfile.htm")
Client.SendFile("newfile.htm")
Client.Disconnect

'Release Client object
set Client = Nothing

See Also

ReplicationClient.Connect


GetExtendedErrorInfo Method

This method retrieves any available ReplicationClient error information.

Syntax

ReplicationClient.GetExtendedErrorInfo

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

ReplicationClient.GetExtendedErrorInfo returns an array of ReplicationClientError objects. GetExtendedErrorInfo returns a maximum of one error per destination. GetExtendedErrorInfo only returns errors associated with replication destinations; it does not return other errors, such as invalid parameter errors or object not initialized. These types of errors are returned in an Err object.

If the previous ReplicationClient method or property statement was successful, GetExtendedErrorInfo returns an empty array. Therefore, you should check for an empty array before attempting to access the array elements.

Example

The following example is an error subroutine that you can call when encountering an error condition following a call to a ReplicationClient method.

sub CError

  dim ClientError
  set ClientError = ReplClient.GetExtendedErrorInfo

  'If the ClientError array isn't empty, loop through it
  'and display each error
  dim NumElements = Ubound(ClientError)
  if NumElements > 0 then
    Wscript.Echo "The following errors were received: "
    dim i
    for i = 0 to NumElements
    Wscript.Echo ClientError(i).ErrorCode
    Next
  end if
End Sub

See Also

ReplicationClientError


Initialize Method

This method initializes the client and sets project parameters.

Syntax

ReplicationClient.Initialize(Project)

Parameters

Project

The Content Deployment project to use for this replication client.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

This method must be the first method called on the replication client, unless the object is created through the ReplicationProject object, in which case this method does not need to be called.

Example

The following initializes the existing Project1.

Option Explicit
On Error Resume Next

dim Client
Set Client = CreateObject("CrsApi.ReplicationClient")
Client.Initialize("Project1")

'Release Client object
set Client = Nothing

See Also

ReplicationProject.Start, ReplicationServer.OpenProject


SendFile Method

This method sends a file to each destination server defined for the project.

Syntax

ReplicationClient.SendFile(File)

Parameters

File

The file to replicate. The file path should not include the full path, but should be relative to the project.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

If a connection has already been established, this function sends the file. Otherwise, it connects, sends the file, and disconnects, committing the file. If transaction processing is turned on at the destination servers, then the file transaction is not applied until either a Commit or Disconnect is called.

Since this method does not go through the Content Deployment service on the source computer, the replication information is not logged on the source computer.

Note

You cannot run both the SendFile method and a replication on a source computer at the same time. If you attempt to run both, Content Deployment refuses and issues an error message.

Example

The following example sends the file Newfile.htm to the Project1 destination servers.

Option Explicit
On Error Resume Next

dim Client
set Client = CreateObject("CrsApi.ReplicationClient")
Client.Initialize("Project1")
Client.SendFile("Newfile.htm")
'Release Client object
set Client = Nothing

See Also

ReplicationClient.DeleteFile, ReplicationClient.GetExtendedErrorInfo, SendFiles, ReplicationProject.EnumDestination


SendFiles Method

This method sends an array of files to each destination server defined for the project.

Syntax

ReplicationClient.SendFiles(FileArray)

Parameters

FileArray

The array of files to replicate. The file paths should not include a full path, but should be relative to the project.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

If a connection has already been established, this method sends the files. Otherwise, it connects, sends the files, and disconnects, committing the files. If transaction processing is turned on at the destinations, then the file transaction is not applied until either a Commit or Disconnect is called.

Since this method does not go through the Content Deployment server on the source machine, the replication information is not logged on the source.

Note

You cannot run both the SendFiles method and a replication on a source machine at the same time. If you attempt to run both, Content Deployment refuses and issues an error message.

Example

The following example sends the files Newfile1.htm through Newfile10.htm to Project1's destination servers.

Option Explicit
On Error Resume Next

const NumFiles = 10

dim Client
set Client = CreateObject("CrsApi.ReplicationClient")
Client.Initialize("Project1")

dim i, FileList[NumFiles - 1]

for i = 0 to NumFiles
  FileList[i] = "Newfile" & i & ".htm"
next

Client.SendFiles FileList

'Release Client object
set Client = Nothing

See Also

DeleteFile, GetExtendedErrorInfo, SendFile, ReplicationProject.EnumDestination


ReplicationClient Properties

© 1997-1998 Microsoft Corporation. All rights reserved.


ACLs Property

This property specifies whether access control lists (ACLs) associated with replicated files are replicated along with the files to the destination servers.

Syntax

ReplicationClient.ACLs [= SendACLs]

SendACLs

If True, the Content Deployment server sends the file ACLs associated with the files to the destination servers. If False, the ACLs are not replicated.

Remarks

You must have Site Server Publishing administrator privileges on the server to get or set this property.

You can set this property at any time, but the new settings do not take effect until a connect operation, including SendFile in connectionless mode, is performed.

Example

The following example saves the current ACLs property setting, sets the ACLs property to True (replicate the ACLs with their associated files), and resets the ACLs when it's done.

Option Explicit
On Error Resume Next

dim Client
set Client = CreateObject("CrsApi.ReplicationClient")
dim ACLs
Client.Initialize("Project1")
ACLs = Client.ACLs
Client.ACLs = True
Client.DeleteFile("oldfile.htm")
Client.SendFile("newfile.htm")
Client.ACLs = ACLs

'Release Client object
set Client = Nothing

See Also

ReplicationClient.Connect


FastMode Property

This property specifies whether the connection from the Content Deployment server to the destination servers is reliable.

Syntax

ReplicationClient.FastMode [=Mode]

Parameters

Mode

If True, fast replication mode is enabled; if False, fast replication mode is disabled.

Remarks

You should use fast replication mode unless the connection to the destination servers is unreliable.

You must have Site Server Publishing administrator privileges on the server to get or set this property.

This property is initially set from the project description during a call to ReplicationClient.Initialize.

You can set this property at any time, but the new settings do not take effect until a connect operation, including SendFile in connectionless mode, is performed.

Example

The following example initializes Project1 and enables fast replication mode.

Option Explicit
On Error Resume Next

dim Client
set Client = CreateObject("CrsApi.ReplicationClient")
Client.Initialize("Project1")
Client.FastMode = True

'Release Client object
set Client = Nothing

See Also

ReplicationClient.Initialize


Force Property

This property forces the replication of files from the source servers to the destination servers.

Syntax

ReplicationClient.Force [=Force]

Parameters

Force

If True, force the replication of all files. If False, do not force the replication.

Remarks

Normally files are only replicated from the source servers to the destination servers when the files on the source servers are newer than the files on the destination servers. The Force property specifies that the Content Deployment server replicates all files, regardless of the time and date stamp.

You must have Site Server Publishing administrator privileges on the server to get or set this property.

This property is initially set from the project description during a call to ReplicationClient.Initialize.

You can set this property at any time, but the new settings do not take effect until a connect operation, including SendFile in connectionless mode, is performed.

Example

The following example enables the forcing of Project1 replication files.

Option Explicit
On Error Resume Next

dim Client
set Client = CreateObject("CrsApi.ReplicationClient")
Client.Initialize("Project1")
Client.Force = True

'Release Client object
set Client = Nothing

See Also

ReplicationClient.Commit


NumDestinations Property

This read-only property specifies the number of destination servers to which the Content Deployment server replicates files.

Syntax

ReplicationClient.NumDestinations

Remarks

You must have Site Server Publishing administrator privileges on the server to get or set this property.

Example

The following example displays a message with the number of destination servers.

Option Explicit
On Error Resume Next

dim Client
set Client = CreateObject("CrsApi.ReplicationClient")
Client.Initialize("Project1")
dim NumDestinations
NumDestinations = Client.NumDestinations
if 1 = NumDestinations then
  Wscript.Echo "There is 1 destination."
else
  Wscript.Echo "There are " & NumDestinations & " destinations."
end if
'Release Client object
set Client = Nothing

See Also

ReplicationProject.EnumDestination


SkipLockedFiles Property

This property specifies whether to try to send locked files to each destination server defined for the project.

Syntax

ReplicationClient.SkipLockedFiles [= Skip]

Parameters

Skip

If True, do not try to send locked files; if False, try to send locked files.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

Example

The following example tries to send any locked files to Project1's destination servers.

Option Explicit
On Error Resume Next

dim Client
set Client = CreateObject("CrsApi.ReplicationClient")
Client.Initialize("Project1")

Client.SkipLockedFiles = False

'Release Client object
set Client = Nothing

See Also

ReplicationClient.DeleteFile, ReplicationClient.GetExtendedErrorInfo, ReplicationProject.EnumDestination


ReplicationClientError

The ReplicationClientError object provides ReplicationClient error information to your Content Deployment applications.

The following table briefly describes the ReplicationClientError object's properties.

Property | Description
Description | Textual description of error
Destination | Destination computer of error
ErrorCode | Content Deployment or system error code
FileName | Filename associated with the error
Project | Project in which error occurred
Source | Source machine on which error occurred


CLSID and ProgID

ReplicationClientError CLSID

6AF9D110-9F37-11d0-BADA-00C04FD7082F

ReplicationClientError ProgID

CrsApi.ReplicationClientError

ReplicationClientError is a dual-interface COM object.


Accessing ReplicationClientError Objects

You access an existing ReplicationClientError object by calling the ReplicationClient.GetExtendedErrorInfo method, as in the following example, where ReplError is the name of the ReplicationClientError object:

Option Explicit
On Error Resume Next

dim ReplClient
set ReplClient = CreateObject("CrsApi.ReplicationClient")
ReplClient.Initialize("Project1")
if err.Number > 0 then
  dim ReplError
  set ReplError = ReplClient.GetExtendedErrorInfo

  'If the ReplError array isn't empty, loop through it
  'and display each error
  dim NumElements = Ubound(ReplError)

  if NumElements > 0 then
    Wscript.Echo "The following errors were received: "
    dim i
    for i = 0 to NumElements
    Wscript.Echo ReplError(i).ErrorCode
    Next
  end if
end if

'Release objects
set ReplError  = Nothing
set ReplClient = Nothing


ReplicationClientError Properties

© 1997-1998 Microsoft Corporation. All rights reserved.


Description Property

This property is a textual description of the error.

Syntax

ReplicationClientError.Description

Remarks

You get access to the ReplicationClientError object by calling the ReplicationClient.GetExtendedErrorInfo method, which returns an array of ReplicationClientError objects. Since the array is empty when no error information is available, be sure to do bounds checking before accessing the array.

Example

The following example attempts to initialize the project named Project1. If it cannot, it displays any error codes and error descriptions that Content Deployment returns.

Option Explicit
On Error Resume Next

dim Client
set Client = CreateObject("CrsApi.ReplicationClient")
Client.Initialize("Project1")
if err.Number > 0 then
  dim ClientError
  Set ClientError = Client.GetExtendedErrorInfo
end if
'If the ClientError array isn't empty, loop through it
'and display each error
dim NumElements = Ubound(ClientError)
if NumElements > 0 then
  dim i
  for i = 0 to NumElements
    Wscript.Echo "Error code: " & ClientError(i).ErrorCode
    Wscript.Echo "Description: " & ClientError(i).Description
  Next
  end if
'Release objects
set ClientError = Nothing
set Client      = Nothing

See Also

ReplicationClient.GetExtendedErrorInfo


Destination Property

This specifies the destination server where the error was encountered.

Syntax

ReplicationClientError.Destination

Example

The following example displays the names of the servers where the errors were encountered.

Option Explicit
On Error Resume Next

dim Client
set Client = CreateObject("CrsApi.ReplicationClient")
Client.Initialize("Project1")
if err.Number > 0 then
  dim ClientError
  set ClientError = Client.GetExtendedErrorInfo
end if
'If the ClientError array isn't empty, loop through it
'and display each error
dim NumElements = Ubound(ClientError)
if NumElements > 0 then
  dim i
  Wscript.Echo "Could not initialize Project1 on the destination(s):"
  for i = 0 to NumElements
    Wscript.Echo ClientError(i).Destination
  Next
end if
'Release objects
set ClientError = Nothing
set Client      = Nothing

See Also

ReplicationClient.GetExtendedErrorInfo


ErrorCode Property

This property specifies the error code that the Content Deployment server setswhen a method fails.

Syntax

ReplicationClientError.ErrorCode

Remarks

See Error Codes for a description of each error code.

Example

The following example initializes the project. If any errors occur during initialization, the example displays the error codes.

Option Explicit
On Error Resume Next

dim Client
set Client = CreateObject("CrsApi.ReplicationClient")
Client.Initialize("Project1")
dim ClientError
if err.Number > 0 then
  set ClientError = Client.GetExtendedErrorInfo
end if
'If the ClientError array isn't empty, loop through it
'and display each error
dim NumElements = Ubound(ClientError)
if NumElements > 0 then
  redim preserve ClientError(NumElements)
  Wscript.Echo "The following errors were received:"
  dim i
  for i = 0 to NumElements
    Wscript.Echo "Error code: " & ClientError(i).ErrorCode
    Wscript.Echo "Description: " & ClientError(i).Description
  Next
end if
'Release objects
set ClientError = Nothing
set Client      = Nothing

See Also

ReplicationClient.GetExtendedErrorInfo


FileName Property

This property specifies the name of the file associated with the error.

Syntax

ReplicationClientError.FileName

Remarks

You must have Site Server Publishing administrator privileges on the server to get or set this property.

Example

The following example initializes the project. If any errors occur during initialization, the error codes are echoed to the Web page. If a file is associated with the error, the file name is also displayed to the Web page.

Option Explicit
On Error Resume Next

dim Client
set Client = CreateObject("CrsApi.ReplicationClient")
Client.Initialize("Project1")
Client.DeleteFile("ProjectTest\*.htm")

if err.Number > 0 then
  dim ClientError
  set ClientError = Client.GetExtendedErrorInfo
end if

'If the ClientError array isn't empty, loop through it
'and display each error
dim NumElements
NumElements = Ubound(ClientError)

if NumElements > 0 then
  dim i
  for i = 0 to NumElements
    Wscript.Echo "File:  " & ClientError(i).FileName
    Wscript.Echo "Error: " & ClientError(i).ErrorCode
  Next
end if

'Release objects
set ClientError = Nothing
set Client      = Nothing

See Also

ReplicationClient.GetExtendedErrorInfo


Project Property

This property specifies the Project associated with the error.

Syntax

ReplicationClientError.Project

Remarks

You must have Site Server Publishing administrator privileges on the server to get or set this property.

Example

The following example initializes the project. If any errors occur during initialization, the project name, which should be Project1, and error codes are echoed to the Web page.

Option Explicit
On Error Resume Next

dim Client
set Client = CreateObject("CrsApi.ReplicationClient")
Client.Initialize("Project1")
if err.Number > 0 then
  dim ClientError
  set ClientError = Client.GetExtendedErrorInfo
end if
'If the ClientError array isn't empty, loop through it
'and display each error
dim NumElements = Ubound(ClientError)

if NumElements > 0 then
  dim Project
  Project = ClientError(0).Project
  Wscript.Echo "Failed to initialize project: " & Project
  Wscript.Echo "The following errors were received"
  dim i
  for i = 0 to NumElements
    Wscript.Echo "Error code:  " & ClientError(i).ErrorCode
    Wscript.Echo "Description: " & ClientError(i).Description
  Next
end if
'Release objects
set ClientError = Nothing
set Client      = Nothing

See Also

ReplicationClient.GetExtendedErrorInfo


Source Property

This property specifies the source computer where the error occurred.

Syntax

ReplicationClientError.Source[=Source]

Parameters

Source

The source computer where the error occurred. The source computer should be the computer where the client was created.

Remarks

You must have Site Server Publishing administrator privileges on the server to get or set this property.

Example

The following example initializes the project. If any errors occur during initialization, the example displays the source computer name where the client was created.

Option Explicit
On Error Resume Next

dim Client
set Client = CreateObject("CrsApi.ReplicationClient")
Client.Initialize("Project1")
if err.Number > 0 then
  dim ClientError
  set ClientError = Client.GetExtendedErrorInfo
  'If the ClientError array isn't empty, loop through it
  'and display each error
  dim NumElements
  NumElements = Ubound(ClientError)
  if NumElements > 0 then
    dim Project
    Project = ClientError(0).Project
    dim Source
    Source = ClientError(0).Source
    Wscript.Echo "Failed to initialize project: " & Project
    Wscript.Echo "On machine: " & Source
    Wscript.Echo "The following errors were received"
    dim i
    for i = 0 to NumElements
    Wscript.Echo "Error code: " & ClientError(i).ErrorCode
    Wscript.Echo "Description: " & ClientError(i).Description
    Next
  end if
end if
'Release objects
set ClientError = Nothing
set Client      = Nothing

See Also

ReplicationClient.GetExtendedErrorInfo


ReplicationEventSinkConfig

The ReplicationEventSinkConfig object defines the configuration of an event sink.

Note

You can create you own event sink by writing a COM DLL implementation of the ReplicationEventSink object.

The following table briefly describes the ReplicationEventSinkConfig object's methods and properties.

Method | Description
Commit | Commits changes to the event sink.
IsRegisteredForEvent | Whether event sink listens for a given event.
RegisterForEvent | Specifies an event for which an event sink listens.
UnRegisterForEvent | Specifies an event for which an event sink no longer listens.
Property | Description
CLSID | CLSID or ProgId of the event sink.
DataSource | Data source name (DSN) of the database.
Disabled | Specifies whether event sink is disabled.
EventLifetime | The number of days to store the event.
Name | Friendly name for the event sink.
Password | Password for the local database or store-and-forward event sink.
ProjectFilter | Events for which all project event sinks listen.
ProviderCLSID | ProgID or CLSID of the provider for the store-and-forward event sink.
Server | Server to which the store-and-forward event sink forwards events.
UserName | User name for the local database or store-and-forward event sink.

Note

You must stop and restart the Content Replication server for any event sink changes to take effect. Use the ReplicationServer.Stop method to stop the server and the ReplicationServer.Start method to start the server.


CLSID and ProgID

ReplicationEventSinkConfig CLSID

66D6D7FD-22D2-11D0-9B98-00C04FD5CD09

ReplicationEventSinkConfig ProgID

CrsApi.ReplicationEventSinkConfig

ReplicationEventSinkConfig is a dual-interface COM object.


Creating a ReplicationEventSinkConfig Object

You create a new ReplicationEventSinkConfig object (event sink) by calling the ReplicationServer.AddEventSink method, as in the following example, where ReplSink is the name you give to the new ReplicationEventSink object:

On Error Resume Next
dim ReplServer

set ReplServer = CreateObject("CrsApi.ReplicationServer")
dim ReplSink
set ReplSink = ReplServer.AddEventSink("TestSink")
...

'Release objects
set ReplSink   = Nothing
set ReplServer = Nothing


Accessing ReplicationEventSinkConfig Objects

You access an existing ReplicationEventSinkConfig object (event sink) by calling the ReplicationServer.EnumEventSinks method, as in the following example, where ReplSink is the name of the ReplicationEventSinkConfig object:

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim ReplSink

do while True
  'Clear any error text
  Err.Clear
  'Get an event sink
  set ReplSink = ReplServer.EnumEventSinks(Iterator)
  'Quit if empty object returned
  if IsEmpty(ReplSink) then
    Wscript.Echo "Empty object returned for event sink"
    exit do
  end if

'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do
  'If some other error, display the number and exit
  if ReplError > 0 then
   Wscript.Echo "Error: " & ReplError
  end if
  if ReplSink.CLSID = "NT" then
    dim GotIt
    GotIt = True
    ReplSink.ProjectFilter("Project1")
  end if
Loop

if GotIt = False then
  Wscript.Echo "The event sink monitor is not monitoring events."
else
  Wscript.Echo "The event sink monitor is monitoring events."
end if

'Release objects
set ReplSink   = Nothing
set ReplServer = Nothing


ReplicationEventSinkConfig Methods

© 1997-1998 Microsoft Corporation. All rights reserved.


Commit Method

This method commits changes to the event sink.

Syntax

ReplicationEventSinkConfig.Commit

Remarks

You must have Site Server Publishing administrator privileges on the server to get or set this property.

You must commit any event sink changes and stop and restart the Content Deployment server before the event sink changes take effect. Use the ReplicationServer.Stop method to stop the server and the ReplicationServer.Start method to start the server.

Example

The following example adds Project1's events to those that the NT event sink monitors, commits the change, and stops and restarts the server.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim EvSink

do while True
  'Clear any error text
  Err.Clear
  'Get an event sink
  set EvSink = ReplServer.EnumEventSinks(Iterator)
  'Quit if empty object returned (no more instances)
  if IsEmpty(EvSink) then exit do
  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do
  if EvSink.CLSID = "NT" then
    EvSink.ProjectFilter("Project1")
    EvSink.Commit
    ReplServer.Stop
    ReplServer.Start
  end if
Loop

'Release objects
set EvSink     = Nothing
set ReplServer = Nothing

See Also

ReplicationServer.AddEventSink, ReplicationServer.EnumEventSinks


IsRegisteredForEvent Method

This method determines whether an event sink monitors an event.

Syntax

ReplicationEventSinkConfig.IsRegisteredForEvent(Event)

Parameters

Event

The event in question.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

See Crsmsg.h for the list of predefined events.

Example

The following example displays the names of the event sinks that monitor CRS_EVENT_RECEIVING_ACL events.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17
const CRS_EVENT_RECEIVING_ACL  = 0&40003786

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0

dim EvSink
On Error Resume Next
do while True
  'Clear any error text
  Err.Clear
  'Get an event sink
  set EvSink = ReplServer.EnumEventSinks(Iterator)

  'Quit if empty object returned (no more instances)
  if IsEmpty(EvSink) then exit do

  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  dim EvMon
  EvMon = EvSink.IsRegisteredForEvent(CRS_EVENT_RECEIVING_ACL)
  if EvMon = True then
    Wscript.Echo "Event sink " & EvSink.Name & " is monitoring" & " CRS_EVENT_RECEIVING_ACL events"
  end if
Loop

'Release objects
set EvSink     = Nothing
set ReplServer = Nothing

See Also

ReplicationServer.AddEventSink, ReplicationServer.EnumEventSinks


RegisterForEvent Method

This method specifies an event for which an event sink listens.

Syntax

ReplicationEventSinkConfig.RegisterForEvent(Event)

Parameters

Event

The event with which the ReplicationEventSinkConfig object is interested.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

If the ProjectFilter property is True, registering from an event from any of a project's event sinks also registers the event from all of the other project event sinks. If the ProjectFilter property is False, the registering only affects the current event sink.

See Crsmsg.h for the list of predefined events.

Example

The following example registers the NT event sink to receive file sent events.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17
const CRS_EVENT_SENT_FILE    = 0&4000377A

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0

dim EvSink
On Error Resume Next
do while True
  'Clear any error text
  Err.Clear
  'Get an event sink
  set EvSink = ReplServer.EnumEventSinks(Iterator)

  'Quit if empty object returned (no more instances)
  if IsEmpty(EvSink) then exit do

  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  if EvSink.CLSID = "NT" then
    EvSink.RegisterForEvent(CRS_EVENT_SENT_FILE)
  end if
Loop

'Release objects
set EvSink     = Nothing
set ReplServer = Nothing

See Also

ProjectFilter, UnregisterForEvent, ReplicationServer.AddEventSink, ReplicationServer.EnumEventSinks


UnRegisterForEvent Method

This method specifies an event for which an event sink no longer listens.

Syntax

ReplicationEventSinkConfig.UnRegisterForEvent[=Event]

Parameters

Event

The event with which the event sink is no longer interested.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

If the ProjectFilter property is True, unregistering from an event from any of a project's event sinks also unregisters the event from all of the other project event sinks. If the ProjectFilter property is False, the unregistering only affects the current event sink.

Example

The following example instructs the NT event sink to no longer receive file sent events.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17
const CRS_EVENT_SENT_FILE    = 0&4000377A

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim EvSink

do while True
  'Clear any error text
  Err.Clear
  'Get an event sink
  set EvSink = ReplServer.EnumEventSinks(Iterator)

  'Quit if empty object returned (no more instances)
  if IsEmpty(EvSink) then exit do

  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  if EvSink.CLSID = "NT" then
    EvSink.UnRegisterForEvent(CRS_EVENT_SENT_FILE)
    exit do
  end if
Loop

'Release objects
set EvSink     = Nothing
set ReplServer = Nothing

See Also

ProjectFilter, RegisterForEvent, ReplicationServer.AddEventSink , ReplicationServer.EnumEventSinks


ReplicationEventSinkConfig Properties

© 1997-1998 Microsoft Corporation. All rights reserved.


CLSID Property

This property specifies either the CLSID or ProgID of the event sink.

Syntax

ReplicationEventSinkConfig.CLSID[=ID]

Parameters

ID

The ProgID or CLSID of the event sink. The following ProgIDs are defined for the built-in event sinks:

CRSLocalEvents

The local OLEDB event sink.

Crssink

The local store and forward Content Deployment event sink.

Mail

The event sink for mail.

NT

The NT event sink.

Remarks

You must have Site Server Publishing administrator privileges on the server to get or set this property.

The ReplicationEventSinkConfig object can be either a user-defined event sink object or one of the installed Content Deployment event sinks, such as the OLEDB event sink or the Content Deployment event sink. You must set the CLSID property when you create your own event sink.

Example

The following example adds Project1's events to those that the NT event sink monitors and commits the change.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim EvSink

do while True
  'Clear any error text
  Err.Clear
  'Get an event sink
  set EvSink = ReplServer.EnumEventSinks(Iterator)

  'Quit if empty object returned (no more instances)
  if IsEmpty(EvSink) then exit do

  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  dim CLSID
  CLSID = EvSink.CLSID
  if CLSID = "NT" then
    EvSink.ProjectFilter("Project1")
    EvSink.Commit
    exit do
  end if
Loop

'Release objects
set EvSink     = Nothing
set ReplServer = Nothing

See Also

ReplicationServer.AddEventSink, ReplicationServer.EnumEventSinks


DataSource Property

This property specifies the data source name (DSN) of the database.

Syntax

ReplicationEventSinkConfig.DataSource[=DSN]

Parameters

DSN

The DSN for the ReplicationEventSinkConfig object.

Remarks

This property is required for the local database event sink, CRSLocalEvents, which is the only event sink that uses this property.

You must have Site Server Publishing administrator privileges on the server to set this property.

Example

The following example displays the DSN for the current event sinks.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim EvSink
dim Iterator
Iterator = 0

do while True
  'Clear any error text
  Err.Clear
  'Get an event sink
  set EvSink = ReplServer.EnumEventSinks(Iterator)
  'Quit if empty object returned (no more instances)
  if IsEmpty(EvSink) then exit do

  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  Wscript.Echo "The " & EvSink.Name & " has DNS: " & EvSink.DNS
Loop

'Release objects
set EvSink     = Nothing
set ReplServer = Nothing

See Also

ReplicationServer.AddEventSink, ReplicationServer.EnumEventSinks


Disabled Property

This property specifies whether the event sink is disabled.

Syntax

ReplicationEventSinkConfig.Disabled[=Disabled]

Parameters

Disabled

If True, the event sink is disabled; if False, the event sink is enabled.

Remarks

You must have Site Server Publishing administrator privileges on the server to get or set this property.

Example

The following example displays the disabled event sinks.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim EvSink

do while True
  'Clear any error text
  Err.Clear
  'Get an event sink
  set EvSink = ReplServer.EnumEventSinks(Iterator)

  'Quit if empty object returned (no more instances)
  if IsEmpty(EvSink) then exit do

  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  dim Disabled
  Disabled = EvSink.Disabled
  if Disabled = True then
    Wscript.Echo "Event sink " & EvSink.Name & " is disabled."
  end if
Loop

'Release objects
set EvSink     = Nothing
set ReplServer = Nothing

See Also

ReplicationServer.AddEventSink, ReplicationServer.EnumEventSinks


EventLifetime Property

This property specifies the number of days to store the event.

Syntax

ReplicationEventSinkConfig.EventLifetime[=Days]

Parameters

Days

The number of days to store the event.

0

Store the event indefinitely

n

Store the event n days.

Remarks

You must have Site Server Publishing administrator privileges on the server to get or set this property.

Example

The following example stores the local store-and-forward events indefinitely.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim EvSink

do while True
  'Clear any error text
  Err.Clear
  'Get an event sink
  set EvSink = ReplServer.EnumEventSinks(Iterator)

  'Quit if empty object returned (no more instances)
  if IsEmpty(EvSink) then exit do

  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  if EvSink.CLSID = "Crssink" then EvSink.Lifetime = 0
Loop

'Release objects
set EvSink     = Nothing
set ReplServer = Nothing

See Also

ReplicationServer.AddEventSink, ReplicationServer.EnumEventSinks


Name Property

This property specifies the friendly name for the event sink.

Syntax

ReplicationEventSinkConfig.Name[=Name]

Parameters

Name

The name of the event sink.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

Example

The following example displays the names of all of the event sinks.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17
const CRS_EVENT_RECEIVING_ACL  = 0&40003786

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

Wscript.Echo "The event sinks are:"

dim Iterator
Iterator = 0
dim EvSink

do while True
  'Clear any error text
  Err.Clear
  'Get an event sink
  set EvSink = ReplServer.EnumEventSinks(Iterator)

  'Quit if empty object returned (no more instances)
  if IsEmpty(EvSink) then exit do

  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  Wscript.Echo EvSink.Name
Loop

'Release objects
set EvSink     = Nothing
set ReplServer = Nothing

See Also

ReplicationServer.AddEventSink, ReplicationServer.EnumEventSinks


Password Property

This specifies the password for the local database or Content Deployment event sink.

Syntax

ReplicationEventSinkConfig.Password[=Password]

Parameters

Password

The password.

Remarks

You must have Site Server Publishing administrator privileges on the server to get or set this property.

Example

The following example sets the local database user name to CrsAdmin and the password to Oxymoron.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim EvSink

do while True
  'Clear any error text
  Err.Clear
  'Get an event sink
  set EvSink = ReplServer.EnumEventSinks(Iterator)

  'Quit if empty object returned (no more instances)
  if IsEmpty(EvSink) then exit do

  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  if EvSink.CLSID = "Crssink" then
    EvSink.Username = "CrsAdmin"
    EvSink.Password = "Oxymoron"
  end if
Loop

'Release objects
set EvSink     = Nothing
set ReplServer = Nothing

See Also

ReplicationEventSinkConfig.UserName, ReplicationServer.AddEventSink, ReplicationServer.EnumEventSinks


ProjectFilter Property

This property specifies the project that an event sink monitors.

Syntax

ReplicationEventSinkConfig.ProjectFilter[=Project]

Parameters

Project

The name of the project to monitor for events.

Remarks

You must have Site Server Publishing administrator privileges on the server to get or set this property.

The event sink gets all events for the specified project. If you subsequently call a RegisterForEvent method, only those events are monitored.

Example

The following example instructs the store-and-forward event sink to monitor events for the Project1 project.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim EvSink

do while True
  'Clear any error text
  Err.Clear
  'Get an event sink
  set EvSink = ReplServer.EnumEventSinks(Iterator)

  'Quit if empty object returned (no more instances)
  if IsEmpty(EvSink) then exit do

  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  if EvSink.CLSID = "Crssink" then
    EvSink.ProjectFilter("Project1")
  end if
Loop

'Release objects
set EvSink     = Nothing
set ReplServer = Nothing

See Also

RegisterForEvent, UnregisterForEvent, ReplicationServer.AddEventSink, ReplicationServer.EnumEventSinks


ProviderCLSID Property

This property specifies the ProgID or CLSID of the provider for the store-and-forward event sink.

Syntax

ReplicationEventSinkConfig.ProviderCLSID[=ProviderID]

Parameters

ProviderID

The ProgID or CLSID of the provider (the Content Deployment server from which files are replicated) for the store-and-forward event sink.

Remarks

You must have Site Server Publishing administrator privileges on the server to set this property.

Example

The following example displays the CLSID of provider for the store-and-forward event sink.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim EvSink

do while True
  'Clear any error text
  Err.Clear
  'Get an event sink
  set EvSink = ReplServer.EnumEventSinks(Iterator)

  'Quit if empty object returned (no more instances)
  if IsEmpty(EvSink) then exit do

  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  if EvSink.CLSID = "Crssink" then
    Wscript.Echo "CLSID for Crssink: " & EvSink.ProviderCLSID
  exit do
end if
Loop

'Release objects
set EvSink     = Nothing
set ReplServer = Nothing

See Also

ReplicationServer.AddEventSink, ReplicationServer.EnumEventSinks


Server Property

This property specifies the server to which the store-and-forward event sink forwards events.

Syntax

ReplicationEventSinkConfig.Server[=Server]

Parameters

Server

The server to which Content Deployment forwards events.

Remarks

You must have Site Server Publishing administrator privileges on the server to get or set this property.

Example

The following example displays the name of the server to which the store-and-forward event sink forwards events.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim EvSink

do while True
  'Clear any error text
  Err.Clear
  'Get an event sink
  set EvSink = ReplServer.EnumEventSinks(Iterator)

  'Quit if empty object returned (no more instances)
  if IsEmpty(EvSink) then exit do

  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  if EvSink.CLSID = "Crssink" then
    Wscript.Echo "Crssink forwards to server " & EvSink.Server
    exit do
  end if
Loop

'Release objects
set EvSink     = Nothing
set ReplServer = Nothing


UserName Property

This property specifies the user name for the local database or store-and-forward event sink.

Syntax

ReplicationEventSinkConfig.UserName[=UserName]

Parameters

UserName

The name of the user.

Remarks

You must have Site Server Publishing administrator privileges on the server to get or set this property.

Example

The following example sets the local database user name to CrsAdmin and the password to Oxymoron.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim EvSink

do while True
  'Clear any error text
  Err.Clear
  'Get an event sink
  set EvSink = ReplServer.EnumEventSinks(Iterator)

  'Quit if empty object returned (no more instances)
  if IsEmpty(EvSink) then exit do

  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  if EvSink.CLSID = "Crssink" then
    EvSink.Username = "CrsAdmin"
    EvSink.Password = "Oxymoron"
  end if
Loop
'Release objects
set EvSink     = Nothing
set ReplServer = Nothing

See Also

Password, ReplicationServer.AddEventSink , ReplicationServer.EnumEventSinks


ReplicationInstance

The ReplicationInstance object provides access to individual replication instances. It is most often used to query and report back information about the results of a replication. The object defines the following methods and properties (all properties are read-only):

Method | Description
Cancel | Cancels the running replication
Query | Issues a query to update replication information
Property | Description
BytesReceived | Number of bytes received
BytesSent | Number of bytes sent
EndTime | Replication ending time
FilesErrored | Number of files in error
FilesErroredBytes | Number of bytes associated with the files in error
FilesMatched | Number of files matched
FilesMatchedBytes | Number of bytes associated with the files matched
FilesReceived | Number of files received
FilesSent | Number of files sent
Flags | Flags with which replication was started
ID | Replication ID
Name | Project name
StartTime | Replication starting time
State | Replication state
Status | Current status of the replication


CLSID and ProgID

ReplicationInstance CLSID

66D6D7F7-22D2-11D0-9B98-00C04FD5CD09

ReplicationInstance ProgID

CrsApi.ReplicationInstance

ReplicationInstance is a dual-interface COM object.


Accessing ReplicationInstance Objects

You access an existing ReplicationInstance object by calling the ReplicationProject.EnumReplications method, as in the following example, where ReplProject is the name of the project and ReplInst is the name you give to the ReplicationInstance object (this example only accesses completed replications. See the ReplicationInstance.State property for information on replication in other states):

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const REPL_STATE_COMPLETE    = 3
const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("Crsapi.ReplicationServer")
ReplServer.Initialize("")
dim ReplProject
set ReplProject = ReplServer.OpenProject("MyProject", OPEN_EXISTING_PROJECT)

Dim ReplInst
dim Iterator
Iterator = 0
dim ReplError

do while True
  'Clear any error text
  Err.Clear
  'Get the next replication instance
  set ReplInst = ReplProject.EnumReplications(REPL_STATE_COMPLETE, Iterator)

  'Display error message and quit if empty object returned
  if IsEmpty(ReplInst) then
    Wscript.Echo "Empty replication instance returned."
    exit do
  end if

  'Quit if "No more items" error
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  'Now you have a valid replication instance
  ...

Loop

'Release objects
set ReplInst    = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing

Note

You can access the replication instances of any or all of the projects on a server by using the ReplicationServer.EnumInstances method.

Once you have an instance of a ReplicationInstance object, use the ReplicationInstance.Query method to ensure that you have the latest information.


ReplicationInstance Methods

© 1997-1998 Microsoft Corporation. All rights reserved.


Cancel Method

This method cancels a replication.

Syntax

ReplicationInstance.Cancel

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

Example

The following example cancels and displays the names of the replications where the status is other than NOERROR.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const REPL_STATE_RUNNING   = 2
const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")
dim ReplProject
set ReplProject = ReplServer.OpenProject("Project1", OPEN_EXISTING_PROJECT)

dim Iterator
Iterator = 0
dim Inst

Wscript.Echo "The following replications were cancelled:"

do while True
  'Clear any error text
  Err.Clear
  'Get a replication instance
  set ReplInst = ReplProject.EnumReplications(REPL_STATE_RUNNING, Iterator)

  'Quit if empty object returned (no more instances)
  if IsEmpty(ReplInst) then exit do

  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  dim ReplStatus
  ReplStatus = ReplInst.Status
  if Status <> NOERROR
    'Cancel it!
    ReplInst.Cancel
    Wscript.Echo ReplInst.Name
  end if

Loop

'Release objects
set ReplInst    = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

ReplicationProject.Cancel


Query Method

This method updates replication information.

Syntax

ReplicationInstance.Query

Remarks

You must call this method before you can obtain accurate information about a ReplicationInstance object's properties.

Example

The following example displays the information on the completed replications for Proj1.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17
const OPEN_EXISTING_PROJECT  = 2
const REPL_STATE_COMPLETE    = 3

Err.Clear

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("Proj1", OPEN_EXISTING_PROJECT)

dim Iterator
Iterator = 0
dim Inst

dim ID
ID = 0

do while True

  'Get replication instance
  set Inst = ReplProject.EnumReplications(REPL_STATE_COMPLETE, Iterator)

  'Quit if "No more items" error
  if Err.Number = CRS_ERROR_NO_MORE_ITEMS then exit do

  'Quit if Instance is empty
  if IsEmpty(Inst) then
   Wscript.Echo "Instance object is empty."
   exit do
  end if

  'Quit if Instance is NULL
  if IsNull(Inst) then
   Wscript.Echo "Instance object is Null."
   exit do
  end if

  'Quit if we're looking at the same instance
  if ID = Inst.ID then exit do

  'Update Instance properties
  Inst.Query

  'Display Instance properties:
  Wscript.Echo "Replication " & Inst.Name & " had the following info:"
  Wscript.Echo ""
  Wscript.Echo "Bytes received:  " & Inst.BytesReceived
  Wscript.Echo "Bytes sent:    " & Inst.BytesSent
  Wscript.Echo "Files errored:   " & Inst.FilesErrored
  Wscript.Echo "Files errored bytes: " & Inst.FilesErroredBytes
  Wscript.Echo "Files matched:   " & Inst.FilesMatched
  Wscript.Echo "Files matched bytes: " & Inst.FilesMatchedBytes
  Wscript.Echo "Files sent:    " & Inst.FilesSent
  Wscript.Echo "Flags:     " & Inst.Flags
  Wscript.Echo "ID:      " & Inst.ID
  Wscript.Echo "Start time:    " & Inst.StartTime
  Wscript.Echo "End time:    " & Inst.EndTime
  Wscript.Echo "Status:      " & Inst.Status

  'Save Instance ID
  ID = Inst.ID

  'Release Instance object
set Inst = Nothing

Loop

'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

ID


ReplicationInstance Properties

© 1997-1998 Microsoft Corporation. All rights reserved.


BytesReceived Property

This read-only property specifies the number of bytes received for the replication.

Syntax

ReplicationInstance.BytesReceived

Remarks

Example

See the Query method .

See Also

BytesSent, FilesReceived, FilesSent


BytesSent Property

This read-only property specifies the number of bytes sent during the replication.

Syntax

ReplicationInstance.BytesSent

Remarks

Example

See the Query method.

See Also

BytesReceived, FilesReceived, FilesSent


EndTime Property

This property specifies the time when the replication finished.

Syntax

ReplicationInstance.EndTime

Remarks

EndTime fails and succeeds depending upon the state of the replication. The following table explains this behavior:

State | ReplicationInstance.StateProperty Value | EndTime Behavior
Starting | 1 | Sets Err.Number to E_FAIL
Running | 2 | Sets Err.Number to E_FAIL
Receiving | 6 | Sets Err.Number to E_FAIL
Pending | 7 | Sets Err.Number to E_FAIL
Complete | 3 | Sets Err.Number to NOERROR and returns the time
Aborted | 4 | Sets Err.Number to NOERROR and returns the time
Canceled | 5 | Sets Err.Number to NOERROR and returns the time

Example

See the Query method.

See Also

Cancel, StartTime


FilesErrored Property

This read-only property specifies the number of files in error for the replication.

Syntax

ReplicationInstance.FilesErrored

Remarks

Example

See the Query method.

See Also

FilesErroredBytes , FilesMatched , FilesMatchedBytes , FilesReceived , FilesSent


FilesErroredBytes Property

This read-only property specifies the number of bytes associated with files in error for the replication.

Syntax

ReplicationInstance.FilesErroredBytes

Remarks

Example

See the Query method.

See Also

FilesErrored, FilesMatched, FilesMatchedBytes, FilesReceived, FilesSent


FilesMatched Property

This read-only property specifies the number of files matched for the replication.

Syntax

ReplicationInstance.FilesMatched

Remarks

Example

See the Query method.

See Also

FilesErrored, FilesErroredBytes, FilesMatchedBytes, FilesReceived, FilesSent


FilesMatchedBytes Property

This read-only property specifies the number of bytes matched during the recent replications.

Syntax

ReplicationInstance.FilesMatchedBytes

Remarks

When a file is matched, Content Deployment has recognized that the file on the destination server is the same as the file on the source server. Therefore Content Deployment need not copy the file from the source to the destination, unless the ReplicationClient.Force property is True.

Example

See the Query method.

See Also

FilesErrored, FilesErroredBytes, FilesMatched, FilesReceived, FilesSent


FilesReceived Property

This read-only property specifies the number of files and directories received for a current replication.

Syntax

ReplicationInstance.FilesReceived

Remarks

Example

See the Query method.

See Also

FilesErrored, FilesErroredBytes, FilesMatched, FilesMatchedBytes, FilesSent


FilesSent Property

This read-only property specifies the number of files sent during the recent replications.

Syntax

ReplicationInstance.FilesSent

Remarks

Example

See the Query method.

See Also

FilesErrored, FilesErroredBytes, FilesMatched, FilesMatchedBytes, FilesReceived


Flags Property

This read-only property specifies the flags with which the current replications were started.

Syntax

ReplicationInstance.Flags

Remarks

See the Flags appendix for a description of the flags.

Example

See the Query method.

See Also

Query


ID Property

This read-only property specifies the replication ID.

Syntax

ReplicationInstance.ID

Remarks

You must have Site Server Publishing administrator privileges on the server to read this property.

The ID is a 32-bit integer that uniquely identifies the replication on the machine.

Example

See the Query method.

See Also

Name


Name Property

This read-only property specifies the name of the project.

Syntax

ReplicationInstance.Name

Remarks

You must have Site Server Publishing administrator privileges on the server to read this property.

Example

See the Query method.

See Also

ReplicationProject


StartTime Property

This read-only property specifies the starting time for the replication.

Syntax

ReplicationInstance.StartTime

Remarks

Example

See the Query method.

See Also

Cancel, EndTime


State Property

This read-only property specifies the current state of the replication.

Syntax

ReplicationInstance.State

Remarks

The states are:

State | Value | Description
REPL_STATE_EMPTY | 0 | Invalid state.
REPL_STATE_STARTING | 1 | Replication starting.
REPL_STATE_RUNNING | 2 | Replication running.
REPL_STATE_COMPLETE | 3 | Replication completed successfully.
REPL_STATE_ABORTED | 4 | Replication aborted with an error.
REPL_STATE_CANCELED | 5 | Replication canceled.
REPL_STATE_RECEIVING | 6 | Replication receiving.
REPL_STATE_PENDING | 7 | Replication pending.

Example

See the Cancel method.

See Also

Status


Status Property

This read-only property specifies the current status of the replication.

Syntax

ReplicationInstance.Status

Remarks

This property may be used to retrieve the exact error that caused a replication to abort. If the project completes successfully, the status will be set to NOERROR.

Example

See the Cancel method.

See Also

State


ReplicationItem

The ReplicationItem object provides access to individual replication items. The following table briefly describes the ReplicationItem object's read-only properties.

Property | Description
Attributes | Attributes of the item.
CreationTime | When the item was created
LastAccessTime | When the item was last accessed
LastModifiedTime | When the item was last modified
Name | The name of the item
SizeHigh | The high size of the item
SizeLow | The low size of the item


CLSID and ProgID

ReplicationItem CLSID

66D6D7FE-22D2-11D0-9B98-00C04FD5CD09

ReplicationItem ProgID

CrsApi.ReplicationItem

ReplicationItem is a dual-interface COM object.


Accessing ReplicationItem Objects

You access an existing ReplicationItem object by calling the ReplicationProject.EnumItems method, as in the following example, where ReplItem is the name you give to the ReplicationItem object:

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("Crsapi.ReplicationServer")
ReplServer.Initialize("")
dim ReplProject
set ReplProject = ReplServer.OpenProject("MyProject", OPEN_EXISTING_PROJECT)

Dim ReplItem
dim Iterator
Iterator = 0
dim ReplError

do while True
  'Clear any error text
  Err.Clear
  'Get the next replication item
  set ReplItem = ReplProject.EnumItems "\LocalProj", Iterator

  'Display error message and quit if empty object returned
  if IsEmpty(ReplItem) then
    Wscript.Echo "Empty replication item returned."
    exit do
  end if

  'Quit if "No more items" error
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  'Now you have a valid replication item
  'Use ReplicationClient to replicate it
  ...

Loop

'Release objects
set ReplItem    = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing


ReplicationItem Properties

© 1997-1998 Microsoft Corporation. All rights reserved.


Attributes Property

This read-only property specifies the attributes of the object.

Syntax

ReplicationItem.Attributes

Remarks

The attributes are defined Winnt.h:

Attribute Name | Value | Description
FILE_ATTRIBUTE_READONLY | 1 (0x1) | The item has the read-only bit set.
FILE_ATTRIBUTE_HIDDEN | 2 (0x2) | The item has the hidden bit set.
FILE_ATTRIBUTE_SYSTEM | 4 (0x4) | The item has the system bit set.
FILE_ATTRIBUTE_DIRECTORY | 16 (0x10) | The item is a directory.
FILE_ATTRIBUTE_ARCHIVE | 32 (0x20) | The item has the archive bit set.
FILE_ATTRIBUTE_ENCRYPTED | 64 (0x40) | The item is encrypted.
FILE_ATTRIBUTE_NORMAL | 128 (0x80) | The item is a normal file or directory.
FILE_ATTRIBUTE_TEMPORARY | 256 (0x100) | The item is a temporary directory.
FILE_ATTRIBUTE_SPARSE_FILE | 512 (0x200) | The item is a sparse file.
FILE_ATTRIBUTE_REPARSE_POINT | 1024 (0x400) | The item is a reparse point.
FILE_ATTRIBUTE_COMPRESSED | 2048 (0x800) | The item is a compressed file or directory.
FILE_ATTRIBUTE_OFFLINE | 4096 (0x1000) | The item is not available.

If the FILE_ATTRIBUTE_DIRECTORY attribute is not set, the ReplicationItem object is a file. If the ReplicationItem object is a file, Attributes contains the file attributes. If the ReplicationItem is not a file, it is a metabase item.

Example

The following example displays the attributes of the replication items in the \LocalProj directory for the Test project.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("Crsapi.ReplicationServer")
ReplServer.Initialize("")
dim Project
set Project = ReplServer.OpenProject("Test", OPEN_EXISTING_PROJECT)

Dim ReplItem
dim Iterator
Iterator = 0
dim ReplError

do while True
  'Clear any error text
  Err.Clear
  'Get the next replication item
  set ReplItem = Project.EnumItems "\LocalProj", Iterator

  'Display error message and quit if empty object returned
  if IsEmpty(ReplInst) then
    Wscript.Echo "Empty replication item returned."
    exit do
  end if

  'Quit if "No more items" error
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  Wscript.Echo "Name: " & ReplItem.Name
  Wscript.Echo "Attributes: " & ReplItem.Attributes
  Wscript.Echo "Creation time: " & ReplItem.CreationTime
  Wscript.Echo "Last access time: " & ReplItem.LastAccessTime
  Wscript.Echo "Last modified time: " & ReplItem.LastModifiedTime
  dim size
  size = ReplItem.SizeHigh + ReplItem.SizeLow
  Wscript.Echo "Size: " & size & " (bytes)"

Loop

'Release objects
set ReplInst    = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

Name, ReplicationProject.EnumItems


CreationTime Property

This read-only property specifies the time when the item was created.

Syntax

ReplicationItem.CreationTime

Remarks

Example

See the Attributes property example.

See Also

LastAccessTime, LastModifiedTime, ReplicationProject.EnumItems


LastAccessTime Property

This read-only property specifies the time when the item was most-recently accessed.

Syntax

ReplicationItem.LastAccessTime

Remarks

Example

See the Attributes property example.

See Also

LastModifiedTime, ReplicationProject.EnumItems


LastModifiedTime Property

This read-only property specifies the time when the item was most-recently modified.

Syntax

ReplicationItem.LastModifiedTime

Remarks

Example

See the Attributes property example.

See Also

LastModifiedTime, ReplicationProject.EnumItems


Name Property

This read-only property specifies the name of the item.

Syntax

ReplicationItem.Name

Remarks

Example

See the Attributes property example.

See Also

ReplicationProject.EnumItems


SizeHigh Property

This read-only property specifies the high size of files over 4GBytes in size.

Syntax

ReplicationItem.SizeHigh

Remarks

Files larger than 4GBytes use both the SizeHigh and SizeLow properties.

Example

See the Attributes property example.

See Also

SizeLow, ReplicationProject.EnumItems


SizeLow Property

This read-only property specifies the size of files less than 4GBytes in size.

Syntax

ReplicationItem.SizeLow

Remarks

Files larger than 4GBytes use both the SizeHigh and SizeLow properties.

Example

See the Attributes property example.

See Also

SizeHigh, ReplicationProject.EnumItems


ReplicationPostingAcceptor

The ReplicationPostingAcceptor object provides access to replication posting acceptor settings. The following table briefly describes the ReplicationPostingAcceptor object's methods.

Method | Description
Enum | Lists all Posting Acceptor parameters.
Get | Retrieves a Posting Acceptor parameter.
Put | Sets a Posting Acceptor parameter.


CLSID and ProgID

ReplicationPostingAcceptor CLSID

055f638a-1d77-11d1-a32b-0000f8014963

ReplicationPostingAcceptor ProgID

CrsApi.ReplicationPostingAcceptor

ReplicationPostingAcceptor is a dual-interface COM object.


Creating a ReplicationPostingAcceptor Object

You create a new ReplicationPostingAcceptor object by calling the ReplicationServer.OpenPostingAcceptor method, as in the following example, where ReplPA is the name you give to the new ReplicationPostingAcceptor object:

Option Explicit
On Error Resume Next

dim ReplServer
set ReplServer = CreateObject("Crsapi.ReplicationServer")
ReplServer.Initialize("")

dim ReplPA
set ReplPA = ReplServer.OpenPostingAcceptor
...

'Release Posting Acceptor object
set ReplPA = Nothing


ReplicationPostingAcceptor Methods

© 1997-1998 Microsoft Corporation. All rights reserved.


Enum Method

This method lists the parameters of the Posting Acceptor.

Syntax

ReplicationPostingAcceptor.Enum(Iterator, ParamName)

Parameters

Iterator

Used by the service to enumerate the list of parameters. This value should be initialized to zero, and should not be modified.

ParamName

Used by the service to enumerate the names of the parameters. This value should be initialized to an empty string (""), and should not be modified.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

The parameters are described in the following table:

Parameter | Description
MaximumOpenTransactions | The maximum number of transactions that can be running at the same time.
OpenTransactionsTimeout | The timeout duration, in milliseconds.
AllowAnonymous | Whether anonymous users can post.
AutoStartReplications | Whether replications are automatically started when a new post arrives.
PathToPA | The absolute path to the posting acceptor directory.
RepostURL | The URL on the destination server to which the postings are sent.
TargetURL | The URL on the source server from which the postings are sent.

Example

The following example lists the parameters of the Posting Acceptor.

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("Crsapi.ReplicationServer")
ReplServer.Initialize("")
dim RepPA
set RepPA = ReplServer.OpenPostingAcceptor

dim ParamName
ParamName = ""
dim ParamVal
dim Iterator
Iterator = 0
dim ReplError

do while True
  'Clear any error text
  Err.Clear

  ParamVal = RepPA.Enum(Iterator, ParamName)

  'Quit if ParamName is empty (no parameter returned)
  if IsEmpty(ParamVal) then exit do

  'Quit if "No more items" error

  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  Wscript.Echo ParamName & " = " & ParamVal
Loop

'Release objects
set RepPA      = Nothing
set ReplServer = Nothing

See Also

Get, Put, ReplicationServer.OpenPostingAcceptor


Get Method

This method retrieves the value of a Posting Acceptor property.

Syntax

ReplicationPostingAcceptor.Get(Property)

Parameters

Property

The name of the property:

Parameter | Description
MaximumOpenTransactions | The maximum number of transactions that can be running at the same time.
OpenTransactionsTimeout | The timeout duration, in milliseconds.
AllowAnonymous | Whether anonymous users can post.
AutoStartReplications | Whether replications are automatically started when a new post arrives.
PathToPA | The absolute path to the posting acceptor directory.
RepostURL | The URL on the destination server to which the postings are sent.
TargetURL | The URL on the source server from which the postings are sent.

Example

See the Enum property.

See Also

Enum, Put


Put Method

This method sets the value of a Posting Acceptor property.

Syntax

ReplicationPostingAcceptor.Put(ParamName, ParamValue)

Parameters

ParamName

The name of the parameter to set.

Parameter | Description
MaximumOpenTransactions | The maximum number of transactions that can be running at the same time.
OpenTransactionsTimeout | The timeout duration, in milliseconds.
AllowAnonymous | Whether anonymous users can post.
AutoStartReplications | Whether replications are automatically started when a new post arrives.
PathToPA | The absolute path to the posting acceptor directory.
RepostURL | The URL on the destination server to which the postings are sent.
TargetURL | The URL on the source server from which the postings are sent.

ParamValue

The value to which the parameter is set.

Remarks

Example

The following example changes the timeout to 50000 (five seconds).

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("Crsapi.ReplicationServer")
ReplServer.Initialize("")
dim RepPA
set RepPA = ReplServer.OpenPostingAcceptor

RepPA.Put("OpenTransactionsTimeout", "50000")

'Release objects
set RepPA      = Nothing
set ReplServer = Nothing

See Also

Enum, Get


ReplicationProject

The ReplicationProject object provides methods and properties to administer projects on a Content Deployment server. The ReplicationProject object defines the following methods and properties:

Method | Description
AddDestination | Adds a destination to the project
AddSchedule | Adds a schedule to the project.
ApplyTransaction | Applies transaction to the project
Cancel | Cancels the running project
CheckAccess | Gets the current user's access permissions.
Commit | Commits changes for a project
Enum | Lists the parameters for a project
EnumAccess | Lists the users access permissions for a project.
EnumDestination | Lists the destinations for a project
EnumItems | Lists the ReplicationItem objects for a project
EnumReplications | Lists the ReplicationInstance objects for a project
EnumSchedules | Lists the ReplicationSchedule objects for a project.
Get | Retrieves a parameter for the project
GrantAccess | Grants a user access to a project
Put | Sets a parameter for the project
RemoveAccess | Removes user’s access to a project
RemoveDestination | Removes a destination from a project
Rollback | Rolls back to a previous replication
Start | Starts a project run
StartReplicationClient | Invokes a ReplicationClient object for the project
Property | Description
Flags | A bitmask of the flags for the project (see the Flags appendix)
LocalDirectory | Local directory for the project
Name | The name of the project
ReplicationMethod | The replication method (push or pull) used for the project


CLSID and ProgID

ReplicationProject CLSID

66D6D7F2-22D2-11D0-9B98-00C04FD5CD09

ReplicationProject ProgID

CrsApi.ReplicationProject

ReplicationProject is a dual-interface COM object.


Creating a ReplicationProject Object

You create a new ReplicationProject object by calling the ReplicationServer.OpenProject method, as in the following example, where ReplProj is the name you give to the new ReplicationProject object:

Option Explicit
On Error Resume Next

const OPEN_NEW_PROJECT  = 1

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("MyProject", OPEN_NEW_PROJECT)
'Set project parameters
...
'Commit any changes to the project
ReplProject.Committ

...

'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing


Accessing ReplicationProject Objects

You access a ReplicationProject object by calling the ReplicationServer.OpenProject method, as in the following example, where ReplProj is the name you give to the new ReplicationProject object:

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("MyProject", OPEN_EXISTING_PROJECT)
...

'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing

Note

You can access all of the projects on a server using the ReplicationServer.EnumProjects method.


ReplicationProject Methods

© 1997-1998 Microsoft Corporation. All rights reserved.


AddDestination Method

This method adds a destination to the project.

Syntax

ReplicationProject.AddDestination(Destination)

Parameters

Destination

Name of the server or route to add to the project.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

Duplicate destination names are automatically eliminated from the list.

Note If you add a destination that is on the same machine, you cannot replicate files using the ReplicationClient methods.

Example

The following example add the destination MyDest to the list of destinations.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("MyProject", OPEN_EXISTING_PROJECT)

ReplProject.AddDestination("MyDest")

'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

EnumDestination , RemoveDestination


AddSchedule Method

This method adds a schedule to the project.

Syntax

ReplicationProject.AddSchedule

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

This method returns a ReplicationSchedule object.

Example

The following example adds a new schedule to the project MyProject.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("MyProject", OPEN_EXISTING_PROJECT)

dim RepSched
set RepSched = ReplProject.AddSchedule
...

'Release objects
set ReplSched   = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

EnumSchedules


ApplyTransaction Method

This method applies any pending transaction for the project.

Syntax

ReplicationProject.ApplyTransaction(Reserved)

Parameters

Reserved

Reserved. Must be zero.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

Immediately applies any transactions pending for the project.

Example

The following example applies any pending transactions for the project Project1.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("Project1", OPEN_EXISTING_PROJECT)

'Fire up a client
dim ReplClient
ReplClient = ReplProject.StartReplicationClient(0)

'Do some replicating
...

'Commit client's actions and applies any transactions
ReplClient.Commit
ReplProject.ApplyTransaction

'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing


Cancel Method

This method cancels a running project.

Syntax

ReplicationProject.Cancel

Remarks

Example

The following example cancels the project if the replication is in the aborted state.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const REPL_STATE_ABORTED   = 4

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("Project1", OPEN_EXISTING_PROJECT)

dim ReplInst
set ReplInst = ReplProject.Start(0)

dim ReplState
ReplState = ReplInst.State

'Quit if the state is aborted
if ReplState = REPL_STATE_ABORTED then ReplClient.Cancel

'Release objects
set ReplInst    = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

Start


CheckAccess Method

This method retrieves the current user's access permissions on a Content Deployment project.

Syntax

ReplicationProject.CheckAccess

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

The access permissions are as follows:

Name | Value | Description
CRS_ADMIN_ACCESS | 983103 | The user has Site Server Publishing administrator access privileges
CRS_USER_ACCESS | 131097 | The user has Site Server Publishing operator access privileges

Example

The following example retrieves the current user's access permissions on Project1.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const CRS_USER_ACCESS    = 0&20019
const CRS_ADMIN_ACCESS   = 0&F003F

dim ReplServer
set ReplServer = CreateObject("Crsapi.ReplicationServer")
ReplServer.Initialize("")
dim ReplProject
set ReplProject = ReplServer.OpenProject("Project1", OPEN_EXISTING_PROJECT)

dim Perms
Perms = ReplProject.CheckAccess

if Perms = CRS_ADMIN_ACCESS then
 Wscript.Echo "You have administrator privileges on Project1"
elseif Perms = CRS_USER_ACCESS
  Wscript.Echo "You have operator privileges on Project1"
else
  Wscript.Echo "You have no privileges on Project1"
end if

'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

GrantAccess, RemoveAccess


Commit Method

This method commits changes for a project.

Syntax

ReplicationProject.Commit

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

You must use this method to initialize a new project. There are a number of required parameters and properties that you must set before you can call the Commit method. All of the parameters and properties are described in the Parameters topic. The required parameters and properties are described in the following table.

Required Parameters and Properties for Push Projects
Name | Description
ReplicationMethod | Set this property to "SENDINET" for Push projects.
Destination | This parameter is a list of the names of all servers to receive the replication. Can be Empty ("") if there is no destination. If creating a project using routes, it must be the name of the route. The list cannot exceed 4096 characters. Microsoft recommends that you use the ReplicationProject.AddDestination, ReplicationProject.EnumDestination, and ReplicationProject.RemoveDestination methods to add, list, and remove a destination, respectively.
LocalDirectory | This property is the (Unicode) name of the local directory used to send or receive the content. Cannot be Empty ("").
Flags | This property is a long array of bitmapped values (see the Flags appendix)
Required Parameters and Properties for Pull Projects
Name | Description
ReplicationMethod | Set this property to "PULL" for Pull projects.
RootUrl | This parameter is the URL from which to pull data; for example, “http://www.microsoft.com/”.
LocalDirectory | This property is the name of the local directory to store the information. Cannot be Empty ("").
Depth | This parameter is the depth of the replication. For HTTP, this is the number of times to follow links from the root page. For FTP, this is the depth to go in the directory structure.

Example

The following example specifies that the new project MyProject pulls Web pages from http://www.microsoft.com/ to C:\LocalCopy, going as much as three levels deep.

Option Explicit
On Error Resume Next

const CREATE_NEW_PROJECT = 1

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

'Create new pull project, FromMS
dim ReplProject
set ReplProject = ReplServer.OpenProject("FromMS", CREATE_NEW_PROJECT)
ReplProject.ReplicationMethod = "PULL"
ReplProject.Put("RootUrl", "http://www.microsoft.com/")
ReplProject.LocalDirectory = "C:\LocalCopy"
ReplProject.Put("Depth", "3"
ReplProject.Commit

'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

ReplicationServer.OpenProject


Enum Method

This method lists the parameters of a project.

Syntax

ReplicationProject.Enum(Iterator, ParamName)

Parameters

Iterator

Used by the service to enumerate the list of parameters. This value should be initialized to zero, and should not be modified.

ParamName

Used by the service to enumerate the parameter names. This value should be initialized to an empty string, "", and should not be modified.

Remarks

For a list of parameters that can be retrieved from Content Deployment projects, see Parameters.

Example

The following example lists the parameters of Project1.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("Crsapi.ReplicationServer")
ReplServer.Initialize("")
dim Project
set ReplProject = ReplServer.OpenProject("Project1", OPEN_EXISTING_PROJECT)

dim ParamName
dim ParamVal
dim Iterator
Iterator = 0
dim ReplError

do while True
  ParamVal = ReplProject.Enum(Iterator, ParamName)

  'Clear any error text
  Err.Clear

  'Quit if "No more items" error

  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  Wscript.Echo "Parameter " & ParamName & " = " & ParamVal
Loop

'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

EnumDestination , EnumReplications


EnumAccess Method

This method lists the users with their access privileges on the project.

Syntax

ReplicationProject.EnumAccess(Iterator, Access)

Parameters

Iterator

Used by the service to enumerate the list of users. This value should be initialized to zero, and should not be modified.

Access

The returned access value.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

The access privileges are described in the following table.

Name | Value | Description
CRS_ADMIN_ACCESS | 983103 | The user has Site Server Publishing administrator access privileges
CRS_USER_ACCESS | 131097 | The user has Site Server Publishing operator access privileges

Example

The following example displays the access privileges of the users on Project1.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const CRS_USER_ACCESS    = 0&20019
const CRS_ADMIN_ACCESS     = 0&F003F
const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("Crsapi.ReplicationServer")
ReplServer.Initialize("")
dim Project
set Project = ReplServer.OpenProject("Project1", OPEN_EXISTING_PROJECT)

dim UserName
dim AccessPriv
dim Iterator
Iterator = 0
dim ReplError

do while True
  'Clear any error text
  Err.Clear

  UserName = Project.EnumAccess(Iterator, AccessPriv)

  'Quit if "No more items" error
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  if AccessPriv = 0 then
    Wscript.Echo UserName & " has no access."
  elseif AccessPriv = CRS_USER_ACCESS then
    Wscript.Echo UserName & " has operator access."
  elseif AccessPriv = CRS_ADMIN_ACCESS then
    Wscript.Echo UserName & " has administrator access."
  end if
Loop

'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing


EnumDestination Method

This method lists the destinations for the project.

Syntax

ReplicationProject.EnumDestination(Iterator)

Parameters

Iterator

Used by the service to enumerate the list of destinations. This value should be initialized to zero, and should not be modified.

Example

The following example displays the destinations for the Project1 project.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("Crsapi.ReplicationServer")
ReplServer.Initialize("")
dim Project
set Project = ReplServer.OpenProject("Project1", OPEN_EXISTING_PROJECT)

dim Dest
dim Iterator
Iterator = 0
dim ReplError

Wscript.Echo "The destination servers for Project1 are:"

do while True
  'Clear any error text
  Err.Clear

  Dest = Project.EnumDestinations(Iterator)
  'Quit if "No more items" error
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  Wscript.Echo Dest
Loop

'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

Enum


EnumItems Method

This method lists the replication item objects for the project.

Syntax

ReplicationProject.EnumItems(Directory, Iterator)

Parameters

Directory

Relative path to the directory to begin enumerating.

Iterator

Used by the service to enumerate the list of replication items. This value should be initialized to zero, and should not be modified.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

EnumItems returns the ReplicationItem objects in Directory in an enumerated list. The objects are the files for standard projects and containers for metabase projects.

Example

The following example displays the names of the replication items in the .\LocalRep directory.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("Crsapi.ReplicationServer")
ReplServer.Initialize("")
dim Project
set Project = ReplServer.OpenProject("Project1", OPEN_EXISTING_PROJECT)

dim Directory
Directory = ".\LocalRep"
Dim ReplItem
dim Iterator
Iterator = 0
dim ReplError

Wscript.Echo "The following items were replicated from " & Directory

do while True
  'Clear any error text
  Err.Clear
  'Get the next replication item
  set ReplItem = Project.EnumItems Directory, Iterator

  'Display error message and quit if empty object returned
  if IsEmpty(ReplItem) then
    Wscript.Echo "Empty replication item returned."
    exit do
  end if

  'Quit if "No more items" error
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  Wscript.Echo ReplItem.Name
Loop
'Release objects
set ReplItem    = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

ReplicationItem


EnumReplications Method

This method lists the replication instances for the project.

Syntax

ReplicationProject.EnumReplications(State, Iterator)

Parameters

State

Queries for replications of a given state. The states are described in the following table.

State | Value | Description
REPL_STATE_EMPTY | 0 | Return all replications.
REPL_STATE_STARTING | 1 | Return only starting replications.
REPL_STATE_RUNNING | 2 | Return only running replications.
REPL_STATE_COMPLETE | 3 | Return only completed replications.
REPL_STATE_ABORTED | 4 | Return only aborted replications.
REPL_STATE_CANCELED | 5 | Return only canceled replications.
REPL_STATE_RECEIVING | 6 | Return only receiving replications.
REPL_STATE_PENDING | 7 | Return only pending replications.

Iterator

Used by the service to enumerate the list of replications. This value should be initialized to zero, and should not be modified.

Remarks

When there are no more items to enumerate, EnumReplications sets the global error message to CRS_ERROR_NO_MORE_ITEMS.

Example

The following example lists when the replication was started, the number of files sent, the state of the replication, and the status of the replication for all replication instances for the Proj1 project.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17
const OPEN_EXISTING_PROJECT  = 2
const REPL_STATE_EMPTY    = 0

Err.Clear

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("Proj1", OPEN_EXISTING_PROJECT)

dim Iterator
Iterator = 0
dim Inst

dim ID
ID = 0

do while True

  'Get replication instance
  set Inst = ReplProject.EnumReplications(REPL_STATE_EMPTY, Iterator)

  'Quit if "No more items" error
  if Err.Number = CRS_ERROR_NO_MORE_ITEMS then exit do

  'Quit if Instance is empty
  if IsEmpty(Inst) then
   Wscript.Echo "Instance object is empty."
   exit do
  end if

  'Quit if Instance is NULL
  if IsNull(Inst) then
   Wscript.Echo "Instance object is Null."
   exit do
  end if

  'Quit if we're looking at the same instance
  if ID = Inst.ID then exit do

  'Update Instance properties
  Inst.Query

  'Display Instance properties
  Wscript.Echo "Replication : " & Inst.ID & " properties:"
  Wscript.Echo "Started:   " & Inst.StartTime
  Wscript.Echo "Ended:   " & Inst.EndTime
  Wscript.Echo "Files sent:  " & Inst.FilesSent
  Wscript.Echo "State:   " & Inst.State
  Wscript.Echo "Status:    " & Inst.Staus

  'Save Instance ID
  ID = Inst.ID

Loop

'Release objects
set Inst        = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

Enum


EnumSchedules Method

This method lists the schedules for the project.

Syntax

ReplicationProject.EnumSchedules(Iterator)

Parameters

Iterator

Used by the service to enumerate the list of schedules. This value should be initialized to zero, and should not be modified.

Example

The following example displays the descriptions for the schedules for the Project1 project.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("Crsapi.ReplicationServer")
ReplServer.Initialize("")
dim Project
set Project = ReplServer.OpenProject("Project1", OPEN_EXISTING_PROJECT)

dim Sched
dim Iterator
Iterator = 0
dim ReplError

Wscript.Echo "The schedule descriptions for Project1 are"

do while True
  'Clear any error text
  Err.Clear

  set Sched = Project.EnumSchedules(Iterator)

  'Quit if "No more items" error
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  Wscript.Echo Sched.Description
Loop
'Release objects
set Sched       = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

AddSchedule


Get Method

This method retrieves a parameter for the project.

Syntax

ReplicationProject.Get(ParamName)

Parameters

ParamName

The name of the parameter to retrieve.

Remarks

For a list of Content Deployment project parameters, see the Parameters appendix.

Example

The following example retrieves the value of the TransactionMethod parameter for MyProject.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("MyProject",
  OPEN_EXISTING_PROJECT)

TMethod = ReplProject.Get("TransactionMethod")
if TMethod = "Yes" then
  Wscript.Echo "MyProject uses transaction processing."
else
  Wscript.Echo "MyProject does not use transaction processing."
end if
'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

Put


GrantAccess Method

This method grants a user access to a Content Deployment project.

Syntax

ReplicationProject.GrantAccess(User, Access)

Parameters

User

User/group to be granted access to Content Deployment.

Access

The permissions for the user:

Name | Value | Description
CRS_ADMIN_ACCESS | 983103 | The user has Site Server Publishing administrator access privileges
CRS_USER_ACCESS | 131097 | The user has Site Server Publishing operator access privileges

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

Example

The following example grants administrator access to the user Dougs on Project1.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const CRS_ADMIN_ACCESS   = 0&F003F

dim ReplServer
set ReplServer = CreateObject("Crsapi.ReplicationServer")
ReplServer.Initialize("")
dim ReplProject
set ReplProject = ReplServer.OpenProject("Project1", OPEN_EXISTING_PROJECT)

ReplProject.GrantAccess("Dougs", CRS_ADMIN_ACCESS)
'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

CheckAccess, RemoveAccess


Put Method

This method sets the value of a parameter for the project.

Syntax

ReplicationProject.Put(ParamName, ParamValue)

Parameters

ParamName

Name of the parameter.

ParamValue

The parameter value.

Remarks

Parameters are not set for the project until they are committed by using ReplicationProject.Commit. For a list of project parameters, see the Parameters appendix.

Note You must explicitly cast any whole number value that you assign to a global parameter to a 32-bit (long) integer with CLng(), as shown in the following example.

Example

The following example sets the Depth parameter (the depth of the replication) to 3 for project MyProject.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2

dim ReplServer, Depth

set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("MyProject", OPEN_EXISTING_PROJECT)

Depth = Clng(3)

ReplProject.Put("Depth", Depth)

'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

Get


RemoveAccess Method

This method removes a user’s access to a Content Deployment project.

Syntax

ReplicationProject.RemoveAccess(User)

Parameters

User

The user or group for whom access to the project is removed.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

If a user is in a group that has access to the project, the user will continue to have access to the project.

Example

The following example removes user Steveb from access to the Project1 project.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2

dim ReplServer
set ReplServer = CreateObject("Crsapi.ReplicationServer")
ReplServer.Initialize("")
dim ReplProject
set ReplProject = ReplServer.OpenProject("Project1", OPEN_EXISTING_PROJECT)
ReplProject.RemoveAccess("Steveb")

'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

CheckAccess, GrantAccess


RemoveDestination Method

This method removes a destination from the project.

Syntax

ReplicationProject.RemoveDestination(Destination)

Parameters

Destination

The server or route to remove from the project.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

Example

The following example removes the destination server Capricorn from the list of destination servers for the Test project.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("Test", OPEN_EXISTING_PROJECT)

ReplProject.RemoveDestination("Capricorn")

'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

AddDestination


Rollback Method

This method rolls back to a previous replication.

Syntax

ReplicationProject.Rollback(NumRollbacks)

Parameters

NumRollbacks

The number of rollbacks to perform.

Remarks

Example

The following example cancels the project and rolls the replication back to the previous state if the status is aborted.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const REPL_STATE_ABORTED   = 4

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("Project1", OPEN_EXISTING_PROJECT)

dim ReplInst
set ReplInst = ReplProject.Start(0)

dim ReplStatus
ReplStatus = ReplInst.Status

'Quit and roll back one if the status was aborted
if ReplStatus = REPL_STATE_ABORTED then
  ReplClient.Cancel
  ReplProject.RollBack(1)
end if

'Release objects
set ReplInst    = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing


Start Method

This method starts the project.

Syntax

ReplicationProject.Start(Flags)

Parameters

Flags

Flags for this particular replication. Specify zero (0) to use the flags already defined for the project. See the Flags appendix for a description of the flags.

Remarks

Note

You must define a project for the replication (using the ReplicationProject.Name property) before you call this method. If you have not defined a project before you call this method, Start fails, setting the error code CRS_ERROR_PROJECT_NOT_FOUND (15101).

Example

The following example starts the Project1 project with the default flags, cancelling it if it's aborted.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const REPL_STATE_ABORTED   = 4

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("Project1", OPEN_EXISTING_PROJECT)

dim ReplInst
set ReplInst = ReplProject.Start(0)

dim ReplStatus
ReplStatus = ReplInst.Status

'Quit if the status was aborted
if ReplStatus = REPL_STATE_ABORTED then ReplClient.Cancel

'Release objects
set ReplInst    = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

Cancel


StartReplicationClient Method

This method returns a ReplicationClient object that can be used to replicate individual files.

Syntax

ReplicationProject.StartReplicationClient(Reserved)

Parameters

Reserved

This parameter is reserved for future use and should be set to zero.

Remarks

Note

You must define a project for the replication (using the ReplicationProject.Name property) before you call this method. If you have not defined a project before you call this method, Start fails, setting the error code CRS_ERROR_PROJECT_NOT_FOUND (15101).

You can only start a replication client on a local Content Deployment computer. This method fails if the previous ReplicationServer.Initialize method is called with the Server parameter set to the name of a remote Content Deployment computer.

Example

The following example starts a replication client on the new Latest project, copies a file, and deletes a file.

Option Explicit
On Error Resume Next

const CREATE_NEW_PROJECT  = 1

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("Latest", CREATE_NEW_PROJECT)

ReplProject.ReplicationMethod = "SENDINET"
ReplProject.Put("Destination", "http://www.mytestmachine.com/")
ReplProject.LocalDirectory = "C:\LocalCopy"
ReplProject.Flags = RF_EXCLUDE_AL
ReplProject.Flags = RF_FASTMODE
ReplProject.Commit

dim ReplClient
set ReplClient = ReplProject.StartReplicationClient(0)

ReplClient.SendFile("NewFile.htm")
ReplClient.DeleteFile("OldFile.htm")

'Release objects
set ReplClient  = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

ReplicationClient.Initialize


ReplicationProject Properties

© 1997-1998 Microsoft Corporation. All rights reserved.


Flags Property

This property specifies project settings that determine how the replication proceeds .

Syntax

ReplicationProject.Flags[=Value]

Parameters

Value

A bitmask specifying the settings for the project.

Remarks

You must have Site Server Publishing administrator privileges on the server to get or set this property.

See the Flags appendix for a description of the flags.

Example

The following example replicates all files in Project1, regardless of whether they've been changed.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const RF_FORCE_REPL    = 8

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("Project1", OPEN_EXISTING_PROJECT)
ReplProject.Flags = RF_FORCE_REPL
ReplProject.Start

See Also

Get


LocalDirectory Property

This property specifies the local directory for the project.

Syntax

ReplicationProject.LocalDirectory[=Dir]

Parameters

Dir

The local directory.

Example

The following example creates a new project, Test, which pushes content from the local directory C:\Tmp to the destination server http://www.mytestmachine.com. The project replicates only C:\Tmp, but no subdirectories under it. It also uses fast mode, which implies a reliable connection.

Option Explicit
On Error Resume Next

const CREATE_NEW_PROJECT  = 1
const RF_EXCLUDE_ALL    = 4096
const RF_FASTMODE     = 128

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

'Create new push project
dim ReplProject
set ReplProject = ReplServer.OpenProject("Test", CREATE_NEW_PROJECT)

ReplProject.ReplicationMethod = "SENDINET"
ReplProject.Put("Destination", "http://www.mytestmachine.com/")
ReplProject.LocalDirectory = "C:\Tmp"
ReplProject.Flags = RF_EXCLUDE_AL
ReplProject.Flags = RF_FASTMODE

ReplProject.Commit
ReplProject.Start

'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

Get


Name Property

This property specifies the name of the project.

Syntax

ReplicationProject.Name[=Name]

Parameters

Name

The name of the project.

Remarks

Name does not take effect until Commit is called.

Example

The following example retrieves the names of the existing projects.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim ReplProject
dim RepError
Wscript.Echo "The project names are:"

while True do
  Err.Clear
  set ReplProject = ReplServer.EnumProjects(Iterator)
  if IsEmpty(ReplProject) then exit do
  RepError = Err.Number
  if RepError = CRS_ERROR_NO_MORE_ITEMS then exit do

  Wscript.Echo ReplProject.Name
Loop
'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

Get, Put


ReplicationMethod Property

This parameter specifies the replication method for a project.

Syntax

ReplicationProject.ReplicationMethod[= Method]

Parameters

Method

The method of replicating for the project.

Method | Description
ACTIVE | Component Deployment project
PULL | Internet retrieval project
SENDINET | Content Deployment project

Remarks

Example

The following example specifies that the new project MyProject pulls Web pages from http://www.microsoft.com/ to C:\LocalCopy, going up to three levels deep,and uses the PULL replication method.

Option Explicit
On Error Resume Next

const CREATE_NEW_PROJECT = 1

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

'Create new pull project, FromMS
dim ReplProject
set ReplProject = ReplServer.OpenProject("FromMS", CREATE_NEW_PROJECT)

ReplProject.ReplicationMethod = "PULL"
ReplProject.Put("RootUrl", "http://www.microsoft.com/")
ReplProject.LocalDirectory = "C:\LocalCopy"
ReplProject.Put("Depth", "3"
ReplProject.Commit

'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

Get


ReplicationRoute

The ReplicationRoute object provides methods and properties to administer individual replication routes. The ReplicationRoute object defines the following methods and properties:

Method | Description
AddDestination | Adds a destination to the route
Commit | Commits changes for a route
Enum | Enumerates route’s parameters
EnumDestination | Enumerates destinations for the route
Get | Retrieves a parameter for the route
Put | Sets a parameter for the route
RemoveDestination | Removes destination from the route
Property | Description
BaseDirectory | Base directory for the route
Name | Route’s name


CLSID and ProgID

ReplicationRoute CLSID

66D6D7FC-22D2-11D0-9B98-00C04FD5CD09

ReplicationRoute ProgID

CrsApi.ReplicationRoute

ReplicationRoute is a dual-interface COM object.


Creating a ReplicationRoute Object

You create a new ReplicationRoute object by calling the ReplicationServer.AddRoute method, as in the following example, where ReplRoute is the name you give to the new ReplicationRoute object:

Option Explicit
On Error Resume Next

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplRoute
set ReplRoute = ReplServer.AddRoute("Default")
...

'Release objects
set ReplRoute  = Nothing
set ReplServer = Nothing


Accessing ReplicationRoute Objects

You access an existing ReplicationRoute object by calling the ReplicationServer.EnumRoutes method, as in the following example, where ReplRoute is the name you give to the new ReplicationRoute object:

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0

dim ReplRoute

do while True
  'Clear any error text
  Err.Clear
  'Get a route
  set ReplRoute = ReplServer.EnumRoutes(Iterator)

  'Quit if empty object returned (no more instances)
  if IsEmpty(ReplRoute) then exit do

  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  'You now have a good route
  ...
loop

'Release objects
set ReplRoute  = Nothing
set ReplServer = Nothing


ReplicationRoute Methods

© 1997-1998 Microsoft Corporation. All rights reserved.


AddDestination Method

This method adds a destination to the route.

Syntax

ReplicationRoute.AddDestination(Destination)

Parameters

Destination

The name of the server or route to add.

Remarks

Duplicate destination names are automatically eliminated from the list.

Example

The following example adds the destination server Marrakech to the Test route.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0

dim ReplRoute

do while True
  'Clear any error text
  Err.Clear
  'Get a route
  set ReplRoute = ReplServer.EnumRoutes(Iterator)

  'Quit if empty object returned (no more instances)
  if IsEmpty(ReplRoute) then exit do

  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  'If the route is Test, add Marrakech
  if ReplRoute.Name = Test then ReplRoute.AddDestination("Marrakech")
loop
'Release objects
set ReplRoute  = Nothing
set ReplServer = Nothing

See Also

EnumDestination , RemoveDestination


Commit Method

This method commits changes for a route.

Syntax

ReplicationRoute.Commit

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

This method commits changes made to the route properties. This method must be called when creating a new route. Prior to this call, the required BaseDirectory route parameter must be set.

Example

The following example commits the new route Test for an endpoint server.

Option Explicit
On Error Resume Next

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplRoute
set ReplRoute = ReplServer.AddRoute("Test")

'Set the required parameter
Rep.BaseDirectory="D:\INETPUB\WWWROOT"

ReplRoute.Commit

'Release objects
set ReplRoute  = Nothing
set ReplServer = Nothing

See Also

ReplicationServer.AddRoute, ReplicationServer.EnumRoutes


Enum Method

This method lists the parameters of a route.

Syntax

ReplicationRoute.Enum(Iterator, ParamName)

Parameters

Iterator

Used by the service to enumerate the list of parameters. This value should be initialized to zero, and should not be modified.

ParamName

Used by the service to return the name of the parameter. This value should be initialized to an empty string, "", and should not be modified.

Remarks

The only parameters that are listed are BaseDirectory, which you can set with either the BaseDirectory property or with the Put method, and Destinations, which you can set with the AddDestination method.

Example

The following example lists the names and values of all of the parameters for the Temp route.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim ReplRoute
dim RouteParam

do while True
  'Clear any error text
  Err.Clear
  'Get a route
  set ReplRoute = ReplServer.EnumRoutes(Iterator)

  'Quit if empty object returned (no more instances)
  if IsEmpty(ReplRoute) then exit do

  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  dim Name
  Name = ReplRoute.Name

  'We have a valid route. Check if it's the one we want
  if Name = "Temp" then
    dim RouteParam
    RouteParam = ""
    dim ParamValue

    do while True
    Err.Clear
    ParamValue = ReplRoute.Enum(Iterator, RouteParam)

    'Exit if we've looped past the last parameter
    if ParamValue = CRS_ERROR_NO_MORE_ITEMS then exit do

    Wscript.Echo "Parameter " & RouteParam & "= " & ParamValue
    Loop
  end if
  'We can exit now, since we already found our route
  exit do

loop
'Release objects
set ReplRoute  = Nothing
set ReplServer = Nothing

See Also

BaseDirectory, Get, Put


EnumDestination Method

This method lists the destinations for the route.

Syntax

ReplicationRoute.EnumDestination(Iterator)

Parameters

Iterator

Used by the service to enumerate the list of destinations. This value should be initialized to zero, and should not be modified.

Example

The following example lists the destinations for the Temp route.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim ReplRoute
dim RouteParam

do while True
  'Clear any error text
  Err.Clear
  'Get a route
  set ReplRoute = ReplServer.EnumRoutes(Iterator)

  'Quit if empty object returned (no more instances)
  if IsEmpty(ReplRoute) then exit do

  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  'We have a valid route. Check if it's the one we want
  dim Name = ReplRoute.Name
  if Name = "Temp" then
    dim RouteDest
    Wscript.Echo "The Temp route had the following destinations"

    do while True
    Err.Clear
    RouteDest = ReplRoute.EnumDestination(Iterator)

    'Exit if we've looped past the last parameter
    if RouteDest = CRS_ERROR_NO_MORE_ITEMS then exit do

    Wscript.Echo RouteDest
    Loop
  end if
  'We can exit now, since we already found our route
  exit do

Loop
'Release objects
set ReplRoute  = Nothing
set ReplServer = Nothing

See Also

Enum


Get Method

This method retrieves a parameter for the route.

Syntax

ReplicationRoute.Get(ParamName)

Parameters

ParamName

The name of the parameter to get. The only parameter available is BaseDirectory, which identifies the directory from which the content is replicated.

Example

The following example retrieves and displays the value of the BaseDirectory parameter for all routes.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS   = 0&80003B17

dim ReplServer, Iterator, ReplRoute, BaseDirectory
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

Iterator = 0

do while True
  'Clear any error text
  Err.Clear
  'Get a route
  set ReplRoute = ReplServer.EnumRoutes(Iterator)

  'Quit if "No more items" error
  if Err.Number = CRS_ERROR_NO_MORE_ITEMS then exit do

  BaseDirectory = ReplRoute.Get("BaseDirectory")

  if IsEmpty(BaseDirectory) = False then
    Wscript.Echo "The base direcory for route " & ReplRoute.Name _
    & " is " & BaseDirectory
  end if

Loop
'Release objects
set ReplRoute  = Nothing
set ReplServer = Nothing

See Also

BaseDirectory, Put


Put Method

This method sets a parameter for the route.

Syntax

ReplicationRoute.Put(ParamName, ParamValue)

Parameters

ParamName

The name of the parameter to set. The only parameter available is BaseDirectory, which identifies the directory from which the content is replicated.

ParamValue

The parameter value. For BaseDirectory, this must be a full pathname.

Remarks

Parameters are not set for the route until they are committed by using the ReplicationRoute.Commit method.

Example

The following example sets the value of the BaseDirectory parameter to C:\Test.

Option Explicit
On Error Resume Next

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplRoute
set ReplRoute = ReplServer.AddRoute("Test")
ReplRoute.Set("Parameter", "Value")
ReplRoute.Commit

'Release objects
set ReplRoute  = Nothing
set ReplServer = Nothing

See Also

BaseDirectory, Get


RemoveDestination Method

This method removes a destination from the route.

Syntax

ReplicationRoute.RemoveDestination(Destination)

Parameters

Destination

Name of the server or route to remove.

Example

The following example removes the destination server TestPC from the route Test.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim ReplRoute

do while True
  'Clear any error text
  Err.Clear
  'Get a route
  set ReplRoute = ReplServer.EnumRoutes(Iterator)

  'Quit if empty object returned (no more instances)
  if IsEmpty(ReplRoute) then exit do

  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  'If the route is Test, delete TestPC
  if ReplRoute.Name = Test then ReplRoute.DeleteDestination("TestPC")

loop
'Release objects
set ReplRoute  = Nothing
set ReplServer = Nothing

See Also

AddDestination , EnumDestination


ReplicationRoute Properties

© 1997-1998 Microsoft Corporation. All rights reserved.


BaseDirectory Property

This property specifies the base directory for the route.

Syntax

ReplicationRoute.BaseDirectory[=Dir]

Parameters

Dir

The base directory for the route. This must be an absolute path.

Remarks

The directory path must be absolute, it cannot be relative.

Example

The following example specifies \Stress as the base directory for the Test route.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim ReplRoute

do while True
  'Clear any error text
  Err.Clear
  'Get a route
  set ReplRoute = ReplServer.EnumRoutes(Iterator)

  'Quit if empty object returned (no more instances)
  if IsEmpty(ReplRoute) then exit do

  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  if ReplRoute.Name = Test then ReplRoute.BaseDirectory = "\Stress"

loop
'Release objects
set ReplRoute  = Nothing
set ReplServer = Nothing

See Also

Get, Put


Name Property

This property specifies the name of the route.

Syntax

ReplicationRoute.Name[=Name]

Parameters

Name

The name of the route.

Example

The following example retrieves and displays the names of all routes.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim ReplRoute

Wscript.Echo "The routes are:"

do while True
  'Clear any error text
  Err.Clear
  'Get a route
  set ReplRoute = ReplServer.EnumRoutes(Iterator)

  'Quit if empty object returned (no more instances)
  if IsEmpty(ReplRoute) then exit do

  'Quit if "No more items" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  Wscript.Echo ReplRoute.Name

Loop
'Release objects
set ReplRoute  = Nothing
set ReplServer = Nothing


ReplicationSchedule

The ReplicationSchedule object controls the schedule of when and how often replications are run. The following table briefly describes the ReplicationSchedule object's methods and properties.

Method | Description
Commit | Commits the schedule to the project
Remove | Removes the schedule from the project
Property | Description
Days | The days of the week to run the replication
Description | A description of the schedule
Hour | The hour of the day to run the replication
Minute | The minute of the hour to run the replication
RunOnce | The date and time when the replication is only run one time
ScheduledAction | The action (replicate or apply) scheduled for the project


CLSID and ProgID

ReplicationSchedule CLSID

4E28F5F0-1B3C-11d1-8C8C-00C04FC2D3B9

ReplicationSchedule ProgID

CrsApi.ReplicationSchedule

ReplicationSchedule is a dual-interface COM object.


Creating a ReplicationSchedule Object

You create a new ReplicationSchedule object by calling the ReplicationProject.AddSchedule method, as in the following example, where ReplSched is the name you give to the new ReplicationSchedule object:

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("MyProject", OPEN_EXISTING_PROJECT)

dim ReplSched
set ReplSched = ReplProject.AddSchedule
...

'Release objects
set ReplSched   = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing


Accessing a ReplicationSchedule Object

You access an existing ReplicationSchedule object by calling the ReplicationProject.EnumSchedules method, as in the following example, where ReplSched is the name you give to the new ReplicationSchedule object:

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("MyProject", OPEN_EXISTING_PROJECT)

dim ReplSched

do while True
  Err.Clear
  set ReplSched = ReplProject.EnumSchedules

  if IsEmpty(ReplSched) then exit do
  if ReplSched = CRS_ERROR_NO_MORE_ITEMS then exit do

  'We have a valid schedule
  ...

  'Release Schedule object
 loop
'Release objects
set ReplSched   = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing


ReplicationSchedule Methods

© 1997-1998 Microsoft Corporation. All rights reserved.


Commit Method

This property commits any changes to the schedule.

Syntax

ReplicationSchedule.Commit

Remarks

You must commit any changes to a schedule before they take effect.

Example

The following example creates a new schedule for project MyProject to replicate on Friday at 11:00 P.M.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const CRS_SCHEDULE_DAY_FRIDAY  = 16
const CRS_SCHEDULE_REPLICATE   = 2

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("MyProject", OPEN_EXISTING_PROJECT)

dim RepSched
set RepSched = ReplProject.AddSchedule

RepSched.Description = "The Friday night schedule."
RepSched.Days = CRS_SCHEDULE_DAY_FRIDAY
RepSched.Hour = 23
RepSched.ScheduledAction = CRS_SCHEDULE_REPLICATE
RepSched.Commit

'Release objects
set Sched       = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

ReplicationProject.AddSchedule, ReplicationProject.EnumSchedules


Remove Method

This method deletes the schedule from the project.

Syntax

ReplicationSchedule.Remove

Remarks

Example

The following example removes all of the schedules from the Test project.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("Test", OPEN_EXISTING_PROJECT)

dim Iterator
Iterator = 0

dim RepSched

do while True
  Err.Clear
  set RepSched = ReplProject.EnumSchedules(Iterator)

  if IsEmpty(RepSched) then exit do
  if RepSched = CRS_ERROR_NO_MORE_ITEMS then exit do

  RepSched.Remove

loop
'Release objects
set Sched       = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

ReplicationProject.AddSchedule, ReplicationProject.EnumSchedules


ReplicationSchedule Properties

© 1997-1998 Microsoft Corporation. All rights reserved.


Days Property

This property specifies on which days of the week the project replication occurs.

Syntax

ReplicationSchedule.Days[=Day]

Parameters

Day

The day of the week when the schedule is run.

Remarks

The following days are defined:

CRS_SCHEDULE_DAY_MONDAY | 1
CRS_SCHEDULE_DAY_TUESDAY | 2
CRS_SCHEDULE_DAY_WEDNESDAY | 4
CRS_SCHEDULE_DAY_THURSDAY | 8
CRS_SCHEDULE_DAY_FRIDAY | 16
CRS_SCHEDULE_DAY_SATURDAY | 32
CRS_SCHEDULE_DAY_SUNDAY | 64
CRS_SCHEDULE_DAILY | 255

Example

The following example creates a new schedule to replicate project Test on Mondays and Fridays at 3:00 P.M.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const CRS_SCHEDULE_DAY_MONDAY  = 1
const CRS_SCHEDULE_DAY_FRIDAY  = 16

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("Test", OPEN_EXISTING_PROJECT)

dim RepSched
set RepSched = ReplProject.AddSchedule
RepSched.Days = CRS_SCHEDULE_DAY_MONDAY and CRS_SCHEDULE_DAY_FRIDAY
RepSched.Hour = "15"

'Release objects
set Sched       = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

Hour, Minute, ReplicationProject.AddSchedule, ReplicationProject.EnumSchedules


Description Property

This property specifies a description of the schedule.

Syntax

ReplicationSchedule.Description[=Description]

Parameters

Description

A text string describing the schedule.

Remarks

Example

The following example adds a description to the new schedule for project Test.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const CRS_SCHEDULE_DAY_SUNDAY  = 64

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("Test", OPEN_EXISTING_PROJECT)

dim RepSched
set RepSched = ReplProject.AddSchedule
RepSched.Days = CRS_SCHEDULE_DAY_SUNDAY
RepSched.Hour = "1"
RepSched.Description = "Run every Sunday at 1AM"

'Release objects
set Sched       = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

ReplicationProject.AddSchedule, ReplicationProject.EnumSchedules


Hour Property

This property specifies the hour when the scheduled project is run.

Syntax

ReplicationSchedule.Hour

Parameters

ReplicationSchedule

The ReplicationSchedule object.

Remarks

Example

The following example runs project Test every day at 5:00 A.M.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT   = 2
const CRS_SCHEDULE_DAY_DAILY  = 255

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("Test", OPEN_EXISTING_PROJECT)

dim RepSched
set RepSched = ReplProject.AddSchedule
RepSched.Days = CRS_SCHEDULE_DAY_DAILY
RepSched.Hour = "5"

'Release objects
set Sched       = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

Minute, ReplicationProject.AddSchedule, ReplicationProject.EnumSchedules


Minute Property

This property specifies the minute when the scheduled project is run.

Syntax

ReplicationSchedule.Minute[=Minute]

Parameters

Minute

The minute when the scheduled project is run.

Remarks

Example

The following example runs MyProject on Saturdays at 8:30 A.M.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const CRS_SCHEDULE_SATURDAY  = 32

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("Test", OPEN_EXISTING_PROJECT)

dim RepSched
set RepSched = ReplProject.AddSchedule
RepSched.Days = CRS_SCHEDULE_DAY_SATURDAY
RepSched.Hour = "8"
RepSched.Minute = "30"

'Release objects
set Sched       = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

Hour, ReplicationProject.AddSchedule, ReplicationProject.EnumSchedules


RunOnce Property

This property specifies the date and time when a non-recurring schedule is run.

Syntax

ReplicationSchedule.RunOnce[=Date]

Parameters

Date

The date and time when the scheduled project is run.

Remarks

Example

The following example runs the Test project on July 4, 1998 at noon.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("MyProject", OPEN_EXISTING_PROJECT)

dim RepSched
set RepSched = ReplProject.AddSchedule
RepSched.RunOnce = "7/4/98 12:00"

'Release object
set Sched       = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

ScheduledAction


ScheduledAction Property

This property specifies which type of replication is performed by the project.

Syntax

ReplicationSchedule.ScheduledAction[=Action]

Parameters

Action

The type of action.

Remarks

The defined actions are as follows:

Action | Value | Description
CRS_SCHEDULE_APPLY | 1 | Apply changes but don't replicate content
CRS_SCHEDULE_REPLICATE | 2 | Replicate content

Example

The following example applies the changes to the schedule for project MyTest, but does not replicate any content.

Option Explicit
On Error Resume Next

const OPEN_EXISTING_PROJECT  = 2
const CRS_SCHEDULE_APPLY   = 1

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplProject
set ReplProject = ReplServer.OpenProject("MyTest", OPEN_EXISTING_PROJECT)

dim RepSched
set RepSched = ReplProject.AddSchedule

'Set up the schedule
...
'Save the changes
RepSched.ScheduledAction = CRS_SCHEDULE_APPLY

'Release object
set Sched       = Nothing
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

ReplicationProject.AddSchedule, ReplicationProject.EnumSchedules


ReplicationServer

The ReplicationServer object provides provides methods and properties to administer the Content Deployment server. The following table briefly describes the ReplicationServer object's methods and properties.

Method | Description
AddEventSink | Adds/opens an event sink.
AddRoute | Adds a route to the routing table and returns ReplicationRoute object
CheckAccess | Gets the current user's access permissions.
ClearEvents | Clears one or all event sinks.
Commit | Commits changes to Content Deployment
Continue | Continues Content Deployment after a pause request
DeleteEventSink | Removes an event sink.
DeleteProject | Deletes a project on the server
DeleteRoute | Deletes a route from the routing table
Enum | Lists the global parameters
EnumEventSinks | Lists the event sinks.
EnumProjects | Lists the projects.
EnumReplications | Lists the replications as ReplicationInstance objects
EnumRoutes | Lists the routes.
EnumServers | Lists the servers.
EventTimeToLocalTime | Converts a date to the local time zone
Get | Retrieves a global parameter
Initialize | Initializes the server
InitializeEx | Initializes the server under a different user.
MapUrl | Maps a URL to a project.
OpenPostingAcceptor | Opens a posting acceptor.
OpenProject | Opens a project.
Pause | Pauses the service
Put | Sets a global parameter
Start | Starts the server.
Stop | Stops the server.
Property | Description
ServerName | Name of the server connected to during initialization
UseTransactions | Whether transaction processing is done.


CLSID and ProgID

ReplicationServer CLSID

66D6D7ED-22D2-11D0-9B98-00C04FD5CD09

ReplicationServer ProgID

CrsApi.ReplicationServer

ReplicationServer is a dual-interface COM object.


Creating a ReplicationServer Object

You create a new ReplicationServer object by calling the CreateObject method, as in the following example, where ReplServer is the name you give to the new ReplicationServer object:

Option Explicit
On Error Resume Next

dim ReplServer
Set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")
...

'Release Server object
set ReplServer = Nothing

Once you have access to the ReplicationServer object, you must call the Initialize method to initialize the object before you can call any of its methods or set or get any of its properties.


ReplicationServer Methods

© 1997-1998 Microsoft Corporation. All rights reserved.


AddEventSink Method

This method either creates a new event sink or opens an existing event sink.

Syntax

ReplicationServer.AddEventSink(Sink)

Parameters

Sink

The name of the new event sink.

Remarks

You can set the various event sink object properties, but the object is not created until you call the ReplicationEventSink.Commit method on the event sink.

Example

The following example add the new event sink TestSink.

Option Explicit
On Error Resume Next

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplSink
set ReplSink = ReplServer.AddEventSink("TestSink")
...

'Release objects
set ReplSink   = Nothing
set ReplServer = Nothing

See Also

DeleteEventSink, EnumEventSinks


AddRoute Method

This method adds a route to the server’s routing table.

Syntax

ReplicationServer.AddRoute(Route)

Parameters

Route

Name of route to create. Use “Default” to create the default route for a machine.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

You can set the various route object properties, but the object is not created until you call the ReplicationRoute.Commit method on the new route.

Example

The following example creates a new default route.

Option Explicit
On Error Resume Next

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ReplRoute
set ReplRoute = ReplServer.AddRoute("Default")
...

'Release objects
set ReplRoute  = Nothing
set ReplServer = Nothing

See Also

EnumRoutes, ReplicationRoute.Commit


CheckAccess Method

This method retrieves the current user's access permissions on the Content Deployment server.

Syntax

ReplicationServer.CheckAccess

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

The access permissions are as follows:

Name | Value | Description
CRS_ADMIN_ACCESS | 983103 | The user has Site Server Publishing administrator access privileges
CRS_USER_ACCESS | 131097 | The user has Site Server Publishing operator access privileges

Example

The following example checks and displays the access rights of the current user.

Option Explicit
On Error Resume Next

const CRS_USER_ACCESS   = 0&20019
const CRS_ADMIN_ACCESS  = 0&F003F

dim ReplServer
set ReplServer = CreateObject("Crsapi.ReplicationServer")
ReplServer.Initialize("")

dim Perms
Perms = ReplServer.CheckAccess

if Perms = CRS_ADMIN_ACCESS then
 Wscript.Echo "You have administrator privileges on the server"
elseif Perms = CRS_USER_ACCESS
  Wscript.Echo "You have has user privileges on the server"
else
  Wscript.Echo "You have no privileges on the server"
end if

'Release Server object
set ReplServer = Nothing


ClearEvents Method

This method clears one or all event sinks.

Syntax

ReplicationServer.ClearEvents[(EventSink)]

Parameters

EventSink

The name of the event sink to clear. If Empty (""), all event sinks are cleared.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

See ReplicationServer.EnumEventSinks for a description of the default event sinks.

Example

The following example clears the database event sink.

Option Explicit
On Error Resume Next

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

ReplServer.ClearEvents(CRSDBSink)

'Release Server object
set ReplServer = Nothing

See Also

ReplicationServer.EnumEventSinks


Commit Method

This method commits changes to Content Deployment.

Syntax

ReplicationServer.Commit

Parameters

None.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

You must stop and start Content Deployment for the new values to take effect.

Example

The following example checks whether transaction processing is on, and if not, turns it on, commits the change, and stops and restarts the server.

Option Explicit
On Error Resume Next

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim TransProc
TransProc = ReplServer.UseTransactions

if TransProc = False then
  ReplServer.UseTransactions = True
  ReplServer.Commit
  ReplServer.Stop
  ReplServer.Start
end if

'Release Server object
set ReplServer = Nothing

See Also

Start, Stop


Continue Method

This method restarts the Content Deployment server after a pause request.

Syntax

ReplicationServer.Continue

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

Example

The following example pauses the server then restarts it.

Option Explicit
On Error Resume Next

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

ReplServer.Pause
...
ReplServer.Continue

'Release Server object
set ReplServer = Nothing

See Also

Pause , Start , Stop


DeleteEventSink Method

This method removes an event sink.

Syntax

ReplicationServer.DeleteEventSink(Sink)

Parameters

Sink

The name of the event sink to delete.

Remarks

Fails (Err.Number is set to E_FAIL) if Sink is Empty ("") or if the event sink specified by Sink does not exist.

Example

The following example deletes the MySink event sink.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_EVENTSINKS    = 15145
const CRS_ERROR_EVENTSINK_NOT_FOUND  = 15146

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

Err.Clear

ReplServer.Delete("MySink")

if Err.Number = CRS_ERROR_NO_EVENTSINKS then
  Wscript.Echo "No event sinks defined!"
elseif Err.Number = CRS_ERROR_EVENTSINK_NOT_FOUND then
  Wscript.Echo "Event sink MySink not found!"
end if

'Release Server object
set ReplServer = Nothing

See Also

AddEventSink, EnumEventSinks


DeleteProject Method

This method deletes a project on the server.

ReplicationServer.DeleteProject(Project)

Parameters

Project

The name of the project to delete.

Remarks

Example

The following example deletes the Project1 project.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_PROJECTS    = 15100
const CRS_ERROR_PROJECT_NOT_FOUND  = 15101

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

Err.Clear

ReplServer.DeleteProject("Project1")

if Err.Number = CRS_ERROR_NO_PROJECTS then
  Wscript.Echo "No projects defined!"
elseif Err.Number = CRS_ERROR_PROJECT_NOT_FOUND then
  Wscript.Echo "Project1 not found!"
end if

'Release Server object
set ReplServer = Nothing

See Also

OpenProject, EnumProjects


DeleteRoute Method

This method deletes a route from the server’s routing table.

Syntax

ReplicationServer.DeleteRoute(Route)

Parameters

Route

The route to delete.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

Example

The following example deletes the Test route.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_ROUTES    = 15110
const CRS_ERROR_ROUTE_NOT_FOUND  = 15109

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

Err.Clear
ReplServer.DeleteRoute("Test")

if Err.Number = CRS_ERROR_NO_ROUTES then
  Wscript.Echo "No routes defined!"
elseif Err.Number = CRS_ERROR_ROUTE_NOT_FOUND then
  Wscript.Echo "Route Test not found!"
end if

'Release Server object
set ReplServer = Nothing

See Also

AddRoute , EnumRoutes


Enum Method

This method lists the global parameters for the Content Deployment service.

Syntax

ReplicationServer.Enum(Iterator, ParamName)

Parameters

Iterator

Used by the service to enumerate the list of parameters. This value should be initialized to zero, and should not be modified.

ParamName

Used by the service to enumerate the names of the parameters. This value should be initialized to an empty string, "", and should not be modified.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

For a list of parameters that can be retrieved from the Content Deployment service, see the Parameters appendix.

Example

The following example displays the names and values of the service parameters.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim ParamName
ParamName = ""
dim ParamValue
dim Iterator
Iterator = 0
dim ReplError

do while True
  'Clear any error text
  Err.Clear

  ParamValue = ReplServer.Enum(Iterator, ParamName)

  'Quit if "No more items" error

  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  Wscript.Echo "Parameter " & ParamName & " = " & ParamValue
Loop
'Release Server object
set ReplServer = Nothing

See Also

EnumProjects , EnumReplications , EnumRoutes


EnumEventSinks Method

This method lists all event sinks.

Syntax

ReplicationServer.EnumEventSinks(Iterator)

Parameters

Iterator

Used by the service to enumerate the list of parameters. This value should be initialized to zero, and should not be modified.

Remarks

The following event sink ProgIDs are defined:

CRSSink.CRSDBSink

The local database event sink. This event sink is also identified by its Name property, CRSLocalEvents.

CRSSink.CRSSink

The store-and-forward (to another Content Deployment site server) event sink

CRSSink.CRSMailSink

The mail event sink. . This event sink is also identified by its Name property, Mail.

CRSSink.CRSNTSink

The NT event sink. . This event sink is also identified by its Name property, NT.

Example

The following example displays the names of all event sinks.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim ReplError
dim EvSink
Wscript.Echo "The server has the following event sinks"

do while True
  'Clear any error text
  Err.Clear

  set ReplSink = ReplServer.EnumEventSinks(Iterator)

  'Quit if ReplSink is NUL
  if IsEmpty(ReplSink) then exit do

  'Quit if "No more items" error
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  Wscript.Echo ReplSink.Name

Loop
'Release objects
set ReplSink   = Nothing
set ReplServer = Nothing

See Also

AddEventSink, DeleteEventSink, ReplicationEventSinkConfig


EnumProjects Method

This method lists the projects on a server.

Syntax

ReplicationServer.EnumProjects(Iterator)

Parameters

Iterator

Used by the service to enumerate the list of parameters. This value should be initialized to zero, and should not be modified.

Remarks

This method returns CRS_ERROR_NO_PROJECTS when there are no projects defined on the server.

Example

The following example displays the names of the projects on the server.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_PROJECTS  = 15100
const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Project
dim Iterator
Iterator = 0
Wscript.Echo "The projects are:"

do while True
  'Clear any error text
  Err.Clear

  'Get the next project
  set ReplProject = ReplServer.EnumProjects(Iterator)

  'Display error message and
  'Quit if empty object returned (no more instances)
  if IsEmpty(ReplProject) then
    Wscript.Echo "Empty project object returned."
    exit do
  end if

  'Display error message and
  'Quit if "No projects defined" error
  dim ReplError
  ReplError = Err.Number
  if ReplError = CRS_NO_PROJECTS then
    Wscript.Echo "No projects defined."
    exit do
  end if

  'Display error message and
  'Quit if "No more items" error (we've reached the end of the list)
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  Wscript.Echo ReplProject.Name

Loop
'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

DeleteProject, OpenProject, ReplicationProject


EnumReplications Method

This method lists the replications that meet a filter criteria.

Syntax

ReplicationServer.EnumReplications(Project, State, Iterator)

Parameters

Project

The name of the project to filter. If Empty (""), filter all projects.

State

The state of the replications that are listed.

Name | Value | Description
REPL_STATE_EMPTY | 0 | Return all replications.
REPL_STATE_STARTING | 1 | Return only starting replications.
REPL_STATE_RUNNING | 2 | Return only running replications.
REPL_STATE_COMPLETE | 3 | Return only completed replications.
REPL_STATE_ABORTED | 4 | Return only aborted replications.
REPL_STATE_CANCELED | 5 | Return only canceled replications.
REPL_STATE_RECEIVING | 6 | Return only receiving replications.
REPL_STATE_PENDING | 7 | Return only pending replications.

Iterator

Used by the service to enumerate the list of parameters. This value should be initialized to zero, and should not be modified.

Remarks

Example

The following example displays the names of all replications that are pending.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17
const REPL_STATE_PENDING   = 7

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim ReplError
Wscript.Echo "The following replications are pending:"

do while True
  'Clear any error text
  Err.Clear
  Set ReplInst = ReplServer.EnumReplications( "", REPL_STATE_PENDING, Iterator )

  if IsEmpty(ReplInst) then exit do

  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  Wscript.Echo Replication.Name

Loop

'Release objects
set ReplInst   = Nothing
set ReplServer = Nothing

See Also

ReplicationInstance


EnumRoutes Method

This method lists the routes defined on a server.

Syntax

ReplicationServer.EnumRoutes(Iterator)

Parameters

Iterator

Used by the service to enumerate the list of parameters. This value should be initialized to zero, and should not be modified.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

This method returns CRS_ERROR_NO_ROUTES when there are no routes defined on the server.

Example

The following example displays the names of the routes on the Content Deployment server.

Option Explicit
On Error Resume Next

const CRS_ERROR_NO_ROUTES    = 15110
const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim Routes
dim ReplError
Wscript.Echo "The content deployment server has the following routes"

do while True
  'Clear any error text
  Err.Clear

  set ReplRoute = ReplServer.EnumRoutes(Iterator)
  if IsEmpty(ReplRoute) then exit do

  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_ROUTES then exit do
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  Wscript.Echo ReplRoute.Name

Loop
'Release objects
set ReplRoute  = Nothing
set ReplServer = Nothing

See Also

AddRoute, DeleteRoute, ReplicationRoute


EnumServers Method

This method lists the Content Deployment servers.

Syntax

ReplicationServer.EnumServers(Iterator, ServerType)

Parameters

Iterator

Used by the service to enumerate the list of parameters. This value should be initialized to zero, and should not be modified.

ServerType

The type of server listed. The types are:

Server Type | Value | Description
STAGER | 1 | A staging server.
ENDPOINT | 2 | A destination server.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

Example

The following example displays the names of the Content Deployment staging servers.

Option Explicit
On Error Resume Next

const STAGER       = 1
const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim ReplError
dim Server
Wscript.Echo "The Content Deployment staging servers are:"

do while True
  'Clear any error text
  Err.Clear

  set Server = ReplServer.EnumServers(Iterator, STAGER)
  if IsEmpty(ReplServer) then exit do

  'Quit if "No more items" error
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  Wscript.Echo ReplServer.Name

Loop
'Release objects
set Server     = Nothing
set ReplServer = Nothing

See Also

ReplicationServer.ServerName


EventTimeToLocalTime Method

This method converts a date to the local time zone.

Syntax

ReplicationServer.EventTimeToLocalTime(Time)

Parameters

Time

The event time to convert.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

By default, the event time is in Greenwich Mean Time (GMT).

Example

The following example converts the event time.

Option Explicit
On Error Resume Next

const STAGER       = 1
const CRS_ERROR_NO_MORE_ITEMS  = 0&80003B17

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

ReplServer.EventTimeToLocalTime Time

'Release objects
set Server     = Nothing
set ReplServer = Nothing


Get Method

This method retrieves a global parameter for the Content Deployment service.

Syntax

ReplicationServer.Get(ParamName)

Parameters

ParamName

The name of the parameter to retrieve. Parameter names are not case sensitive.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

For a list of parameters that can be retrieve from Content Deployment, see the Parameters appendix.

Example

The following example displays the value of the TransactionMethod parameter for the Test staging server.

Option Explicit
On Error Resume Next

const STAGER  = 1

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Iterator
Iterator = 0
dim ReplError
dim Server
dim Name

do while True
  'Clear any error text
  Err.Clear

  set Server = ReplServer.EnumServers(Iterator, STAGER)
  if IsEmpty(ReplServer) then exit do

  'Quit if "No more items" error
  ReplError = Err.Number
  if ReplError = CRS_ERROR_NO_MORE_ITEMS then exit do

  Name = ReplServer.Name
  if Name = "Test" then
    dim TransMethod
    TransMethod = ReplServer.Get("TransactionMethod")
    if TransMethod = True then
    Wscript.Echo "Test has transaction processing."
    else
    Wscript.Echo "Test does not have transaction processing."
    end if
  endif

Loop
'Release objects
set Server     = Nothing
set ReplServer = Nothing

See Also

ServerName, Put, UseTransactions


Initialize Method

This method initializes the ReplicationServer object.

Syntax

ReplicationServer.Initialize[(Server)]

Parameters

Server

The server to communicate with. This value can be Empty ("") for the current server.

Remarks

This method must be called before any other methods.

Example

The following example initializes the current server.

Option Explicit
On Error Resume Next

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")
...

'Release Server object
set ReplServer = Nothing

See Also

InitializeEx


InitializeEx Method

This method initializes the server under a different user name and password.

Syntax

ReplicationServer.InitializeEx(Server, UserName,Password, Timeout)

Parameters

Server

The server to communicate with. This value can be Empty ("") for the current server.

UserName

The name of the user to log onto the server as.

Password

The password of the user UserName on server Server.

Timeout

The time, in milliseconds, to wait for the server to initialize before timing out. The default is 300000 (5 minutes).

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

Example

The following example initializes the current server under user Steveb, with password Oxymoron.

Option Explicit
On Error Resume Next

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

ReplServer.InitializEx("", Steveb, Oxymoron)
...

'Release Server object
set ReplServer = Nothing

See Also

Initialize


MapUrl Method

This method maps a URL to a project.

Syntax

ReplicationServer.MapUrl(URL, Suffix)

Parameters

URL

Destination URL.

Suffix

Set this argument to Empty ("") before calling this method. Content Deployment returns the relative path from the base project directory that maps to the destination URL.

Remarks

MapURL finds the best match of a given URL to a Content Deployment project.

Example

The following example retrieves and displays the project that best matches the URL http://www.mymachine.com/.

Option Explicit
On Error Resume Next

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Project
dim Suffix
Suffix = ""

set Project = ReplServer.MapURL("http://www.mymachince.com/", Suffix)

if IsEmpty(Project) then
  Wscript.Echo "No project maps to http://www.mymachine.com/."
else
  Wscript.Echo "Project" & Project.Name & "maps to http://www.mymachine.com/."
  Wscript.Echo "The suffix is: " & Suffix
end if

'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing


OpenPostingAcceptor Method

This method retrieves the posting acceptor object.

Syntax

ReplicationServer.OpenPostingAcceptor

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

Example

The following example opens the posting acceptor object.

Option Explicit
On Error Resume Next

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim POST
set POST = ReplServer.OpenPostingAcceptor
...

'Release objects
set POST       = Nothing
set ReplServer = Nothing

See Also

ReplicationPostingAcceptor


OpenProject Method

This method either opens an existing project or creates a new project.

Syntax

ReplicationServer.OpenProject(Project, ProjectFlag)

Parameters

Project

The name of the project to open.

ProjectFlag

Whether to open an existing project or create a new project. Use one of the following values.

Project Flag | Value | Description
CREATE_NEW_PROJECT | 1 | Creates a new project
OPEN_EXISTING_PROJECT | 2 | Opens an existing project

Remarks

Note

Content Deployment sets the ReplicationProject.Name property to the Project argument that you use when ProjectFlag is CREATE_NEW_PROJECT.

Example

The following example opens the existing project Project2.

Option Explicit
On Error Resume Next

const OPEN_NEW_PROJECT   = 1
const OPEN_EXISTING_PROJECT  = 2

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

dim Project
set Project = ReplServer.OpenProject("Project2", OPEN_EXISTING_PROJECT)
...

'Release objects
set ReplProject = Nothing
set ReplServer  = Nothing

See Also

DeleteProject , EnumProjects


Pause Method

This method pauses the Content Deployment server.

Syntax

ReplicationServer.Pause

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

Pausing means that the Content Deployment server rejects any requests to start a new replication. It does not stop any currently running replications.

Example

The following example pauses the server then restarts it.

Option Explicit
On Error Resume Next

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

ReplServer.Pause
...
ReplServer.Continue

'Release Server object
set ReplServer = Nothing

See Also

Continue , Start , Stop


Put Method

This method sets a global parameter for Content Deployment.

Syntax

ReplicationServer.Put(ParamName, ParamValue)

Parameters

ParamName

The name of the parameter to set. Parameter names are not case sensitive.

ParamValue

The parameter value.

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

Parameters are cached locally and are not applied to the Content Deployment service until you call the ReplicationServer.Commit method.

For a list of parameters that can be retrieved from Content Deployment, see the Parameters appendix.

Note You must explicitly cast any whole number value that you assign to a global parameter to a 32-bit (long) integer with CLng(), as shown in the following example.

Example

The following example sets the Depth parameter (the depth of the replication) to 3.

Option Explicit
On Error Resume Next

dim ReplServer, Depth
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

Depth = Clng(3)

ReplServer.Put("Depth", Depth)
ReplServer.Commit

'Release Server object
set ReplServer = Nothing

See Also

Get


Start Method

This method starts Content Deployment.

Syntax

ReplicationServer.Start

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

To start Content Deployment on a machine other than the local machine, use the ReplicationServer.Initialize method to set the machine name, call the ReplicationServer.Start method to start Content Deployment, and then call the ReplicationServer.Initialize method again before using the ReplicationServer object.

Example

The following example starts the local Content Deployment server.

Option Explicit
On Error Resume Next

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

...
ReplServer.Start

'Release Server object
set ReplServer = Nothing

See Also

Continue , Pause , Stop


Stop Method

This method stops Content Deployment.

Syntax

ReplicationServer.Stop

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

Example

The following example stops Content Deployment.

Option Explicit
On Error Resume Next

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

...
ReplServer.Stop

'Release Server object
set ReplServer = Nothing

See Also

Continue , Pause , Start


ReplicationServer Properties

© 1997-1998 Microsoft Corporation. All rights reserved.


ServerName Property

This property specifies the name of the server.

Syntax

ReplicationServer. ServerName

Remarks

Example

The following example displays the name of the server.

Option Explicit
On Error Resume Next

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

Wscript.Echo "The name of the server is: " & ReplServer.ServerName

'Release Server object
set ReplServer = Nothing

See Also

Get, Put


UseTransactions Property

This property specifies the transaction model for the service.

Syntax

ReplicationServer.UseTransactions

Remarks

You must have Site Server Publishing administrator privileges on the server to call this method.

Example

The following example specifies that the service uses transactions.

Option Explicit
On Error Resume Next

dim ReplServer
set ReplServer = CreateObject("CrsApi.ReplicationServer")
ReplServer.Initialize("")

ReplServer.UseTransactions = True

'Release Server object
set ReplServer = Nothing

See Also

Get, ReplicationProject.ApplyTransaction


Flags

This section describes the Content Deployment flags for the ReplicationInstance.Flags method. You can use individual flags by defining them in your VBScript code, as follows:

const RF_UNINSTALL         = 0x2000

However, if you need to examine a large number of possible flags, add the flags to a file, such as Flags.inc, and include that file in the VBScript code of an ASP file, as follows:

<!--#include file = "Events.inc"-->

The following table lists the default flags, their defined values, and a brief description.

Name | Value | Description
RF_AUTO_ROUTE | 512 | Use routing table to create/run the project.
RF_EXCLUDE_ALL | 4096 | Do not replicate subdirectories. Replicate only the current directory.
RF_FASTMODE | 128 | Use the fast replication mode.
RF_FORCE_REPL | 8 | Force replication of all files.
RF_INCREMENTAL | 64 | Only replicate files with different timestamps.
RF_IN_PROC | 32 | Run in process.
RF_NO_CHAIN | 2048 | Do not chain.
RF_NO_DATA | 4 | Do not replicate files, only directories.
RF_NO_DELETE | 1 | Do not delete files on the destination computer.
RF_ON_DIR_CHANGE | 256 | Monitor directory for changes and replicate them immediately.
RF_ON_NOTIFY | 1024 | Accept notifications for this project from the AcceptNotify object.
RF_PERMIT_TREE | 16 | Apply ACLs on source to destination. No files are transferred.
RF_REPLICATE_ACLS | 2 | Replicate both files and ACLs.

You can specify the following project settings to override default project setting values. You should only specify these settings when you start an existing project, never when you create a new project.

Flag | Value | Description
RF_ACLS_ONLY | 16384 | Replicate only ACLs, not files.
RF_CHAIN | 33554432 | Chain.
RF_DATA | 65536 | Replicate files and directories.
RF_DELETE | 16384 | Delete files on the destination computer.
RF_UNINSTALL | 8192 | Do not replicate subdirectories. Replicate only the current directory. This value can be used when creating a project, but can never be overridden.
RF_NO_AUTO_ROUTE | 8388608 | Do not auto route. Should never be used.
RF_NO_FASTMODE | 2097152 | Do not run in fast mode.
RF_NO_FORCE_REPL | 131072 | Do not force replication of current files.
RF_NO_IN_PROC | 524288 | Do not run in process.
RF_NO_INCREMENTAL | 1048576 | Do not run in incremental mode.
RF_NO_ON_DIR_CHANGE | 41094304 | Do not run in directory changes mode.
RF_NO_ON_NOTIFY | 16777216 | Do not run in notify mode.
RF_NO_PERMIT_TREE | 262144 | Do not do a permit function.
RF_NO_REPLICATE_ACLS | 32768 | Do not replicate ACLs.


Error Handling

Whenever you call a Content Deployment method or get or set a Content Deployment property, you should check the Err Object’s number property for an error code. If the method or property was successful, Content Deployment sets the value of number to 0.

For example:

if (Err.Number <> 0) then
  Wscript.Echo "Error :   " & Err.Number
  Wscript.Echo "Description: " & Err.Description
end if

Note that Content Deployment makes internal calls to other programming APIs, including COM, Security/ACL, Registry, Winsock, Service Manager, and Win32. These APIs can return error codes in addition to the given Content Deployment error codes.

Severity Codes

The high nibble of the Error ID indicates the severity of the error.

Nibble | Severity
4 | Informational
8 | Warning
C | Error


Status Codes

Status Codes

Status Code | Name | Description
0 | E_NOERROR | The operation completed successfully.
00003AAA | CRS_REPLICATION_COMPLETED | Replication for project completed successfully.
00003ABB | CRS_ERROR_WOULDBLOCK | The network operation would block.
00003AFF | CRS_PROJECT_CREATED | Successfully created project.
00003B2F | CRS_EVENTSINK_INITIALIZED | The event sink was successfully initialized.
0000274C | WINSOCK_WSAETIMEDOUT | The network session timed out on a send or receive operation.
0000274D | WINSOCK_WSAECONNREFUSED | The remote server was not listening on the appropriate port. This generally indicates that the service was not running but the machine is up
00002733 | WINSOCK_WSAEWOULDBLOCK | The network operation would block.
00002742 | WINSOCK_WSAENETDOWN | The remote network is down.
00002743 | WINSOCK_WSAENETUNREACH | The remote network is unreachable.
00002745 | WINSOCK_WSAECONNABORTED | The network connection was aborted at the network layer.
00002746 | WINSOCK_WSAECONNRESET | The network session was aborted.
40003A98 | CRS_ERROR_FIRST | Content replication services first error message.
40003AA7 | CRS_SERVICE_STARTED | Content Replication System service started successfully.
40003AA8 | CRS_SERVICE_SHUTDOWN | Content Replication System service shutdown successfully.
40003AA9 | CRS_REPLICATION_STARTED | Replication for project started.
40003B1A | CRS_FILE_MATCHED | File matched.
40003B3B | CRS_RESUME_REPLICATION | Resuming replication for project.
80003B17 | CRS_ERROR_NO_MORE_ITEMS | There are no more items in the list.
80003B21 | CRS_ERROR_EDGE_EXISTS | Edge already exists in topology map.
C0003B1B | CRS_ERROR_OPENING_FILE | Error opening file or file not found.
C0003A9D | CRS_ERROR_ACCESS_DENIED | Access Denied.
C0003A9E | CRS_FILE_CREATE_ERROR | Replication was aborted due an inability to open a file locally.
C0003A9F | CRS_SENDINET_ERROR | The replication was aborted during the SENDINET operation due to an inability to send a file.
C0003AA1 | CRS_BAD_SOURCE | Unable to access the replication source.
C0003AA2 | CRS_SENDINET_CONNECT | Unable to connect to the remote server in a SENDINET operation.
C0003AA3 | CRS_HASH_MISMATCH | The MD5 Hash did not match during a transmission. This could indicate transmission failure or that the files transmitted at the source have been modified in transit.
C0003AA4 | CRS_SERVER_ABORTED | The remote server was aborted. This replication request is being aborted. Please re-run the replication for project.
C0003AA5 | CRS_REPLICATION_ABORTED | The Replication was aborted.
C0003AA6 | CRS_SEQUENCE_ERROR | An internal messaging sequence error occurred.
C0003AAB | CRS_AUTH_FAILURE | Authorization failure against server.
C0003AAC | CRS_REMOTE_AUTH_FAILURE | Remote authorization failed to server.
C0003AAD | CRS_ERROR_NOT_IN_ORDER | A message was received out of order. Aborting connection.
C0003AAE | CRS_CONNECTION_RETRY_FAILED | The replication is aborting due to connection that failed and could not be re-established within a reasonable time.
C0003AAF | CRS_ERROR_REPLICATION_CANCELED | Replication cancelled at the request of the user.
C0003AB1 | CRS_ERROR_NO_IP_MAPPING | Can not resolve IP address for hostname. No virtual root created.
C0003AB2 | CRS_ERROR_DISK_FULL | There is not enough space on the disk.
C0003AB3 | CRS_ERROR_TOO_MANY_RUNNING | There are too many active replications. No more can be started until others complete.
C0003ACA | CRS_ERROR_NETDOWN | The remote network is down.
C0003ACB | CRS_ERROR_NETUNREACH | The remote network is unreachable.
C0003ACD | CRS_ERROR_CONNABORTED | The network connection was aborted at the network layer.
C0003AD4 | CRS_ERROR_TIMEOUT | The network session timed out on a send or receive operation.
C0003AFC | CRS_ERROR_NO_PROJECTS | There are no projects defined.
C0003AFD | CRS_ERROR_PROJECT_NOT_FOUND | Could not find project.
C0003AFE | CRS_ERROR_INVALID_PARAMETER | Invalid parameter.
C0003B00 | CRS_ERROR_AUTHENTICATION_FAILURE | Authentication failure. Ensure CRS account has proper access on local and remote machines.
C0003B02 | CRS_ERROR_SERVICE_NOT_RUNNING | The machine is available but the CRS service is not running.
C0003B03 | CRS_ERROR_HOST_DOWN | The machine is unavailable.
C0003B04 | CRS_ERROR_BAD_NET_NAME | The machine can not be found.
C0003B05 | CRS_ERROR_ROUTE_NOT_FOUND | Could not find route.
C0003B06 | CRS_ERROR_NO_ROUTES | There are no routes defined for this machine.
C0003B08 | CRS_ERROR_SERVICE_PAUSED | The CRS service has been paused and is not accepting new requests.
C0003B09 | CRS_ERROR_SERVICE_NOT_PAUSED | Could not restart service, service is not paused.
C0003B0A | CRS_ERROR_NAME_NOT_RESOLVED | Could not resolve URL for project.
C0003B0B | CRS_ERROR_CONNECTION_RESET | Connection to server has been reset. This indicates problems with the remote service or network.
C0003B0C | CRS_ERROR_REPLICATION_NOT_FOUND | No replications found.
C0003B0D | CRS_ERROR_SERVICE_ALREADY_RUNNING | Could not start service. The service has already been started.
C0003B0E | CRS_ERROR_PROJECT_ALREADY_RUNNING | Failed to start replication. The project is already running.
C0003B0F | CRS_ERROR_FILE_MOVE_ERROR | Failed to move file.
C0003B10 | CRS_ERROR_PRODUCT_EXPIRED | Your software has expired.
C0003B11 | CRS_ERROR_PROJECT_INCOMPLETE | The project information is incomplete.
C0003B12 | CRS_ERROR_PARAMETER_NOT_FOUND | Parameter not found.
C0003B13 | CRS_ERROR_REPLICATION_RUNNING | A replication is currently running for the project. The project could not be deleted.
C0003B14 | CRS_ERROR_INVALID_PROJECT_NAME | The project name is invalid. Project names can not contain backslashes or DBCS characters and can not be empty.
C0003B15 | CRS_ERROR_INVALID_ROUTE_NAME | The route name is invalid. Route names can not contain backslashes or DBCS characters and can not be empty.
C0003B16 | CRS_ERROR_INVALID_DWORD | The parameter must be a positive integer.
C0003B18 | CRS_ERROR_TOO_MANY_ARGS | Too many arguments specified.
C0003B19 | CRS_MBS_INIT_ERROR | CRS aborting ACL replication due to an inability to initialize the Microsoft Membership System.
C0003B1C | CRS_ERROR_FILE_FORMAT | Invalid file format.
C0003B1D | CRS_ERROR_FILE_WRITE | Error writing to file.
C0003B1E | WINSOCK_WSAHOSTNAME | Gethostname failed.
C0003B1F | CRS_ERROR_NODE_EXISTS | Node already exists in the topology map.
C0003B20 | CRS_ERROR_NODE_NOT_FOUND | Node not found in topology map.
C0003B22 | CRS_ERROR_ROOTNODE_NOT_FOUND | Root node does not exist in topology map.
C0003B23 | CRS_ERROR_PATH_NOT_FOUND | No path to from root to node in topology map.
C0003B24 | CRS_ERROR_EDGE_NOT_FOUND | Edge does not exist in topology map.
C0003B25 | CRS_ERROR_INVALID_CONTEXT | The current context is invalid. Replication being reset.
C0003B26 | CRS_ERROR_DOWNLEVEL_SERVER | The operation is not supported on a down-level server.
C0003B27 | CRS_ERROR_NO_MAPPING | The URL does not map to any project definitions.
C0003B28 | CRS_ERROR_START_PENDING | Start pending finish of the previous replication.
C0003B29 | CRS_ERROR_NO_EVENTSINKS | There are no event sinks defined.
C0003B2A | CRS_ERROR_EVENTSINK_NOT_FOUND | Could not find event sink.
C0003B2B | CRS_ERROR_WSAHOSTNOTFOUND | Host not found.
C0003B2C | CRS_ERROR_WSATRYAGAIN | Host not found, or SERVERFAIL.
C0003B2D | CRS_ERROR_WSANORECOVERY | Non-recoverable winsock error.
C0003B2E | CRS_ERROR_WSANODATA | Invalid address.
C0003B30 | CRS_ERROR_EVENTSINK_NOT_INITIALIZED | The event sink failed to initialize.
C0003B31 | CRS_ERROR_NOTHING_TO_ROLLBACK | Could not rollback project. No rollback information found.
C0003B32 | CRS_ERROR_NO_DESTINATIONS | The replication could not be started because there are no destinations defined.
C0003B33 | CRS_ERROR_REAUTHENTICATE | Please re-authenticate using an acceptable protocol.
C0003B34 | CRS_ERROR_UNSUPPORTED | This function is not supported in this version of Publishing Manager.
C0003B35 | CRS_ERROR_USER_NOT_FOUND | The specified user could not be found.
C0003B36 | CRS_ERROR_NO_TRANSACTIONS | There are no outstanding transactions for the specified project.
C0003B37 | CRS_ERROR_NO_SERVERS | There are no destination servers defined.
C0003B38 | CRS_ERROR_NO_SCHEDULES | There are no schedules defined for this project.
C0003B39 | CRS_ERROR_NO_EMAIL | Could not contact SMTP to send email for report on project.
C0003B3A | CRS_ERROR_WAIT_ABORT | Waiting abort on project after losing connection with source machine.
C0003B3C | CRS_METABASE_NOT_FOUND | The Metabase is not responding.
C0003B3D | CRS_SSE_VROOT_NOT_FOUND | SiteServer virtual root not found.
C0003B3E | CRS_ERROR_SCHEDULE_NOT_FOUND | The specified project schedule could not be found.
C0003B3F | CRS_ERROR_DROPPED_EMAIL_REPORT | Dropped EMail Report.
C0003B40 | CRS_ERROR_EMAIL_HOST_NOT_DEFINED | No SMTP Server declared.


Parameters

This section describes the Content Deployment parameters. There are global parameters and parameters applying to pull and push operations.

Unless otherwise noted, the parameters are strings with a maximum length of 300 characters, which can be 300 Unicode characters, since Site Server supports the Unicode character set.


Global Parameters

The following parameters apply to all Content Deployment replications.

Name | Description
TransactionMethod | "Yes" or "No". Determines whether or not to use transaction processing.
MailHost | The name of the SMTP mail host.


Pull Parameters

The following parameters are required for all pull replications.

Name | Description
ReplicationMethod | Set the ReplicationProject.ReplicationMethod property to "PULL" for pull projects.
RootUrl | This parameter is the URL from which to pull data; for example, “http://www.microsoft.com/”.
LocalDirectory | Set the ReplicationProject.LocalDirectory property to the name of the local directory to store the information. Cannot be NULL.
Depth | This parameter is the depth of the replication. For HTTP, this is the number of times to follow links off of the root page. For FTP, this is the depth to go in the directory structure.
CernProxy (optional) | Name of the proxy server for HTTP pull replications.
UserName (optional) | User name for secure sites.
Password (optional) | Password for secure sites.
MailTo (optional) | User name to mail to when replication completes.
MailToFail (optional) | User name to mail to when replication fails.
MailToSuccess (optional) | User name to mail to when replication succeeds.
BeforeReceiveScript (optional) | Script to run before receiving files.
AfterReceiveScript (optional) | Script to run after receiving files.


Push Parameters

The following parameters are required for all push replications.

Name | Description
ReplicationMethod | Set the ReplicationProject.ReplicationMethod property to "SENDINET" for Push projects.
Destination | This parameter is a list of the names of all servers to receive the replication. Can be NULL if there is no destination. If creating a project using routes, it must be the name of the route. The list cannot exceed 4096 characters.
LocalDirectory | This property is the name of the local directory used to send or receive the content. This parameter cannot be NULL.
Flags | This (VarType = vbLong) property consists of one or more defined bitmapped values (see Flags)
MapUrl (optional) | The name of the URL that maps to the local directory. For example, "http://www.microsoft.com/Cinemania" could map to the local directory "C:\Microsoft\Cinemania".
ExcludeDir (optional) | The name of a directory to exclude from replication.
MailTo (optional) | The name of the user towhom mail is sent if a replication completes.
MailToFail (optional) | The name of the user towhom mail is sent if a replication fails.
MailToSuccess (optional) | The name of the user towhom mail is sent if a replication succeeds.
AfterSendScript (optional) | The script to execute after sending files.
BeforeReceiveScript (optional) | The script to execute before receiving new files.
BeforeSendScript (optional) | The script to execute before sending files.
AfterReceiveScript (optional) | The script to execute after receiving files.


Events

Content Deployment can issue different levels of events. The following table briefly describes these event levels.

Name | Value | Description
CRSEVENT_SEVERITY_SUCCESS | 0 | The operation completed successfully.
CRSEVENT_SEVERITY_INFORMATIONAL | 1 | There is some additional informational information available about the operation.
CRSEVENT_SEVERITY_WARNING | 2 | The operation generated a warning.
CRSEVENT_SEVERITY_ERROR | 3 | The operation generated an error.

Content Deployment can issue different categories of events. The following table briefly describes these event categories.

Name | Value | Description
CRSEVENT_CATEGORY_GENERAL | 0 | General error and other events.
CRSEVENT_ CATEGORY_FILE | 1 | File events, such as sending a file.
CRSEVENT_ CATEGORY_REPLICATION | 2 | Replication events, such as a replication has started.
CRSEVENT_ CATEGORY_ADMIN | 3 | Project events, such as a project was created.
CRSEVENT_ CATEGORY_SUMMARY | 4 | Summary events, such as a replication summary.

You can filter different types of Content Deployment events. The following table briefly describes these event filters, which you can OR together to specify the event types the event sink receives.

Name | Value | Description
EVFLAG_FILE_EVENTS | 1 | File events.
EVFLAG_ADMIN_EVENTS | 2 | Administrative events.
EVFLAG_SUMMARY_EVENTS | 4 | Summary events.
EVFLAG_REPLICATION_EVENTS | 8 | Replication events.
EVFLAG_ALL | 255 | All events.


Active Channel Server SDK

Welcome to the Active Channel Server Software Development kit! This kit contains documentation and samples that developers can use to aid their efforts in using and extending the functionality of the Active Channel Server feature of Microsoft Site Server 3.0.

What this Kit Contains

This kit is composed of the following parts:

Documentation

The documentation is composed of the following:

Programmer's Guide

The Programmer's Guide is a roadmap for extending the product, providing topical information to developers so that they can quickly and easily begin harnessing the power of the Active Channel Server feature.

Programmer's Reference

The Programmer's Reference contains technical information about Active Channel Server COM objects and the built-in Active Channel Server Agents.

Sample

The sample demonstrates a working example of extending the Active Channel Server through the creation of a custom agent. The sample can be found in the Samples\SiteServer\push\ directory of the installation.

Periodically, updates to the Site Server 3.0 SDK will be included in the Microsoft Platform SDK monthly release, which will be made available on the Microsoft Developer's Network web site at http://www.microsoft.com/msdn/sdk/siteserver.htm.

Prerequisites

The following software is required to take advantage of this SDK:

Software

  • Microsoft Site Server 3.0 Standard Edition or Commerce Edition.

  • A development environment that supports the COM.

General

  • Familiar with the Component Object Model (COM) and Automation.

  • Familiar with a scripting language such as VBScript and Jscript.

Additionally, to build a fully installable Active Channel Server Agent, one must be familiar with constructing ASP pages and Windows GUI elements implemented using the IPropertyPage interface.


About Active Channel Server

With the advent of the Channel Definition Format specification, an open standard has emerged for web content developers to provide users with focused and organized information about related available resources. Using the CDF empowers the end user with a simple and highly specific system to organize and automatically retrieve the resources on a network that they find interesting or essential. The CDF specification empowers the web content developer by allowing the presentation of sets of related resource data to the end client in a natural, intuitive, and effective way. However, web developers using push technology face the arduous task of routinely organizing new content for inclusion in channels. At its worst, this means routinely updating the CDF information about new content by hand.

Enter Active Channel Server.

The Microsoft Active Channel Server is a fully customizable and extensible system for automatically managing and updating the content of channels. Web content developers using the server can concentrate on creating and organizing the new content itself, leaving the rest to the Active Channel Server.

What makes the Active Channel Server the best solution?

It is…

Easy to script

The Active Channel Server takes advantage of the power of the Microsoft Component Object Model (COM) and Automation to make its classes available to scripting languages such as VBScript and JScript. Developers can write generic Active Channel Server Agents in these languages to provide custom refreshing of channel content.

Delivery Independent

The Active Channel Server system does not rely on any particular delivery mechanism for the CDF data. It simply provides the automatic refreshing mechanism and CDF generation on demand, leaving the method of delivery up to the content developer.

Integrated fully with Site Server 3.0

The Active Channel Server feature integrates with the other features of Site Server 3.0 seamlessly. Used in conjunction with the Personalization and Membership feature, it can generate personalized channel content on demand for users. It can also take advantage of the Site Server Search feature, automatically performing searches of constructed catalogs for items to include in a channel.


System Overview

The Active Channel Server system can be broken down into the following basic parts:

The COM Objects

Active Channel Server provides an extremely flexible set of COM/Automation compliant objects for creation and storage of channel information. Since they are COM compliant, any programming language that supports the COM can access them. These objects form the core of the system, and it is through these objects that the core functionality of the system is expressed.

The Refresh Cycle and the Channel Agent

The Channel Agents are scripts that programmatically update the data stored using the COM objects during a refresh cycle. They can be written in any scripting language that supports the COM and has an Active Scripting Engine available on the system. By default, this includes VBScript and JScript. The scripts are run via an Active Scripting Host built by the Active Channel Server Channel COM object.

GUI/Web Configuration Tools

Active Channel Server provides front-end tools that users and administrators can use to configure the various aspects of the system. These include a snap-in for the Microsoft Management Console (MMC), a set of command-line utilities that run using the Windows Scripting Host (WSH), and ASP pages that can be accessed through the Web Administration tool. The MMC and Web Admin tools are designed to be fully extensible, allowing developers and users to easily make custom channel agents available for configuration through these tools.


The Active Channel Server COM Objects

The COM objects implemented for the Active Channel Server closely follow the hierarchy defined by the Channel Definition Format (CDF) and the Open Software Description (OSD) specifications. Each section below groups the objects according to their functionality.


The Core Container Classes

The Active Channel Server COM objects all use two non-COM classes as collection objects. Access to these non-COM class objects is provided through a standard dispinterface. Successful use of the other COM classes requires a good understanding of these classes

List Class

stores information in a list using an integer index. This class is much like an array. The values can be any valid variant data type.

Dictionary Class

stores information in key/value pairs. The keys can be strings. The values can be any valid variant data type.

It is important to realize that these classes are not bona fide COM classes. They exist only within other Active Channel Server COM classes. The dispinterfaces are exposed through the associated property or collection name.


CDF Related COM Classes

The objects defined by these classes can be used to store content to be presented as CDF data to subscribers. The classes are listed below, along with a brief description of each.

Project Class

This class defines an object that can be used to organize a complete set of content. It contains the top level Channel object and all the Logo objects for child objects. It is roughly equivalent to a CDF file.

Channel Class

This object is at the heart of the system. It is the primary container object in the CDF hierarchy. It also runs Channel agents to update its content during the refresh cycle. It also manages the data presentable using the CHANNEL CDF XML element.

Item Class

This object is the primary "leaf" object in the content hierarchy. It manages the data presentable using the ITEM CDF XML element.

Schedule Class

This object can be used to manage the data presentable using the SCHEDULE CDF XML element.

LogTarget Class

This object can be used to manage the data presentable using the LOGTARGET CDF XML element.

Logo Class

This object can be used to manage the data presentable using the LOGO CDF XML element. These objects are always stored in a Project object.

Usage Class

This object can be used to manage the data presentable using the USAGE CDF XML element.

HTTPEquiv Class

This class of object can be used to associate generic HTTP-EQUIV XML elements with the various objects.


OSD Related COM Classes

The objects defined by these classes can be used to store content to be presented as OSD data to subscribers. The classes are listed below, along with a brief description of each. The OSD specification itself can be found at http://www.microsoft.com/standards.

SoftwarePackage Class

This class of object is the primary container in the OSD content hierarchy. It can be used to manage data presentable using the SOFTPKG OSD XML element.

Implementation Class

This class of object can be used to manage data presentable using the IMPLEMENTATION OSD XML element.

Codebase Class

This class of object can be used to manage data presentable using the CODEBASE OSD XML element.


System Management COM Classes

The classes listed below are used by the Active Channel Server system for management purposes.

Manager Class

This class can fetch admin information about the system, including the various projects, installed agents, and associated task information. The task information refers to scheduled refresh cycles.

Task Class

This class can be used to manage the refresh cycle information for a project.


ASP Related COM Classes

The following classes define objects that are useful in constructing personalized channel subscriptions in an ASP environment.

CDFGenerator Class

This class of object can be used to build a user's custom subscription CDF stream in an ASP environment. It integrates with the Personalization & Membership Active User Object system to retrieve the users selected channels.

CDFGenHelper Class

This class of object can be used in an ASP environment to aid other objects retrieve information about a project. The object is intended to act as a mini-server, being persisted as an ASP application-scope object. Objects of class CDFGenerator require instances of this class to b available when requesting a user's personalized channel subscriptions.


The Refresh Cycle and the Channel Agent

The refresh cycle is a generic phrase used to describe what happens when the Refresh method is invoked on an IChannel or IProject dispinterface. When this occurs, it is said that the refresh cycle for the channel or project has begun.

During this cycle, a Channel object runs a script called a Channel Agent. It does this using an Active Scripting Host. This process is similar to the one used with the Windows Scripting Host (WSH) and the Active Server Pages (ASP) system of Internet Information Server 3.0 and above. In the case of the channel scripting host, four dispinterfaces are passed to the namespace for the executing script (agent). They are listed below along with a brief description.

Intrinsic Namespace Interfaces

channel

this name specifies an IChannel dispinterface on the Channel object running the refresh cycle.

project

this name specifies an IProject dispinterface. This interface is passed to the Refresh method directly or indirectly. See the Project Class.

options

this name specifies a dispinterface to the class Dictionary object referred to by the name RefreshOptions on the Channel object. This collection is used to pass refresh option information to the agent for the refresh cycle.

util

this name specifies a dispinterface to methods that perform routine tasks useful within an agent.

Any agent script can access these interfaces by name as if they were intrinsic, just as an ASP page script can access the Request interface within an ASP page.

Scheduling Refresh Cycles for Automatic Execution

An instance of the Task class can be used to schedule a routine refresh cycle on a given project using the Microsoft Scheduled Tasks Administrative tool that comes with Site Server 3.0 and later versions of Microsoft Windows NT.

Project Vs Channel Refresh

Each Channel object can have its own agent and refresh options configured. Normally, one would configure the main channels of a project with various refresh channel agents and then schedule a task with the Scheduled Tasks Administrative tool. This would call Refresh on the Project object's IProject dispinterface. When this occurs, the RefreshAll method is invoked on the top-level channel's IChannel dispinterface. This recursively invokes the RefreshAll method on all Channel object in the content hierarchy for the project. Hence, the entire project and all of its subordinate Channel objects have the refresh cycle run.


Examples

The following examples demonstrate using the COM objects provided by Active Channel Server. The examples include:

Using the Objects to Store Content Data

This example provides a basic demonstration of how to use the objects to store information about content. The examples contained here could be used in a Channel Agent to programmatically update the channel information during a refresh cycle.

Creating Personalized Channel Subscriptions

This example demonstrates how to use the COM objects to present a personalized subscription CDF stream. That is, sending CDF data tailored to suite the choices made by a channel subscriber.

Creating a Custom Channel Agent

This example demonstrates how to go about building your own Channel Agent.

Full Sample: File Selection Installable Channel Agent

This is a tour of the sample agent. It includes a description of the agent, as well as the supporting GUI/Web Tools.


Using the Objects to Store Content Data

The following example shows how to construct the CDF string listed below:

<?XML version="1.0"?>

<CHANNEL HREF="http://www.mysite.com/Channel/homepage.htm"
    BASE="http://www.mysite.com/Channel/">
   <TITLE>Sample "Color" Channel</TITLE>
   <ABSTRACT>The sample color channel contains a red, green, and blue page for viewing.</ABSTRACT>
   <LOGO HREF="logo_big.gif" STYLE="IMAGE-WIDE"/>
   <LOGO HREF="logo_med.gif" STYLE="IMAGE"/>
   <SCHEDULE STARTDATE="1997-09-23">
      <INTERVALTIME DAY="1" />
      <EARLIESTTIME HOUR="2" />
      <LATESTTIME HOUR="6" />
   </SCHEDULE>
      <ITEM HREF="page1.htm">
      <LOGO HREF="red.gif" STYLE="ICON"/>
      <TITLE>The Red Page</TITLE>
      <ABSTRACT>This is the abstract description for the red page.</ABSTRACT>
   </ITEM>
   <ITEM HREF="page2.htm">
      <LOGO HREF="green.gif" STYLE="ICON"/>
       <TITLE>The Green Page</TITLE>
      <ABSTRACT>This is the abstract description for the green page.</ABSTRACT>
      </ITEM>
   <ITEM HREF="page3.htm">
      <LOGO HREF="blue.gif" STYLE="ICON"/>
      <TITLE>The Blue Page</TITLE>
      <ABSTRACT>This is the abstract description for the blue page.</ABSTRACT>
   </ITEM>
   <ITEM HREF="scrnsave.htm">
      <USAGE VALUE="ScreenSaver"></USAGE>
   </ITEM>

</CHANNEL>

The example below builds a Project object defining the content.

' Using VBScript and Windows Scripting Host Runtime Env
Dim Project

Set Project = CreateObject("Push.Project")
Project.Name="ColorChannel"

' Add the logos to the project

call Project.AddLogo("Top-Big","logo_big.gif", "IMAGE-WIDE")
call Project.AddLogo( "Top-Med","logo_med.gif", "IAMGE")
call Project.AddLogo( "Red"    , "red.gif",     "ICON")
call Project.AddLogo( "Green"  , "green.gif",   "ICON")
call Project.AddLogo( "Blue"   , "blue.gif",    "ICON")

' set up the channel

Project.Channel.HREF="http://www.mysite.com/Channel/homepage.htm"
Project.Channel.BASE="http://www.mysite.com/Channel/"
Project.Channel.Title="Sample "Color" Channel"
Project.Channel.Abstract="The sample color channel contains a red, green, and blue page for viewing."

' attach the logos to the channel itself
Project.Channel.LogoRefs.Add "Top-Big"
Project.Channel.LogoRefs.Add "Top-Med"

' set up the schedule element
Project.Channel.Schedule.Startdate=#1997-09-23#
Project.Channel.Schedule.Intervaltime=1
Project.Channel.Schedule.Earliesttime=2
Project.Channel.Schedule.Latesttime=6

' now add the items
Dim Item

' Red item
Set Item = Project.Channel.AddItem
Item.HREF="page1.htm"
Item.Title="The Red Page"
Item.Abstract="This is the abstract description for the red page."
Item.LogoRefs.Add "Red"

' Green item
Set Item = Project.Channel.AddItem()
Item.HREF="page2.htm"
Item.Title="The Green Page"
Item.Abstract="This is the abstract description for the green page."
Item.LogoRefs.Add "Green"

' Blue item
Set Item = Project.Channel.AddItem()
Item.HREF="page3.htm"
Item.Title="The Blue Page"
Item.Abstract="This is the abstract description for the blue page."
Item.LogoRefs.Add "Blue"

' Screensaver item

Set Item = Project.Channel.AddItem()
Item.HREF="scrnsave.htm"
Item.AddUsage "ScreenSaver"

' Save the project  (very important!)
Call Project.Save "ColorChannels"

' write the CDF file to disk
Call Project.WriteCDFFile("c:\channels\color\color.cdf")

This example, although not very interesting, does illustrate the core features of the primary Active Channel Objects. A more interesting use of these objects is in an Active Channel Agent that searches the system for content that meets certain conditions to be included in the Channel object during the refresh cycle.


Creating Personalized Channel Subscriptions

The following extended example demonstrates the power available using the Active Channel Server objects in an ASP environment to allow users to select personalized channel subscriptions.

Assume we have a page here that presents a simple form the user can use to select channels from a project. It would be nice to have the GUID values and channel Titles put in the Application collection for reference by the selector page. Here's how we could do this in the Global.Asa file. Assume a simple set of channels: one top-level, and a few in the subchannels collection.

Global.Asa

<SCRIPT LANGUAGE="VBScript" RUNAT=SERVER>
Sub Application_OnStart
 Set IDispHelper = CreateObject("Push.CDFGenHelper")
 IDispHelper.Load("Project1")
 Set Application("Project1") = IDispHelper

 ' get the project out to get guids and titles
 Set IDispProject = IDispHelper.Project

 ' add guid=title key/value pairs to a dictionary
 Set ChannelTitles = CreateObject("Scripting.Dictionary")
 ChannelTitles(IDispProject.Channel.GUID) = IDispProject.Channel.Title
 For each channel in IDispProject.Channel.subchannels
  ChannelTitles(channel.GUID) = channel.Title
 Next
 Set IDispProject = nothing  'remove this reference
 Set Application("Channel Titles") = ChannelTitles
 …
End Sub
</SCRIPT>

Now we can display the Titles and use the GUID values for an HTML form via an ASP page:

Selection.asp

<HTML>
<HEAD>
<TITLE>Select Only the Channels You Want</TITLE>
</HEAD>
<BODY>
Select The Channels You'd Like to Subscribe to:<br>
<FORM METHOD="POST" ACTION="addthem.asp">
<% For Each Key in Application("Channel Titles")
Response.write("<INPUT TYPE=\"CheckBox\" Name=\"ChanSelection\" VALUE=\""
& Key & "\">" & Application("Channel Titles")(key) & "<br>")
%>
<INPUT TYPE=SUBMIT>
</FORM>
</HTML>

Now we can use the "addthem.asp" file to add the channels to the users directory data. We then can redirect them to a CDF generating ASP page

addthem.asp

<%
   ' Get the directory property name used to hold the channel selections
   ' and style from the CDFGenHelper.  Its in the Application collection

   Application("Helper").GetSelectionListPropName( ListProp, StyleProp)

   '  Create the user's AUO
   const AUOClass = "membership.userobjects"
   Set IDispUserObjects=Server.CreateObject(AUOClass)
   ' add the guid list to the user's data
   '  The Form collection should have a nice array of values
   '  from the checkbox.

   IDispUserObjects.PutEx 2, ListProp,(Request.Form("ChanSelection"))
   IDispUserObjects.Put StyleProp, 0  ' inclusive list
   IDispUserObjects.SetInfo

   Set IDispUserObjects = nothing

   Response.Clear
   Response.Redirect = "generateCDF.asp"
   Response.end
%>

The contents of the "generateCDF.asp" are then listed below. This script actually generates the custom CDF string for the user using their selections stored in the directory database. Way back in the first code example, the dispinterface on an instance of the CDFGenHelper class was added to the Application collection under the name "Project1". This interface is referred to when the Run method is invoked below.

generateCDF.asp

<% Set ICDFGenerator = Server.CreateObject("Push.CDFGenerator")
     ICDFGenerator.Run "Project1"
%>


Creating a Custom Channel Agent

The example below demonstrates building and using a custom Channel Agent. For the purposes of this SDK, a custom channel agent is any agent other than the agents that come installed with Site Server 3.0.

This example agent will scan a specified folder for all Microsoft Word files and include them as content in a channel during a refresh cycle. In this case, the project is set up using a Windows Scripting Host Script (WSH). The top-level Channel object is configured to run the agent as a "customagent" meaning that the RefreshScript property will point to the script's location on the file system.

  • In the first code segment, a Windows Scripting Host (WSH) script is shown that creates an instance of the Project class. It then sets the top-level Channel object's RefreshType property to "userscript." (i.e. custom agent that the programmer specifies) It sets a few hypothetical options for the custom agent, and then executes the refresh cycle on the project.

  • In the second code sample, the hypothetical custom agent is listed. In this example, the agent will scan the directory specified in the RefreshOptions collection under the key "DocsDir." In that directory, it will add all word documents it encounters into the Channel object as Item objects. This example could be used to keep subscribers abreast of say the latest specifications or memos present in the directory specified.

It should be stressed that this example is for illustration purposes only. Usually, it would be easier to build the Project object and Channel using one of the administrative tools such as MMC or WebAdmin. However, for testing purposes, the procedure listed below is quite useful.

Building the Channel and Running the Refresh Cycle

(VBScript and Windows Scripting Host)

' File: sample.vbs
' This WSH script builds a Project object, sets up the
'  top level channel object's refresh information,
'  and runs the refresh cycle on the project
'
'   It will scan the specified directory for all
'    word documents (.doc) and automatically incorporate
'    them into the channel

Option Explicit
Dim Project
Dim Channel
Dim Options

' Set up the Project with useful info
Set Project = CreateObject("Push.Project")
Project.Name="Test Project"
Project.CDFFile="c:\channels\LatestSpecs.cdf"
Project.Schedule.Startdate=#1/1/1998 19:00:00#
Project.Schedule.IntervalTime = 360
' suggest to subscribers that they 'check in'
' every 6 hours for new content

Set Channel = Project.Channel
Set Options = Channel.RefreshOptions

' Some useful (and hypothetical) Bibliographic info
Channel.Base = "file://\\somemachine\TechSpecs\"
Channel.Title="The Latest Specs on Widgets"
Channel.Abstract="This channel contains all the latest specification documents for the Widget research"
Channel.Authors.Add "Dr. John Doe"
Channel.Authors.Add "Dr. Jane Doe"

' Set up the refresh information

Channel.RefreshType="USERSCRIPT"

'  here we will specify a custom script
'   that is listed below.  The path to the
'    agent script is "c:\agentscripts\CustomTechRefresh"

Channel.RefreshScript="c:\scripts\CustomTechRefresh"

Options("DocsDir") = "c:\TechSpecs"
' this option specifies where to find the .doc files

'  Now we run the refresh explicitly
Project.Refresh

' finished adding the items.  Let's Schedule the refresh
'  on the server for every 6 hours
call Project.SetTask("SomeUser",720,0)
Project.Task.Update "password"
'  task should now be scheduled.  The refresh cycle
'  will occur every 6 hours starting a 12 am midnight
'  every day

Project.Save "TestProject"
' save the project

The Custom Agent

The code listed below is the custom agent. Notice the use of the built-in objects.

' File: c:\scripts\CustomTechRefresh
'
'  This script is an agent called by a Push.Channel object
'   to refresh its content.  It checks first to make sure
'   a valid "DocDir" option is passed, and if so, does the
'   following:
'    deletes all items marked with "DeleteonFresh" set to TRUE
'    Scans the directory for .doc files
'    Adds any it finds as items to the Channel object on whose
'    behalf the agent is being run.

If not util.IsValidData(Options("DocDir"), vbString ) Then
  RaiseError("A valid string was not passed to the agent")
End If

Set fs = createobject("Scripting.FileSystemObject")
set folder = fs.GetFolder(Options("DocDir"))
For each File in folder.files
  NameExt = split(File.Name,".")
  If UBound(NameExt) > 0 Then
    If NameExt(UBound(NameExt)) = "doc" Then
      Set Item = Channel.AddItem
      Item.HREF=File.Name
      Item.Title=File.Name
    End If
   End If
Next


Sample: An Installable Channel Agent

A complete sample consisting of a Channel Agent and all supporting options collection tools comes with this release of the Site Server 3.0 SDK. The sample can be found in the "Samples\Microsoft Site Server\Push\Sample Channel Agent\Agent" directory from the location of the SDK install. The sections below outline the key points found in the sample.

Other examples of Channel Agents can be found in the "C:\microsoft site server\bin" directory. This is where the pre-installed agents and admin scripts are located. One can study these to get a picture of how the various agents are implemented.

Development Environment Prerequisites

Most of the sample can be viewed with the beloved NotePad text editor. A C/C++ compiler is required to compile the COM Property Page implementation. Make sure you have the Unicode libraries installed before you attempt to compile it. A Microsoft Developer Studio project is included with the sample should that format be desired.


Sample Files

The sample is composed of the following files/parts: (Note the extra path info in the file names)

The Sample Agent: Redist\SampleAgent.vbs

this is a VBScript script that performs the channel refresh when this agent is selected.

The ASP Property Page: Redist\AgSampleAgent.asp

this ASP page plugs into the WebAdmin tool to facilitate collection of the refresh options for the agent.

The ASP Wizard Page: Redist\WizSampleAgent.asp

this ASP page plugs into the WebAdmin tool to facilitate a wizard approach to collecting options for the agent.

The ASP Wizard Finish Page: Redist\WizPushChn0.asp

this ASP page is targeted when the user has finished selecting the options for the agent.

A Sample INF file: Redist\SampleAgent.inf

this file contains example install information for the agent.

The COM IPropertyPage Implementation. (all other files)

The rest of the files compose the COM IPropertyPage implementation that appears in the MMC snapin PropertySheet for the Agent. This page facilitates the collection of refresh options for the agent through the MMC.


The Sample Agent Script

This script acts as the agent during the refresh cycle. The code in its entirety is listed below.

During the refresh cycle, this agent will gather the specified files in the specified directory for inclusion in the Channel object running the cycle. It additionally uses the WrapSSIFilter COM class to gather bibliographic information encountered in each file it adds.

The first section of the script checks that the RefreshOptions have been set in an acceptable way for the agent to use. In this case, it makes sure the keys "Files" and "Directory" are set and that the associated values are of the correct data type.

It then creates a Scripting.FileSystemObject class object to access the file system and the listed files. For each file passed in the RefreshOptions collection under the key "Files", it adds the file as an Item object to the Items collection for the Channel.

After setting some properties such as the HREF and Title, it then uses the WrapSSIFilter COM object to scan the file for bibliographic tags and information.

On Error Resume Next
Dim g_oPushFilter
Set g_oPushFilter = CreateObject("Push.WrapSSIFilter")
On Error Goto 0
Err.Clear

If Util.IsValidData(Options("Files"), vbArray + vbVariant) AND _
   Util.IsValidData(Options("Directory"), vbString) Then

    Dim strFile, oFileSystem
    Set oFileSystem = CreateObject("Scripting.FileSystemObject")

    For Each strFile in Options("Files")
        Dim oItem
        Set oItem = Channel.AddItem()

        REM Set Item properties
        oItem.DeleteOnRefresh = TRUE
        oItem.HREF            = strFile
        oItem.Title           = strFile
        SetIFilterProperties g_oPushFilter, oItem, oFileSystem.GetFile(Options("Directory") & strFile)

        ' Please refer to the SDK for properties that can be set on Item.
    Next

End If

REM
REM This procedure sets additional Item properties found by the IFilter object
REM
Sub SetIFilterProperties(ByVal oPushFilter, ByVal oItem, ByVal oFile)

    Dim fFilterLoaded, vtData, strAuth, strKwdit

    If VarType(oPushFilter) <> vbObject Then
        oItem.Title = oFile.Name
    Else
        fFilterLoaded = TRUE

        REM
        REM Load the filename into the filter and extract HTM tag properties
        REM
        On Error Resume Next
        oPushFilter.load oFile.Path, 0
        If Err.Number <> 0 Then
            fFilterLoaded = FALSE
            Err.Clear
        End If
        On Error Goto 0

        If fFilterLoaded = FALSE Then
            oItem.Title = oFile.Name
        Else
            REM
            REM Filter is loaded, set the properties retrieved from the file Filter
            REM

            REM set the Title
            vtData = oPushFilter.GetProperty("title")
            If util.IsValidData(vtData, vbString) Then
                oItem.Title = vtData
            Else
                oItem.Title = oFile.Name
            End If

            REM set the authors
            vtData = oPushFilter.GetProperty("authors")
            If util.IsValidData(vtData, (vbArray+vbVariant)) Then
                For each strAuth in vtData
                    oItem.Authors.Add strAuth
                Next
            End If

            REM set the abstract
            vtData = oPushFilter.GetProperty("abstract")
            If util.IsValidData(vtData, vbString) Then
                oItem.Abstract = vtData
            End If

            REM set the Keywords
            vtData = oPushFilter.GetProperty("Keywords")
            If util.IsValidData(vtData, (vbArray+vbVariant)) Then
                For each strKwdit in vtData
                    oItem.Keywords.Add strKwdit
                Next
            End If
        End If 'fFilterLoaded
    End If 'g_bUseFilter
End Sub


The Sample ASP Property Page

This ASP page can be used from the WebAdmin tool to set the refresh options for the agent. The possible refresh options are:

the files to include

the directory containing the files.

The functional highlights from this page are listed below.

Dim m_strProjectName ' the Project Name
  Dim m_prj            ' the Project Object
  Dim m_strChnItmPath  ' the Channel/Item Name
  Dim m_chn            ' the Channel Object
  Dim m_options        ' the refresh options dictionary

  m_strProjectName = Request.QueryString(g_strKeyProjectName)
  m_strChnItmPath = Request.QueryString(g_strKeyChnItmPath)

  Set m_prj = PrjLoadFromName(m_strProjectName)
  Set m_chn = ChnItmFromPrj(m_prj,m_strChnItmPath)

  Set m_options = m_chn.RefreshOptions

In this case, we see that the Project object is loaded from the name sent in the query string of the request. The Project then loads this project, and fetches the appropriate IChannel dispinterface. Through this dispinterface is fetches the dispinterface on the RefreshOptions collection in the Channel object.

The following subroutine is invoked if the form submission has occurred with the options set in the form elements. In this case, the hidden form variable "Action" is set to some value, and the appropriate action is taken with the RefreshOptions collection. In the script below, the RefreshOptions collection (Dictionary Class) dispinterface is stored in the variable m_Options. The sections with comments added are listed in bold.

Sub SavePage(prj)
    Dim strFileName
    Dim rgFileName, I

    strFileName = Request.Form("FileName")
      ' This is the name of the new file to add
    rgFileName = m_options.Item("Files")
      '  This is an array of values indexed under the
      ' agent option "Files" here

    If Request.Form("Action") = "Add" Then

        DebugWriteNameValue "vartype", vartype(rgFileName)

        If IsArray(rgFileName) Then

            For I = 0 To UBound(rgFileName)
                DebugWriteNameValue "rgFileName(I): ", rgFileName(I)
                If strFileName = rgFileName(I) Then
                    WriteClientAlert "You already added this one."
                    Exit Sub
                End If
            Next

            AddArrayElement rgFileName, strFileName
               ' If the file has not already been added, it
               ' is added here

        Else
            ReDim rgFileName(0)
            rgFileName(0) = strFileName
               ' in this case, the array was empty.  So assign
               ' the first element to be the name of the file
               ' to add

            DebugWriteNameValue "vartype(rgFileName)", vartype(rgFileName)
            DebugWriteNameValue "strFileName", strFileName
        End If

        m_options.Item("Files") = rgFileName
         ' here we now set the RefreshOptions key "Files" to
         '  the array of file names.  This is done each
         ' time a file is added

    Elseif Request.Form("Action") = "Remove" Then

        RemoveArrayElement rgFileName, CInt(Request.Form("idx"))

        m_options.Item("Files") = rgFileName
          ' for the "Remove" action, the array element
          ' holding that file name is removed and the shortened
          ' array is set to the RefreshOptions collection under the
          ' key "Files"

    Elseif Request.Form("Action") = "Edit" Then
        rgFileName(CInt(Request.Form("idx"))) = strFileName
        m_options.Item("Files") = rgFileName
          Here we update the "Files" option again

    Elseif Request.Form("Action") = "DirChange" Then
        m_options.Item("Directory") = CStr(Request.Form("Directory"))
          ' The User clicked the "ChangeDir" button on the form.
           '  Here we change the directory string pointed to by the
           ' RefreshOption key "Directory"

        m_options.Item("Files") = rgFileName

    End If
    SaveProject prj
       ' This calls the method Project.Save for the project

  End Sub


The Sample ASP Wizard Page

The Sample ASP Wizard Pages

The ASP pages that contain the "wizard" code are discussed below. The "wizard" is supposed to provide the end user with a "step-by-step" process for setting the options for the agent.

WizSampleAgent.asp

The sample uses many "Lib" files used by the Push feature. They are listed below:

<!--#Include File="LibGlobals.asp"-->
<!--#Include File="LibUtil.asp"-->
<!--#Include File="LibRes.asp"-->
<!--#Include File="LibWizard.asp"-->

One should become familiar with what is contained in them to take advantage of previously defined and useful functionality.

In this case, the user's selections are temporarily stored in the current ASP Session collection under the names "Dict_Directory" and "Dict_Files."

The user can go about changing the Directory that contains the files, and can then select files. Once they hit the "Finish" button, that targets the next file in the sample, the WizPushChn0.asp file.

WizPushChn0.asp


Active Channel Server Object Model

Object Model

The primary hierarchy of objects implemented by the Active Channel Server COM classes is listed below. The structure closely follows the Channel Definition (CDF) and Open Software Description (OSD) specifications on content relationships. In each case, the parent object contains information only about its direct descendents. A complete description of each object can be found by following the associated hyperlinks.

CDF Related Objects

Project

  • Channel

  • LogTarget

  • Logos

  • Schedule

  • Task

  • Elements

  • HTTPEquivs

Channel

  • Subchannels

  • Items

  • SoftwarePackages

  • Elements

  • HTTPEquivs

  • Usages

Item

  • Elements

  • HTTPEquivs

  • Usages

LogTarget

  • Elements

  • HTTPEquivs

Schedule

  • Elements

OSD Related Objects

SoftwarePackages

  • Implementations

  • Elements

  • Usages

Implementation

  • Elements

Codebase

  • Elements


Channel Agent System Overview

Each Channel object can run an agent to update its content during a refresh cycle. The programmer can specify the agent to use with the Channel object RefreshType property. To facilitate the passing of options to the agent at refresh runtime, the Channel object also has the RefreshOptions collection, which is a class Dictionary object. Each key in the Dictionary contains the name of an option, and the associated value contains the option value or values.

When the refresh cycle is run on a Channel object, it creates an ActiveX Scripting Host to execute the agent. For the purposes of this reference, this host will be referred to as the Active Channel Server Agent Host, or just Channel Agent Host. The script used to add the new content will be referred to as the Channel Agent.


The Channel Agent

The Active Channel Server agent is simply a script written in a language such as VBScript or JScript. The only requirement made about a given language is that it must have an installed ActiveX Scripting engine. By default, all machines with the Active Server Pages environment installed have scripting engines for VBScript and JScript.

The Active Channel Server comes with 6 pre-installed agents. The files for these agents can be found in the directory "c:\microsoft site server\bin".

The agents are implemented in the following files:

FileSystemAgent.vbs
DatabaseAgent.vbs
BriefingAgent.vbs
PromotionsAgent.vbs
SearchAgent.vbs

These agents can be used as starting points for the construction of new agents.


The Channel Agent Scripting Host

Each Channel object will create an Active Scripting Host to run a specified agent. When doing so, it passes dispinterfaces to the host that the agent script can then access and modify in its own namespace. Thus, these interfaces appear as "built-in" interfaces to the agent.

Digression: Other Examples of Active Scripting Hosts

The ActiveX Scripting Host technology is perhaps unfamiliar, at least in name, to many developers. To get a more concrete idea of exactly how this system works, a few common examples of ActiveX Scripting Hosts are listed below.

ASP

A well known Active Scripting Host is the Active Server Pages (ASP) system that Internet Information Server (IIS) 3.0 and 4.0 support. In this case, the IIS server instance creates an Active Scripting Host and passes the Request, Response, Server, Session, and Application dispinterfaces to the host. The ASP script can then access these objects via these interfaces in the script without having to explicitly create them. The script to parse is the one identified by the client request usually with the extension ".asp"

Windows Scripting Host

This host is a newcomer, but the principle is the same. When a user types cscript.exe <filename>.<ext> the executable generates an Active Scripting Host and passes the host the WScript dispinterface. Thus WSH scripts can use the built-in WScript object directly.

For more information on the Active Scripting Host system, visit the Microsoft Developer's Network at http://www.microsoft.com/msdn.


Agent Built-In Interfaces

The following dispinterfaces are always available to an agent script within its namespace when executing.

channel

This is the IChannel dispinterface through which the Refresh method was invoked.

options

This is the dispinterface on a class Dictionary object contained in the Channel object's RefreshOptions collection.

project

the IProject dispinterface passed to Refresh as an argument. If Refresh is invoked on an IProject dispinterface, that interface is passed to subsequent calls to IChannel Refresh method invocations.

util

this interface is included automatically in every scripting host. It contains a set of utility methods that perform routine tasks useful to agent programmers.


The Channel Refresh Cycle

To begin the refresh cycle, a programmer invokes the Refresh method on a class IChannel dispinterface. When this occurs, the object first checks its RefreshType property for the name of the agent to run. One of the following occurs in each case:

  1. If the RefreshType property is set to "manual" or "none", no agent is defined, so the cycle ends. This is the default for newly created Channel objects

  2. If the RefreshType property is set to "userscript" or "custom", the object attempts to run the agent defined in the RefreshScript property.

  3. For any other value, the object checks in the registry for a key that matches the name of the agent. From there it can determine the agent to run.

If the object determines that it has an agent specified, it begins the refresh cycle. The process is outlined as follows.

  1. The Channel object creates an Active Scripting Host.

  2. The object loads the appropriate agent script.

  3. For a script specified as "userscript", it loads the VBScript Active Scripting engine, For others, it checks the registry under the name of the agent for a value listed under the named value "Script Language". This determines the scripting language and thus the engine to load.

  4. The object passes its own IChannel dispinterface, the dispinterface contained by the RefreshOptions collection, the associated IProject dispinterface, and the util dispinterface to the scripting host. These become built-in interfaces (or objects) in the agent's namespace. They can be referred to by the names "channel","options","project", and "util" respectively.

  5. The engine is sent the agent script for parsing and execution.


Registry Keys Used By the Channel Agent Refresh System

The Active Channel Server system uses a registry key to define a Channel Agent. Each key can be found under the registry path
HKLM\Software\Microsoft\Site Server\3.0\Active Channel Agents\

The key itself is usually a simple name used to identify the particular agent. For example, the pre-installed agents that come with Active Channel Server have names like "File System" and "Database." The "names" and "data" listed under each of these keys identify configuration information about the respective agent. These names, along with a brief description of their purpose, are listed below.

ASP Property Page

the data under this name refers to the name of an ASP file that can be used by the WebAdmin tool to configure the various options for the agent. The value of the data can be a full or relative path to the ASP page. If the path is relative, the prefix "c:\microsoft site server\bin" is assumed.

ASP Wizard Page

the data under this name refers to the name of an ASP file that can be used by the WebAdmin tool when the user requests to use the "wizard" to help set options for the agent. The value of the data can be a full or relative path to the ASP page. If the path is relative, the prefix "c:\microsoft site server\bin" is assumed.

COM Property Sheet

the data under this name is a GUID identifying the CLSID of a COM class that implements the IPropertyPage interface. An instance of this class is created when a user selects the agent for use by a Channel object in the Microsoft Management Console.

Display Name

the data under this name specifies a display name used by the various admin tools such as the Microsoft Management Console tool and the WebAdmin tool.

Script Language

the data under this name specifies the Active Scripting Engine to use when running the agent script. The hosting Channel object uses this data when the refresh cycle commences to load the appropriate engine for the script.

Script Pathname

the data under this name should define the path to the agent script. If the path is relative, the prefix "c:\microsoft site server\bin" is assumed. (e.g. Script Pathname = "somescript.vbs" implies that the script resides a c:\microsoft site server\bin\somescript.vbs)


Options for the Pre-Installed Channel Agents

The Active Channel Server comes with a set of pre-installed agents. The options listed below are the ones assumed for each. The name of the option would refer to a key in the RefreshOptions collection (Dictionary Object) passed to the agent during a refresh cycle. The value of the key is then used by the agent to specify its behavior. The agent options are listed in the table below.

Agent-> | File System | Database | Search | Briefing | Promotions
Options |  |  |  |  |
ChannelHREF | X |  |  |  |
ChannelLevel | X |  |  | X |
ChannelLogoRefs | X |  |  | X |
ChannelPrecache | X |  |  | X |
ItemLogoRefs | X | X | X | X | X
ItemLogs | X | X | X | X | X
ItemLevel | X | X | X | X | X
ItemPrecache | X | X | X | X | X
MatchCriteria | X |  |  |  |
Directory | X |  |  |  |
RecurseDirectories | X |  |  |  |
FileModifiedLastTime | X |  |  |  |
Catalog |  |  | X |  |
Query |  | X | X |  | X
DefinedColumns |  |  | X |  |
Connection |  | X |  |  | X
ParameterName |  | X |  |  | X
ItemHREF |  |  |  |  | X


ChannelLogoRefs Key

Associated Value Type

Array (VT_ARRAY)

Array Contains

String (VT_BSTR)

Description

An agent uses the strings passed via the ChannelLogoRefs option to populate the LogoRefs collection of each Channel object it creates during the refresh cycle.

Note Do not simply assign a previously defined LogoRefs collection to the RefreshOptions collection under the key "channellogorefs." The LogoRefs collection is a class List object, whereas the "channellogorefs" option is defined to contain an Array (SAFEARRAY). The assignment will succeed, however, the agent will fail to property populate any new Channel object's LogoRefs collection during the refresh cycle.

Example

' VBScript Project.AddLogo("channelbar","/images/bar.gif","IMAGE") Project.AddLogo("icon","/images/icon.gif","ICON") Project.AddLogo("wide","/images/wide.gif","IMAGE-WIDE")
ForAgentLogoNames = Array ("channelbar","icon","wide") Channel.RefreshOptions("channellogorefs") = ForAgentLogoNames Channel.Refresh(Project)

Applies to Agents

File System
Briefing


ChannelLevel Key

Associated Value Type

Integer (VT_I4)

Description

An Agent uses the integer value passed with this option to set the Level property for each Channel object that the agent creates during the refresh cycle.

Example

' VBScript
Channel.RefreshType="File System"
Channel.RefreshOptions("channellevel") = 2

Applies to Agents

File System
Briefing


ChannelPrecache Key

Associated Value Type

String (VT_BSTR)

Description

An Agent uses the string value passed with this option to set the Precache property for each Channel object that the agent creates during the refresh cycle.

Example

' VBScript
Channel.RefreshType = "File System"
Channel.RefreshOptions("channelprecache") = "YES"

Applies to Agents

File System
Briefing


ChannelHREF Key

Associated Value Type

String (VT_BSTR)

Description

An Agent uses the integer value passed with this option to set the HREF property for each Channel object that the agent creates during the refresh cycle.

Example

' VBScript
Channel.RefreshType="file system"
Channel.RefreshOptions("channelhref") = "/channel1/page.htm"

Applies to Agents

File System


ItemLogoRefs Key

Associated Value Type

Array (VT_ARRAY)

Contains

String (VT_BSTR)

Description

An agent uses the strings passed via the ItemLogoRefs option to populate the LogoRefs collection of each Item object it creates during the refresh cycle.

Note Do not simply assign a LogoRefs collection to the RefreshOptions collection under the key "itemlogorefs." The LogoRefs collection is a class List object, whereas the "itemlogorefs" option is defined to contain an Array (SAFEARRAY). The assignment will succeed, however, the agent will fail to property populate any new Item object's LogoRefs collection during the refresh cycle.

Example

' VBScript
Project.AddLogo("icon","/images/icon.gif","ICON")
ForAgentLogoNames = Array ("icon")
Channel.RefreshOptions("itemlogorefs") = ForAgentLogoNames
Channel.Refresh(Project)

Applies to Agents

File System
Search
Promotions
Briefing


ItemLogs Key

Associated Value Type

Array (VT_ARRAY)

Contains

String (VT_BSTR)

Description

An agent uses the strings passed via the ItemLogs option to populate the Logs collection of each Item object it creates during the refresh cycle.

Note Do not simply assign a Logs collection to the RefreshOptions collection under the key "itemlogs." The Logs collection is a class List object, whereas the "itemlogs" option is defined to contain an Array (SAFEARRAY). The assignment will succeed, however, the agent will fail to property populate any new Item object's Logs collection during the refresh cycle.

Example

Channel.RefreshOptions("itemlogs") = array ("log:default")

Applies to Agents

File System
Search
Promotions
Briefing


ItemLevel Key

Associated Value Type

Integer (VT_I4)

Description

An Agent uses the integer value passed with this option to set the Level property for each Item object that the agent creates during the refresh cycle.

Example

' VBScript
Channel.RefreshType="File System"
Channel.RefreshOptions("channellevel") = 2

Applies to Agents

File System
Search
Promotions
Briefing


ItemPrecache Key

Associated Value Type

String (VT_BSTR)

Values

"YES" or "NO"

Description

An Agent uses the string value passed with this option to set the Precache property for each Item object that the agent creates during the refresh cycle.

Example

' VBScript
Channel.RefreshType = "File System"
Channel.RefreshOptions("itemprecache") = "YES"

Applies to Agents

File System
Search
Promotions
Briefing


Directory Key

Associated Value Type

String (VT_BSTR)

Values

filesystem path

Description

This option passes the filesystem path to the directory in which to search for new items and possibly channels, and if found, to incorporate in the class Channel object's collections. The string is passed to the Scripting.FileSystemObject for enumeration (and possibly recursive enumeration) of the files contained within.

Example

Channel.RefreshOptions("Directory") = "c:\channels\channel1"

Applies to Agents

File System


MatchCriteria Key

Associated Value Type

Array (VT_ARRAY)

Contains

String (VT_BSTR)

Description

Each item in the array should be a string "glob" specifying a wild card used to match files. The files in the directory pointed to by the Directory key will first be filtered using the wildcard expression, then checked and possibly incorporated into the Channel object's Items collection. This is essentially a "globbing" mechinism used commonly, such as "DIR *.htm" to list all .htm files in the current directory.

Example

Channel.RefreshOptions("MatchCriteria") = Array("*.htm","*.asp","*.cdf")

Applies to Agents

File System


RecurseDirectories Key

Associated Value Type

String (VT_BSTR)

Values

"YES" or "NO"

Description

This option can be used to have the agent recursively descend subdirectories starting with the directory pointed to by the Directory option. If set to "YES", each directory under the directory specified by the Directory option will become a class Channel object. The hierarchy of the directories will be preserved in the Channel object hierarchy.

Example

Channel.RefreshOptions("recursedirectories")="YES"

Applies to Agents

File System


FileModifiedLastTime Key

Associated Value Type

Date (VT_DATE)

Description

The File System agent will use this option to compare modification times for files found during the refresh cycle. If the file has been modified since the date specified by the option, it will be included as a new item in the Channel object.

Example

Channel.RefreshOptions("filemodifiedlasttime") = #6/30/2001 23:00:00#

Applies to Agents

File System


Catalog Key

Associated Value Type

String (VT_BSTR)

Description

This option specifies the Search catalog to use when performing the search for items. The Search agent script sets the MSSearch.Query object's Catalog property to this value.

Example

Channel.RefreshOptions("Catalog") = "catalogname"

Applies to Agents

Search


Query Key

Associated Value Type

String (VT_BSTR)

Description

Different agents use this key/value pair differently. The uses are listed below for each applicable agent.

Database Agent

The Database agent (databaseagent.vbs) uses the value associated with the "query" key to set the CommandText property of the class ADODB.Command object used to query the database.

Search Agent

The Search agent (searchagent.vbs) uses the string value associated with the "query" key to set the class MSSearch.Query object's Query property.

Promotions Agent

The Promotions agent (promotionsagent.vbs) uses the string value associated with the "query" key to set the CommandText property of the class ADODB.Command object.

Example

Channel.RefreshOptions("query")="Select * from ChannelItems"

Applies to Agents

Database
Search
Promotions


DefinedColumns Key

Associated Value Type

Array (VT_ARRAY)

Contains

String (VT_BSTR)

Description

The Search agent (searchagent.vbs) uses the value of this key to set the DefinedColumns property of an instance of the MSSearch.Query object used to search a catalog.

Example

Channel.RefreshOptions("definedcolumns") = Array("itemname", ... )

Applies to Agents

Search


Connection Key

Associated Value Type

String (BSTR)

Description

Applicable agents use this key to set the ODBC connection string for the pending database query.

Example

Channel.RefreshOptions("connection") = "DATABASE=somedatabase;UID=sa;PWD=;DSN=something"

Applies to Agents

Database
Promotions


ParameterName Key

Associated Value Type

String (VT_BSTR)

Description

This key specifies the name of a "parameter" to have an agent add to new class Item object's HREF property. The name becomes the "parameter" and an associated result row from the query becomes the value.

Example

Channel.RefreshOptions("parameter") = "name"

When the agent finds this key defined in the options class Dictionary object, it constructs the HREF property for the class Item object using the parameter as part of an HTTP GET method string.

For example: to build "/channels/item1.htm?name=Joe" as the HREF property of a new Item object created during the refresh cycle, the queried database table would have two columns defined, one named "HREF" and one named "name". One of the returned rows from the query would have the following return values:

HREF | name
"/channels/item1.htm" | "Joe"

These results are used by the Database agent to construct the HREF property as follows:

HREF = Results("HREF") & "?" & options("parametername") & "=" & Results("parametername")

(The Results collection is the one returned by the ADODB.Commmand.Execute method.)

This would set the new Item object's HREF property to "/channels/item1.htm?name=Joe"

Applies to Agents

Database
Promotions


ItemHREF Key

Associated Value Type

String (VT_BSTR)

Description

The Promotions agent uses the string value passed with this option to set the HREF property for each Item object that the agent creates during the refresh cycle.

Example

Channel.RefreshOptions("itemhref") = "/channels/storefrontpage.htm"

Applies to Agents

Promotions


CoClass CDFGenerator (Push.CDFGenerator.1)

Class CDFGenerator

Programmatic Identifier: Push.CDFGenerator.1

The CDFGenerator class defines an object developers can use in an Active Server Pages (ASP) environment to create personalized channel content for users.

  1. The user requesting the ASP page that will create an instance of the CDFGenerator class be properly registered with the P&M Membership Authentication Server. Specifically, this means that the built-in ASP Server object creating the instance of the Push.CDFGenerator class must be able to successfully create an instance of a fully initialized class Membership.UserObjects object (also known as the Active User object (AUO).

  2. A class Push.CDFGenHelper object within the ASP application scope must be available to service requests for a user's personalized CDF streams. This object must therefore be contained in the ASP Application collection.

The CDFGenerator class exposes a dual interface to methods and properties. They can be accessed via the IDispatch interface or the ICDFGenerator COM interface.

Interface ICDFGenerator

Methods

Name | Description
OnStartPage | Standard server-side ASP method
OnEndPage | Standard server-side ASP method
Run | Builds the user's personal subscription Channel Definition Format (CDF) string from the project.


ICDFGenerator OnEndPage Method

OnEndPage Method

After it finishes executing an ASP page, the built-in ASP Server object automatically invokes this method on all objects it created during the execution of ASP script. The method performs all necessary memory de-allocations and object releases.

This method is standard for all classes designed to take advantage of the ASP environment and is not intended to be invoked directly by script in an ASP page. It is listed here strictly for completeness.


ICDFGenerator OnStartPage Method

OnStartPage Method

The built-in Server object calls this method after it creates an instance of the CDFGenerator class in an ASP script. This method, in turn, invokes Server.CreateObject to create an instance of the Membership.UserObjects class, the primary COM object used by the Personalization and Membership Active User Object (AUO) feature. Once created, it is available for use in retrieving the current user's list of included or excluded channels from the Membership directory database.

This method is standard for all classes designed to take advantage of the ASP environment and is not intended to be invoked directly by script in an ASP page.


ICDFGenerator Run Method

Run Method

This method generates the CDF string representing the user's personal channel selections. It then directly sends the string to the client browser via the built-in ASP Response object with the MIME type set to "application/x-cdf." In essence, the ASP page becomes a dynamic CDF file containing the users personalized channel content.

VBScript Syntax

ICDFGenerator.Run CDFGenHelperName

Parameters

CDFGenHelperName

A string specifying the key indexing a class CDFGenHelper object in the ASP Application collection.

Return Value

None

Remarks

The CDFGenHelperName string passed must be the "key" under which a valid CDFGenHelper interface is indexed in the ASP application's Application collection. If the object cannot be found in the Application collection, the Run method will fail.

The Run method will also fail if the class Server object did not create the instance of the CDFGenerator class, because the UserObjects object will not have been properly instantiated.

Examples

The following example first lists a hypothetical Application_OnStart subroutine located in an ASP application's Global.asa file. The subroutine creates an instance of a CDFGenHelper class and then loads a given Project object. It then adds the object to the ASP Application collection, making it available to other ASP pages within the application scope. The next example lists the contents of a hypothetical ASP page located within the application's scope (i.e., either in or below the virtual directory that contains the Global.asa file). The script creates an instance of the CDFGenerator class that generates the current user's personalized CDF string. It passes the Application "key" name of the CDFGenHelper object as an argument to the Run method. Behind the scenes, the object uses the resident UserObjects object to retrieve the user's list of selected channel GUID values that are stored in the Membership directory service under the user property specified by Project.SelectionListPropName. The Project.SelectionStylePropName optionally is checked to supply the "style" of the list (i.e., whether the list is of channels to include or exclude from the project.) The list and style are then passed to the CDFGenHelper object, and the personalized CDF string is returned. The string is then sent as the response to the user's request with the appropriate MIME-type.

Following is an excerpt from a Global.asa file

<SCRIPT LANGUAGE="VBSCRIPT" RUNAT="SERVER">
Sub Application_OnStart ()
  ...
  Set ICDFGenHelper = CreateObject("Push.CDFGenHelper")
  ICDFGenHelper.Load "Project1"
  Set Application("GenHelperProject1") = ICDFGenHelper
  ...
End Sub
...
</SCRIPT>

An ASP sample script

<%
   Set ICDFGenerator = Server.CreateObject("Push.CDFGenerator")
   ICDFGenerator.Run "GenHelperProject1"
%>

The following example illustrates what happens in the ASP script listed above behind the scenes. However, this approach is not recommended, as it would severely degrade server performance. It is presented strictly to outline the complete process encapsulated by the CDFGenerator methods, as well as facilitate debugging.

<%
   Response.Buffer = True

   '  this step is done in CDFGenerator.OnStartPage method
   Set AUO = Server.CreateObject("Membership.UserObjects")

   '  The run method does the following

   '  Get the dispinterface to the CDFGenHelper object
   Set PushPrjHelper = Application("GenHelperProject1")

   '  fetch the property names that store channel
   '  channel selections from the project
   PushPrjHelper.GetSelectionListPropName( ListPropName, StylePropName )

' get the list of channel GUIDs, and optionally, the style
' of the list
   ChannelList = AUO.Get ListPropName   ' fetch the list
   ListStyle   = AUO.Get StylePropName  ' fetch type of list

   '  Get the CDF string using the returned list and send it to
   '  the built-in ASP Response object

   call PushProject.GetCDFString(ChannelList, ListStyle, Response.Write)

   '  Set the outgoing MIME type explicitly
   Response.ContentType = "application/x-cdf"
   Response.End
%>

See Also

Class UserObjects (Membership.UserObjects)


CoClass CDFGenHelper (Push.CDFGenHelper.1)

Class CDFGenHelper

Programmatic Identifier: Push.CDFGenerator.1

The Push.CDFGenHelper COM class, hereafter referred to as the CDFGenHelper class, defines an Automation object that is used in an Active Server Pages (ASP) environment to generate and return personalized channel content for users. This class is designed to serve personalized CDF strings using a resident copy of a Push.Project object. Normally, an instance of the class is created in the Application_OnStart subroutine located in an ASP application's Global.asa file. It is then normally added to the Application Dictionary object and hence made available to executing ASP scripts that fall within the ASP application scope.

The CDFGenHelper class exposes a dual interface to methods and properties. They can be accessed via the IDispatch interface or the ICDFGenHelper COM interface. The interfaces exposed are listed below.

Interface ICDFGenHelper

The CDFGenHelper class exposes a dual interface to methods and properties. They are accessible as a dispinterface via the IDispatch COM interface, or directly through the custom ICDFGenHelper COM interface.

Methods

Name | Description
GetCDFString | Builds the custom CDF string using the selected channels.
GetSelectionListPropName | Retrieves the property names used to store channel selections in the Membership directory service.
Load | Loads the specified project.

Properties

Name | Description
Project | The dispinterface to a Project object.


ICDFGenHelper GetCDFString Method

GetCDFString Method

The GetCDFString method generates a subset of the CDF formatted string defined by the loaded Project object and the list of Channel.GUID values passed, placing the string into the third "out" argument.

VBScript Syntax

ICDFGenHelper.GetCDFString  ChannelList,  ListStyle, CDFStringout

Parameters

ChannelList

The user's array list of channel GUIDs. (VT_ARRAY)

ListStyle

A Boolean specifying the nature of the list. TRUE means the list is for inclusion (VT_BOOL)

CDFStringout

On return, the personalized CDF string. (VT_BSTR)

Remarks

This method is invoked automatically during the execution of the Push.CDFGenerator.Run method.

Example

The example below shows how an object of this class can be used to return a personalized CDF string for a user.

VBScript in an ASP page

<%
    '  The object is usually pre-created and
    '  stored in the Application object.  In this case,
    ' assume the object is stored in the Application Dictionary
    ' under the key "SomeName"

    Application("SomeName").GetSelectionListPropName LName, LStyle
    Set AUO = Server.CreateObject("Membership.UserObjects")
    List = AUO.Get LName
    Style = AUO.Get LStyle

    ' Spit out the CDF string to the Response stream
    Response.ContentType = "application/x-cdf"
    Application("SomeName").GetCDFString List,Style,Outstring
    Response.Write Outstring
    Response.End

GetSelectionListPropName Method

The GetSelectionListPropName method gets the names of the user properties in the Membership directory service. These strings are properties of the currently loaded Project object.

VBScript Syntax

ICDFGenHelper.GetSelectionListPropName  ListPropName,  StylePropName

Parameters

ListPropName

On return, a string containing the name of the user property in the directory that stores the channel selections (VT_BSTR).

StylePropName

On return, a string containing the name of the user property in the directory that stores the type of list (VT_BSTR).

Remarks

The values set in the passed parameters are fetched from the currently loaded Project object. Attempting to fetch these values before the Load method has been invoked will cause an exception to occur.

Example

VBScript in an ASP page

<%
'  The CDFGenHelper is normally kept in the Application Dictionary
'  under some friendly name.  Assume "CDFGenHelper" for this example

Application("CDFGenHelper").GetSelectionListPropName( Listname, ListStyle)

%>

See Also

Project SelectionListPropName Property

Project SelectionStylePropName Property


ICDFGenHelper Load Method

Load Method

The Load method creates an instance of the Project class and loads a specified project (that is, invokes the Project.Load method).

VBScript Syntax

ICDFGenHelper.Load Name

Parameters

Name

The name of the project to load.

Remarks

The Load method should normally be called within an ASP application's global.asa file within the Application_OnStart subroutine after an instance of the object is created.

Example

VBScript in a global.asa file

Sub Application_OnStart
  Set ICDFGenHelper = CreateObject("Push.CDFGenHelper")
  ICDFGenHelper.Load "ProjectName"
  Set Application("ProjectName") = ICDFGenHelper
  ...
End Sub


Interface ICDFGenHelper Project Property

Project Property

The Project property is the currently loaded class Project object.

VBScript Syntax

ICDFGenHelper.Project

Type

IProject (VT_DISPATCH)

Example

VBScript in ASP script

<%
Set ICDFGenHelper = Application("SomeHelper")
IProject = ICDFGenHelper.Project
…
%>


CoClass Channel (Push.Channel.1)

Class Channel

Programmatic Identifier: Push.Channel.1

The Push.Channel.1 COM class, hereafter referred to as the Channel class, defines an Automation compliant COM object that can be used to manage information used to build an CHANNEL XML element as defined by the Channel Definition Format (CDF) specification.

Dispinterface IChannel

The Channel class exposes a dispinterface to the methods listed below. Therefore, all invocations must proceed through the IDispatch interface only.

Methods

Name | Description
AddElement | Adds a user-defined XML element to the Elements collection.
AddHTTPEquiv | Adds an HTTPEquiv object to the HTTPEquivs collection.
AddItem | Adds an Item object to the Items collection.
AddSoftwarePackage | Adds a SoftwarePackage object to the SoftwarePackages collection.
AddSubchannel | Adds a Channel object to the SubChannels collection.
AddUsage | Adds a Usage object to the Usages collection.
DeleteObjects | Deletes all marked objects in subcollections.
GetCDFString | Builds and returns the CDF string defined by the object and all subobjects in collections.
GetCDFStringforChannel | Builds and returns the CDF string defined by the Channel object only. Collections of objects are not incorporated.
GetCDFStringForItems | Builds and returns the CDF string defined by the Item objects in the Items collection.
GetCDFStringForSubChannels | Builds and returns the CDF string defined by the Channel objects in the Subchannels collection.
Refresh | Runs the refresh cycle on the Channel object.
RefreshAll | Runs the refresh cycle on the Channel object and then invokes RefreshAll on all Channel objects in the Subchannels collection.

Properties

Name | Description
Abstract | Specifies a value for the ABSTRACT element.
Base | Specifies a value for the BASE attribute.
ChanScript | Specifies a value for the CHANSCRIPT element.
Copyright | Specifies a value for the COPYRIGHT element.
DefaultPref | Specifies a value for the DEFAULTPREF attribute.
DeleteOnRefresh | Specifies whether a Parent Channel object should delete this object when DeleteObjects is invoked.
GUID | A globally unique identifier for the channel. (read-only)
HREF | Specifies a value for the HREF attribute.
ID | Specifies a value for the ID attribute.
ItemFormat | Specifies a value for the ITEMFORMAT element.
ItemScript | Specifies a value for the ITEMSCRIPT element.
LastMod | Specifies a value for the LASTMOD attribute.
Level | Specifies a value for the LEVEL attribute.
MinStorage | Specifies a value for the MINSTORAGE element.
NeedsLogin | Specifies whether to generate a LOGIN element.
Precache | Specifies a value for the PRECACHE attribute.
PublicationDate | Specifies a value for the PUBLICATIONDATE element.
RefreshScript | Specifies the refresh agent script to use if RefreshType is set to "userscript" or "custom."
RefreshType | Specifies the type of refresh agent to use during the refresh cycle.
Title | Specifies the value for the TITLE element.

Collections

Name | Description
Authors | A collection of Author names.
Elements | A collection of user-defined XML elements.
HTTPEquivs | A collection of HTTPEquiv objects.
Items | A collection of Item objects.
Keywords | A collection of keywords.
LogoRefs | A collection of Logo references to keys in a Project object's Logos collection.
Logs | A collection of Log strings
Publishers | A collection of publisher's names
RefreshOptions | A collection of refresh cycle options.
SoftwarePackages | A collection of SoftwarePackage objects.
Subchannels | A collection of Channel objects.
Usages | A collection of Usage objects.


AddElement Method

The AddElement method first creates an instance of the Dictionary class and sets the new object's "tag" and "content" keys to the strings passed as parameters to the method. It then adds the object to the corresponding Elements collection and returns the IDispatch interface of the added object.

This method is provided by many of the Push classes to allow the addition of special XML elements that are not represented by the objects directly.

VBScript Syntax

IObject.AddElement  tag [, content]

Parameters

tag (VT_BSTR)

A string specifying the name of the tag.

content (VT_BSTR)

The optional string specifying the content enclosed by the tag.

Return Value

The IDictionary dispinterface on the Dictionary object added to the collection (VT_DISPATCH).

Remarks

See the reference section on the Elements collection for a complete discussion on defining custom XML elements.

Example

VBScript and Windows Scripting Host

CodebaseObject.AddElement "NEWELEMENT", "VALUE"

See Also

The Elements Collection

Defining a Custom XML Element


AddHTTPEquiv Method

The AddHTTPEquiv method first creates an instance of an HTTPEquiv class and sets the new object's Name and Value properties to the strings passed as arguments to the method. It then adds the associated IHTTPEquiv dispinterface to the HTTPEquivs collection, and returns it.

VBScript Syntax

IObject.AddHTTPEquiv  name, value

Parameters

name (VT_BSTR)

A string specifying the value for the element's NAME attribute.

value (VT_BSTR)

A string specifying the value for the element's VALUE attribute.

Return Value

The IHTTPEquiv dispinterface added to the HTTPEquivs collection (VT_DISPATCH).

Example

VBScript and Windows Scripting Host

Set oHttpEquiv = CreateObject("Push.HTTPEquiv")
oHttpEquiv.Name = "This"
oHttpEquiv.Value = "That"

Set oChannel = CreateObject("Push.Channel")
Channel.Httpequivs.Add oHttpEquiv

See Also

The HTTPEquiv Class


Dispinterface IChannel AddItem Method

AddItem Method

The AddItem method creates an instance of an Item class, adds the corresponding IItem dispinterface to the Items collection, and returns the interface.

VBScript Syntax

IChannel.AddItem

Parameters

None

Return Value

The IItem dispinterface (VT_DISPATCH)

Remark

The AddItem method is the easiest way to quickly add an Item object's dispinterface to the Channel.Items collection. The same thing is accomplished by instantiating a Item object and explicitly adding the interface to the Items collection.

Example

VBScript and Windows Scripting Host

' Long method
Set IDispItem = CreateObject("Push.Item")
Set IDispChannel = CreateObject("Push.Channel")
IDispChannel.Items.Add IDispItem

' Short method
Set IDispChannel = CreateObject("Push.Channel")
IDispChannel.AddItem

See Also

The Item Class


Dispinterface IChannel AddSoftwarePackage Method

AddSoftwarePackage Method

The AddSoftwarePackage method creates an instance of the SoftwarePackage class, adds the corresponding ISoftwarePackage dispinterface to the SoftwarePackages collection, and returns the interface.

VBScript Syntax

IChannel.AddSoftwarePackage

Parameters

None

Return Value

The ISoftwarePackage dispinterface (VT_DISPATCH)

Remarks

The SoftwarePackages collection is a List object housing ISoftwarePackage dispinterfaces. One can use the AddSoftwarePackage method to add the interface, or do so explicitly. Both approaches are shown in the example below.

Example

VBScript and Windows Scripting Host

Set IDispChannel = CreateObject("Push.Channel")
IDispChannel.AddSoftwarePackage

' same as

Set IDispChannel = CreateObject("Push.Channel")
Set IDispSoftPack = CreateObject("Push.SoftwarePackage")
IDispChannel.SoftwarePackages.Add IDispSoftPack

See Also

The SoftwarePackage Class


Dispinterface IChannel AddSubchannel Method

AddSubchannel Method

The AddSubChannel method creates an instance of the Channel class, adds the corresponding IChannel dispinterface to the Subchannels collection, and returns the interface.

VBScript Syntax

IChannel.AddSubchannel

Parameters

None

Return Value

The IChannel dispinterface (VT_DISPATCH)

Example

VBScript and Windows Scripting Host

Set IDispChannel = CreateObject("Push.Channel")
Set IDispSubchannel = IDispChannel.AddSubchannel
Set IDispSubSubChannel = IDispSubChannel.AddSubchannel


AddUsage Method

The AddUsage method first creates an instance of the Usage class and sets the new object's Type and Content properties to the strings passed as arguments to the method. It then adds the associated dispinterface to the Usages collection and returns it.

VBScript Syntax

IObject.AddUsage type [, content]

Parameters

type (VT_BSTR)

The string to set the Type property on the new class Usage object.

content (VT_BSTR)

The optional string to set the Content property on the new class Usage object.

Return Value

The IUsage dispinterface added to the collection (VT_DISPATCH).

Example

VBScript and Windows Scripting Host

Set oChannel = CreateObject("Push.Channel")
Set Usage = oChannel.AddUsage("screensaver")

See Also

The Usage Class


Dispinterface IChannel DeleteObjects Method

DeleteObjects Method

The DeleteObjects method deletes all objects in the class Channel object's collections that are marked with DeleteOnRefresh = True.

VBScript Syntax

IChannel.DeleteObjects

Parameters

None

Return Value

None

Remarks

This method strictly removes objects marked for deletion in this object's collections. To remove all objects in the hierarchy marked for deletion, invoke the Refresh method.

Example

VBScript and Windows Scripting Host

Set IDispChannel = CreateObject("Push.Channel")
Set IDispC2 = IDispChannel.AddSubchannel
IDispC2.DeleteOnRefresh = 1
IDispChannel.DeleteObjects  '  oC2 deleted from subchannels 'collection


Dispinterface IChannel GetCDFString Method

GetCDFString Method

The GetCDFString method builds and returns the CDF string defined by this object's properties and collections.

VBScript Syntax

IChannel.GetCDFString
 IProject,
  [ ISchedule,
   [ ILogTarget,
    [ fTopLevel ] ] ]

Parameters

IProject

An IProject dispinterface.

ISchedule

An optional ISchedule dispinterface.

ILogTarget

An optional ILogTarget dispinterface.

fTopLevel

An optional integer flag specifying whether to build a <GENERATED-BY> element.

Return Value

The CDF formatted string (VT_BSTR)

Remarks

When this method is invoked, the following occurs:

  1. All defined properties of the object cause the construction and addition of their corresponding attribute or element to the CDF string.

  2. All collections are enumerated, and the corresponding element constructed and added to the CDF string. For collections of dispinterfaces, GetCDFString is invoked on each and the returned strings are added to the CDF string.

  5. Each Channel object represents a node in the overall hierarchy of objects. When the GetCDFString method is invoked on a particular node (Channel object), the complete CDF formatted string representing that portion of the hierarchy is produced that starts with said node and descends along all possible paths to terminating leafs. (I.e., that portion of the overall hierarchy is generated recursively, starting with the Channel object on which GetCDFString was invoked.)

The IProject parameter is required for all invocations of GetCDFString. This Project object is used to map the strings in the LogoRefs collection to ILogo dispinterfaces found the associated Project object's Logos collection. For each mapped dispinterface, the GetCDFString method is invoked on each and the resulting string is added to the total CDF string.

The ISchedule, ILogTarget and fTopLevel optional arguments can be used to add the SCHEDULE, LOGTARGET and GENERATED-BY elements to the Channel object's CDF string. When passed, the GetCDFString method is invoked on each dispinterface and the resulting string added to the total CDF string. The integer flag, if set to 1, causes the insertion of a GENERATED-BY element. These dispinterfaces do not get propagated to objects in collections.

Example

VBScript and Windows Scripting Host

Set IDispProject = CreateObject("Push.Project")
Set IDispSchedule = CreateObject("Push.Schedule")
Set IDispLogTarget = CreateObject("Push.LogTarget")
Set IDispTopChan = oProject.Channel
Set IDispSubChan = oTopChan.AddSubchannel
Set IDispSubSubChan = oSubChan.AddSubchannel
wscript.echo IDispTopChan.GetCDFString IDispProject, IDispSchedule, IDispLogTarget, 1

would produce the following CDF string: (abbreviated to emphasize the hierarchy)

<CHANNEL>
<SCHEDULE></SCHEDULE>
<LOGTARGET><LOGTARGET>
<GENERATED-BY>
<CHANNEL>
<CHANNEL></CHANNEL>
</CHANNEL>
</CHANNEL>

In this example, only the Project dispinterface is passed:

Set IDispProject = CreateObject("Push.Project")
Set IDispTopChan = oProject.Channel
wscript.echo IDispTopChannel.GetCDFString(IDispProject)

This would produce the following CDF string:

<CHANNEL></CHANNEL>


Dispinterface IChannel GetCDFStringForChannel Method

GetCDFStringForChannel Method

The GetCDFStringForChannel method builds and returns the CDF string defined by this Channel object only.

VBScript Syntax

IChannel.GetCDFStringForChannel
IProject
 [, ISchedule
   [, ILogTarget
      [, fTopLevel ] ] ]

Parameters

IProject (VT_DISPATCH)

an IProject dispinterface

ISchedule (VT_DISPATCH)

an optional ISchedule dispinterface

ILogTarget (VT_DISPATCH)

an optional ILogTarget dispinterface

fTopLevel (VT_I4)

An optional flag specifying whether to build a <GENERATED-BY> element.

Return Value

The CDF formatted string (VT_BSTR)

Remarks

This method differs from GetCDFString only in that it does not enumerate and call GetCDFString on the dispinterfaces contained in the Items, Subchannels, and Softwarepackages collections. All other collections are used to generate their corresponding elements.

Example

VBScript and Windows Scripting Host

Set IProject = CreateObject("Push.Project")
Set ISchedule = CreateObject("Push.Schedule")
Set ILogTarget = CreateObject("Push.LogTarget")

Set ITopChan = IDispProject.Channel
ITopChan.Title = "Top Channel"
ITopChannel.Base = "http://someserver/channel/"

ITopChan.Addsubchannel
ITopChan.AddItem
ITopChan.AddSoftwarePackage

wscript.echo IDispTopChan.GetCDFStringForChannel(IProject, ISchedule, ILogTarget, 1)

produces the following CDF string:

<CHANNEL BASE="http://someserver/channel/">
<TITLE>Top Channel</TITLE>
<SCHEDULE></SCHEDULE>
<LOGTARGET></LOGTARGET>
<GENERATED-BY/>
</CHANNEL>

See Also

GetCDFString Method


Dispinterface IChannel GetCDFStringForItems Method

GetCDFStringForItems Method

The GetCDFStringForItems method builds and returns the CDF string defined by the object's Items collection.

VBScript Syntax

IChannel.GetCDFStringForItems IProject

Parameters

IProject

a IProject dispinterface (VT_DISPATCH)

Return Value

The CDF formatted string (VT_BSTR)

Remarks

When this method is invoked, the GetCDFString method is in turn invoked on each IItem interface in the Items collection. The total resulting CDF string is then returned.

The IProject parameter is required for all invocations of GetCDFStringForItems. This IProject dispinterface is passed as an argument to invocations of GetCDFString.

Example

VBScript and Windows Scripting Host

Set IDispProject = CreateObject("Push.Project")
IDispProject.AddLogo "Item Logo" , "images/itemlogo.gif", "ICON"

Set IDispChannel = IDispProject.Channel
Set Item1 = IDispChannel.AddItem
Item1.LogoRefs.Add "Item Logo"
Set Item2 = IDispChannel.AddItem
Item2.LogoRefs.Add "Item Logo"

wscript.echo IDispChannel.GetCDFStringForItems(IDispProject)

This produces the following output

<ITEM>
<LOGO HREF="images/itemlogo.gif" STYLE="ICON"/>
</ITEM>
<ITEM>
<LOGO HREF="images/itemlogo.gif" STYLE="ICON"/>
</ITEM>

See Also

IItem GetCDFString Method

Items Collection


Dispinterface IChannel GetCDFStringForSubchannels Method

GetCDFStringForSubchannels Method

The GetCDFStringForSubChannels method builds and returns the CDF string defined by this Channel object's SubChannels collection.

VBScript Syntax

IChannel.GetCDFStringForSubchannels IProject

Parameters

IProject

An IProject dispinterface (VT_DISPATCH)

Return Value

The CDF formatted string (VT_BSTR).

Remarks

When this method is invoked, the GetCDFString method is in turn invoked on each IChannel dispinterface in the SubChannels collection. The total resulting CDF string is then returned.

The IProject argument is required for all invocations of GetCDFStringForSubchannels. This specified dispinterface is passed as an argument to all invocations of GetCDFString on the IChannel dispinterfaces.

Example

Set Project = CreateObject("Push.Project")
Project.Channel.AddSubChannel
Project.Channel.AddSubChannel
WScript.Echo Project.Channel.GetCDFStringForSubchannels(Project)

See Also

GetCDFString Method


Dispinterface IChannel Refresh Method

Refresh Method

This method runs the refresh cycle on the Channel object.

VBScript Syntax

IChannel.Refresh  IProject

Parameters

IProject

An IProject dispinterface (VT_DISPATCH)

Return Value

None

Remarks

The Refresh method runs the refresh cycle for this Channel object. When the method executes, it checks the RefreshType property value. If the string is not "userscript", "custom", "manual" or "none", it checks the appropriate registry location for a key that matches the string (case is ignored). When found, it finds the agent's corresponding "Script Name" named value. It then gets the "Script Language" named value that holds the corresponding scripting language identifier. Using these two values, it creates an Active Scripting Host to execute the agent. It passes four dispinterfaces to the host so that they appear within the namespace of the agent script. These interfaces and their corresponding namespace names are listed in the table below

Namespace name | dispinterface
channel | The IChannel interface for the Channel object.
project | The IProject dispinterface passed to the method as an argument.
options | The dispinterface on the Dictionary object referred to by the RefreshOptions collection.
util | A dispinterface on a "utility" object.

If the RefreshType property is set to "userscript" or "custom," the process is the same, except that the file parsed and executed is pointed to by the RefreshScript property. If the RefreshType property value is "manual" or "none" no refresh cycle occurs.

The registry keys used by the Refresh method are all found under the key:

HKLM\Software\Microsoft\Site Server\3.0\Active Channel\Active Channel Agents\.

Example

VBScript

Set IProject = CreateObject("push.project.1")
Set IChannel = IProject.Channel
IChannel.RefreshType = "File System"
IChannel.RefreshOptions("directory") = "c:\channelcontent\"
IChannel.RefreshOptions("matchcriteria") = Array("*.asp","*.htm","*.doc")
' before
wscript.echo "before refresh"
wscript.echo IChannel.GetCDFString IProject
IChannel.Refresh IProject
' channel has the filesystem agent refresh it
wscript.echo "after refresh"
wscript.echo IChannel.GetCDFString IProject

See Also

IProject Refresh Method

RefreshOptions Collection

RefreshType Property


Dispinterface IChannel RefreshAll Method

RefreshAll Method

The RefreshAll method runs the refresh cycle for this Channel (i.e. invokes Refresh) and then invokes RefreshAll on each Channel object in the SubChannels collection.

VBScript Syntax

IChannel.RefreshAll  IProject

Parameters

IProject

An IProject dispinterface (VT_DISPATCH).

Return Value

None

Remarks

This method differs from the Refresh method in that it descends through the Channel object's SubChannels collection, invoking RefreshAll on each Channel object's dispinterface contained within. Thus, if invoked on the top level Channel object then all Channel objects in the hierarchy will have Refresh invoked in turn. In fact, this is precisely what occurs upon invocation of a Project object's Refresh method.

Example

VBScript

Set IProject = CreateObject("push.project")
Set IChannel = IProject.Channel
' (set up refresh options here
call IChannel.RefreshAll(IProject)

See Also

Refresh Method

RefreshOptions Collection


Abstract Property

This property holds the value used to build an optional ABSTRACT CDF element. When the CDF string for an object that has an Abstract property is constructed, the property is checked. If it is not null, the <ABSTRACT> element is added to the string with the value of the property as the contents.

Type

String (VT_BSTR)

Default

Null

Example

VBScript

IDispChannel.Abstract = "This channel contains …"


Base Property

This property holds the value used to build an optional BASE CDF attribute for the owning object's CDF element. When the CDF string for an object that has a Base property is constructed, the property is checked. If it is not null, the BASE attribute is added to the string with the value of the property as the value.

Type

String (VT_BSTR)

Default

Null

Remarks

This property acts like a "default" URL prefix for all ITEM HREF values within the CHANNEL. Therefore, it should be set to a valid URL or URI.

Example

VBScript

IDispChannel.Base = "http://someserver/somecontent/"


ChanScript Property

The ChanScript property holds the value used to build an optional CHANSCRIPT CDF element. When the CDF string for an object that has a ChanScript property is constructed, the property is checked. If it is not null, the <CHANSCRIPT> element is added to the string, with the value of the property set as the contents.

Type

String (VT_BSTR)

Default

Null

Remarks

This element is used by the Mobile Channel channel distribution system to identify an ITEM element that contains an HREF to a Mobile Channel script. The value of the element should specify an ID attribute value for an ITEM element contained within the CHANNEL CDF element.

A complete discussion of this element and its associated functionality is beyond the scope of this documentation. For additional information about XML elements used by the Mobile Channel channel distribution system, see the product documentation and software development kit (SDK).

Example

VBScript

IDispChannel.ChannelScript = "item2"
Set IDispItem = IDispChannel.AddItem
IDispItem.ID = "item2"
IDispItem.HREF="http://someserver/somedir/itemscript.mcs"


Copyright Property

This property holds the value used to build an optional COPYRIGHT CDF element. When the CDF string for an object that has an Copyright property is constructed, the property is checked. If it is not null, the <COPYRIGHT> element is added to the string with the value of the property as the contents.

Type

String (VT_BSTR)

Default

Null

Example

VBScript

IDispChannel.Copyright = "Copyright&copy; 1998 SomeCompany, Inc"
Set IDispItem = IDispChannel.AddItem
IDispItem.Copyright = "Copyright&copy; 1998 SomeCompany, Inc"


DefaultPref Property

The DefaultPref property holds the value used to build an optional DEFAULTPREF attribute for the owning Channel object's CDF element. When the CDF string for the object is constructed, the property is checked. If it is not null, the DEFAULTPREF attribute is added to the element, with the value of the property set as the value.

Type

BSTR (VT_BSTR)

Default

Null

Remarks

This element is used by the Mobile Channel channel distribution system to identify a default preference to subscriptions for the channel. If a client accepts default subscriptions to channels, then all CHANNEL elements containing the DEFAULTPREF="YES" attribute/value pair will be subscribed to.

The Mobile Channel channel distribution system currently accepts either "YES" or "NO" as valid values for this attribute.

A complete discussion of this element and its associated functionality is beyond the scope of this documentation. For additional information about XML elements used by the Mobile Channel channel distribution system, see the product documentation and SDK.

Example

VBScript

IDispChannel.DefaultPref = "YES"


DeleteOnRefresh Property

This property marks the object for deletion when the DeleteObjects method is called on the parent Channel object.

Type

Integer (VT_I4)

Default

Null

Example

Set IDispChannel = CreateObject("Push.Channel")
Set IDispItem = IDispChannel.AddItem
IDispItem.DeleteOnRefresh = 1 'true
IDispChannel.DeleteObjects  ' Item would be deleted


Dispinterface IChannel GUID Property

GUID Property

The GUID property is a read-only string holding the class Channel object's globally unique identifier. This value uniquely identifies the channel from others. A list of GUID values is normally stored in the Personalization and Membership directory service to identify the channels a user has selected to include or exclude for viewing.

Type

String (VT_BSTR) (read only)

Default

This property is generated automatically during the creation of a Channel object.

Remarks

When a user selects a channel for their personal subscriptions, one can use the UserObjects COM object (ProgID: Membership.UserObjects) to store the value. The name of the user property in the directory database is normally stored in a Project object's SelectionListPropName property. These GUID values can be fetched as well by using the UserObjects object and passed to an instance of the CDFGenerator object for generation of the personalized CDF stream.

Example

GUID = IDispChannel.GUID

See Also

Creating Personalized Channel Subscriptions

The CDFGenerator Class

The CDFGenHelper Class


HREF Property

This property holds the value used to build an optional HREF attribute for the owning object's CDF element. When the CDF string for an object that has an HREF property is constructed, the property is checked. If it is not null, the HREF attribute is added to the element with the value of the property as the value.

Type

String (VT_BSTR)

Default

Null

Remarks

This property should contain an absolute or relative URL or URI. Relative URLs are completed using a parent element's BASE attribute.

Example

VBScript

IDispChannel.Base = "http://someserver/somedirectory"
IDispItem.HREF = "page1.htm"


ID Property

The ID property holds the value used to build an optional ID attribute for the owning object's CDF element. When the CDF string for the object is constructed, the property is checked. If it is not null, the ID attribute is added to the element, with the value of the property set as the value.

Type

String (VT_BSTR)

Default

Null

Remarks

This attribute is used by the Mobile Channel channel distribution system to create a small identifier for an ITEM or CHANNEL element in a CDF stream. This is useful in cases where network bandwidth is at a premium, and sending long URLs for each element is not desirable or required. The intention is for the ID attribute to be a small string that is unique within the transmitted CDF stream. For example:

<CHANNEL ID="c1">
<ITEM ID="item1">…</ITEM>
</CHANNEL>

A requirement is made that the top-level channel ID must be the same as the name of a .cdf file, if one is used.

A complete discussion of this element and its associated functionality is beyond the scope of this documentation. For additional information about XML elements used by the Mobile Channel channel distribution system, see the product documentation and SDK.

Example

VBScript

IDispChannel.ID = "c1"
IDispItem = IDispChannel.AddItem
IDispItem.ID = "i1"


ItemFormat Property

The ItemFormat property holds the value used to build an optional ITEMFORMAT CDF element. When the CDF string for an object that has a ItemFormat property is constructed, the property is checked. If it is not null, the <ITEMFORMAT> element is added to the string, with the value of the property set as the contents.

Type

String (VT_BSTR)

Default

Null

Remarks

This element is used by the Mobile Channel channel distribution system to specify how a given ITEM element's associated data file is formatted. These files are used to simplify the presentation of data. If the element is included within a CHANNEL element, the ITEMFORMAT value is "inherited" by all child ITEM elements within.

A complete discussion of this element and its associated functionality is beyond the scope of this documentation. For additional information about XML elements used by the Mobile Channel channel distribution system, see the product documentation and SDK.

Example

VBScript

Set IDispChannel = CreateObject("Push.Channel")
Set IDispItem = IDispChannel.AddItem()
IDispItem.ItemFormat = ";TITLE,PICTURE=IMG,BODY"


ItemScript Property

The ItemScript property holds the value used to build an optional ITEMSCRIPT CDF element. When the CDF string for an object that has a ItemScript property is constructed, the property is checked. If it is not null, the <ITEMSCRIPT> element is added to the string, with the value of the property as the contents.

Type

String (VT_BSTR)

Default

Null

Remarks

This element is used by the Mobile Channel channel distribution system to identify an ITEM element that contains an HREF to a Mobile Channel script used to present an ITEM element's associated content. The value of the element should specify an ID attribute value for an ITEM element contained within the CHANNEL CDF element. If the ITEMSCRIPT element is added as a child element within a CHANNEL element, all ITEM elements "inherit" the value of the ITEMSCRIPT element.

A complete discussion of this element and its associated functionality is beyond the scope of this documentation. For additional information about XML elements used by the Mobile Channel channel distribution system, see the product documentation and SDK.

Example

VBScript

Set IDispChannel = CreateObject("Push.Channel")
Set IDispItem = IDispChannel.AddItem()
IDispItem.ItemFormat = ";TITLE,PICTURE=IMG,BODY"


LastMod Property

This property holds the value used to build an optional LASTMOD attribute for the owning object's CDF element. When the CDF string for an object that has a LastMod property is constructed, the property is checked. If it is not null, the LASTMOD attribute is added to the string with the value of the property as the value.

Type

Date (VT_DATE)

Default

Null

Example

VBScript

IDispChannel.LastMod = #12/12/1998 12:00:00:00"


Level Property

This property holds the value used to build an optional LEVEL attribute for the owning object's CDF element. When the CDF string for an object that has an Level property is constructed, the property is checked. If it is not null, the LEVEL attribute is added to the element with the value of the property as the value.

Type

Integer (VT_I4)

Default

Null

Example

VBScript

IDispChannel.Level = 2


Dispinterface IChannel MinStorage Method

MinStorage Property

This property holds the value used to build an optional MINSTORAGE CDF element. When the CDF string for an object that has a Title property is constructed, the property is checked. If it is not null, the <MINSTORAGE> element is added to the string with the value of the property set as the contents.

Type

Integer (VT_I4)

Default

Null

Example

VBScript

IDispChannel.MinStorage = 2000


Dispinterface IChannel DeleteOnRefresh Method

DeleteOnRefresh Property

This property marks the object for deletion from a parent Channel object's collection. The deletion occurs when a process invokes the DeleteObjects method on the parent.

Type

Integer (VT_I4)

Default

0 (False)

Remarks

An agent or program must call the DeleteObjects method explicitly to delete the marked objects in collections.

Example

VBScript

Set IChannel = CreateObject("Push.Channel")
Set IItem = IChannel.AddItem
IItem.DeleteOnRefresh = TRUE
…


Dispinterface IChannel NeedsLogin Property

NeedsLogin Property

This integer flag specifies whether the <LOGIN/> child element should be constructed and added to the class Channel object's CDF string when GetCDFString is invoked.

Type

Integer (VT_I4)

Default

0 (false)

Example

IChannel.NeedsLogin = True 'or 1

The CDF string for the channel would then include a <LOGIN/> element.


Precache Property

This property holds the value used to build an optional PRECACHE attribute for the owning object's CDF element. When the CDF string for an object that has a Precache property is constructed, the property is checked. If it is not null, the PRECACHE attribute is added to the element with the value of the property as the value.

Type

String (BSTR)

Default

Null

Remarks

The CDF specification currently defines either "YES" or "NO" as valid values for this attibute.

Example

VBScript

IDispChannel.Precache = "YES"


PublicationDate

PublicationDate Property

This property holds the value used to build an optional PUBLICATIONDATE CDF element. When the CDF string for an object that has a PublicationDate property is constructed, the property is checked. If it is not null, the <PUBLICATIONDATE> element is added to the string with the value of the property as the contents.

Type

Date (VT_DATE)

Default

Null

Example

VBScript

IDispChannel.PublicationDate = #12/12/1998 12:00:00#


Dispinterface IChannel RefreshScript Property

RefreshScript Property

The RefreshScript property is a string specifying the name of an agent script to use during the refresh cycle if the RefreshType property contains the value "userscript" or "custom" when the Refresh method is invoked on the class Channel object. This script is used as the refresh agent. The value can be a full file system path, a relative path, or simply a name, in which case the default "c:\microsoft site server\bin" directory is assumed to contain the script.

Type

String (VT_BSTR)

Default

Null

Example

In this example, the custom refresh agent simply adds two Item objects to the Channel object during the refresh cycle.

Contents of file build_project.vbs

'  Using VBScript and Windows Scripting Host
'   Here the channel is configured and refreshed
Set Prj = CreateObject("Push.Project")
Prj.Channel.RefreshType="UserScript"
Prj.Channel.refreshscript=".\CustomAgentScript.vbs"
call Prj.Channel.Refresh(Prj)

At this point the contents of the file CustomAgentScript.vbs are passed to the scripting host for parsing and execution. The script could look simply like this:

channel.AddItem()
channel.AddItem()


Dispinterface IChannel RefreshType Property

RefreshType Property

The RefreshType property is a string specifying the Active Channel Server Agent to use during the refresh cycle.

Type

String (VT_BSTR)

Default

None

Remarks

There are three categories of agents:

"userscript" or "custom"

The script name identified by the RefreshScript property is passed to the Active Scripting Host.

"manual" or "none"

No refresh cycle is run on this channel, and control is returned to the caller of Refresh.

All others.

The value is used to look up a registry key to find the associated named values defining the agent. The agent script specified by the named value "Agent Script" is passed to the Active Scripting Host.

If this property contains something other that "manual" or "none", and the system is unable to locate the appropriate agent script, an agent error is.

The table below lists the default agent names that come with the server, along with a brief description. Any number of new agents can be added.

Value | Meaning
"manual" or "none" | There is no agent for the channel; the content items are refreshed manually.
"File System" | Use the file system agent.
"Search" | Use the index server agent.
"Database" | Use the database agent.
"Promotions" | Use the Promotions agent.
"Briefing" | Use the briefing agent.
"userscript" or "custom" | Use a custom agent. Use the RefreshScript to specify the name of the script.

It is important to keep the spacing shown above when assigning the agent to the RefreshType property. For example: assigning "FILESYSTEM" will not work. It must be "file system". (Case is ignored in VBScript).

Example

'  VBScript
Prj.Channel.refreshscript="c:\agents\customscript.vbs"
Prj.Channel.refreshType="userscript"


Title Property

This property holds the value used to build an optional TITLE CDF element. When the CDF string for an object that has a Title property is constructed, the property is checked. If it is not null, the <TITLE> element is added to the string with the value of the property as the contents.

Type

String (VT_BSTR)

Default

Null

Example

VBScript

IDispChannel.Title = "The Title of the Channel"


Authors Collection

This collection is a dispinterface on a class List object intended to contain strings. When the parent object’s CDF string is assembled, each string in this collection causes the insertion of a <AUTHOR> element. The value of the string is inserted as its content.

Type

IList (VT_DISPATCH)

Contains

String (VT_BSTR)

Default

Empty

Example

VBScript

Set IChannel = CreateObject("Push.Channel")
IChannel.Authors.Add "Some Author"
Set IItem = IChannel.AddItem
IItem.Authors.Add "Author of this item"

See Also

Class List


Elements Collection

This collection is a dispinterface on a class List object that contains definitions for custom XML elements not natively supported by Push classes.

Type

IList (VT_DISPATCH)

Contains

IDictionary (VT_DISPATCH)

Default

Empty

Remarks

The Elements collection is available to define special XML elements needed by a particular Push application that is not defined within the Active Channel Server classes. The collection is a List class object that should contain Dictionary class objects. Each Dictionary object defines an XML element through a set of key/value pairs. When an object that has an Elements collection is assembling its CDF string, it enumerates each object in the collection and adds the XML element defined by each.

One normally adds elements to the Elements collection by using the AddElement method. This method automatically creates a Dictionary object and assigns the appropriate keys and values. For a full description on how to define a custom XML element, see Defining a Custom XML Element.

See Also

Defining A Custom XML Element

Class List

Class Dictionary


Defining A Custom XML Element

The Dictionary class object can define an XML element when placed in an Elements collection for a supporting object. Normally, a programmer would simply use the AddElement method to add an XML element to the collection of a particular object. This sets the name of the element, and optionally, the content. However, adding attributes requires adding extra key/value pairs to the corresponding Dictionary object. The name and content of the element use two predefined keys that are required when building the element's CDF string. The predefined keys used to define the element are listed below.

Key | Value | Value Type
Tag | This value becomes the name of the XML element. | String. The string should comply with the XML specification on naming elements.
Content | This value becomes the content of the element. | String.

All other key value pairs become attribute and value pairs for the element.

A programmer must be careful not to overwrite the contents indexed under "tag" and "content," as they are reserved and may not be used as names for attributes in this case. When the element's CDF string is built, the value under "tag" always becomes the name of the element, and the value under "content" always becomes the content of the element. All other key/value pairs always become attribute and value pairs for the element.

Example

As an example, we will add the following XML element to a Channel object:

<THIS ATTRIB1=VAL1 ATTRIB2=VAL2>
This is some content
</THIS>

The following key/value pairs would define this element in a Dictionary object.

Key | Value
Tag | "THIS"
Content | "This is some content"
"attrib1" | "VAL1"
"attrib2" | "VAL2"

Note The keys "attrib1" and "attrib2" are shown in lowercase specifically. This is because the Dictionary object stores all keys in lower case internally. Thus, "ATTRIB1", "attrib1", and "AtTrIb1" all refer to the same key. The parent object converts the keys to upper case when it creates the CDF string for the element.

The code below demonstrates the process of defining the XML element above in VBScript by using the Channel object. Since the Dictionary class is not a bona fide COM class, we cannot directly create an instance. We must use the AddElement method to get started.

Set Element = Channel.AddElement("this","this is some content")
Element("attrib1")="VAL1"
Element("attrib2")="VAL2"


HTTPEquivs Collection

This collection is a dispinterface on a class List object intended to contain IHTTPEquiv dispinterfaces. When the parent object’s CDF string is assembled, the GetCDFString method is invoked on each interface to fetch the object's CDF string contribution.

Type

IList (VT_DISPATCH)

Contains

IHTTPEquiv (VT_DISPATCH)

Remarks

Objects can be added to this collection in one of two ways:

  3. Use the parent object’s AddHTTPEquiv method.

  4. Explicitly assign the object to the List object by using the Add method.

Example

‘ VBScript and Windows Scripting Host
Set IHttpequiv = CreateObject(“Push.HTTPEquiv”)
IObject.HTTPEquivs.Add IHttpequiv

or

IHTTPEquiv = IObject.AddHTTPEquiv "this","that"

See Also

Class HTTPEquiv


Dispinterface IChannel Items Collection

Items Collection

The Items collection is a dispinterface on a class List object. The list is intended to contain IItem dispinterfaces. Each interface associates an Item object as a subordinate to the parent Channel object.

Type

IList (VT_DISPATCH)

Contains

IItem (VT_DISPATCH)

Remarks

Interfaces can be added to this collection in one of two ways:

  1. Use the parent object’s AddItem method.

  2. Explicitly assign the object to the List object using the Add method.

Each IItem dispinterface in this collection has GetCDFString invoked on it when the parent Channel object receives an invocation of GetCDFString or GetCDFStringForItems.

Example

‘ VBScript and Windows Scripting Host
Set Channel = CreateObject(“Push.Channel”)
Set Item = CreateObject(“Push.Item”)
call Channel.Items.Add(Item)

or

Set Channel = CreateObject(“Push.Channel”)
Set Item = Channel.AddItem

The second version is more compact.

See Also

Class Item


Keywords Collection

This collection is a dispinterface on a class List object intended to contain keyword strings. When the parent object’s CDF string is constructed, each string causes the generation of a <KEYWORD> element, with the string being the contents.

Type

IList (VT_DISPATCH)

Contains

String (VT_BSTR)

Remarks

Strings can be added to this collection by using the List object’s Add method.

Example

‘ VBScript and Windows Scripting Host
Set Channel = CreateObject(“Push.Channel”)
call Channel.Keywords.Add(“KeywordHere)

See Also

Class List


LogoRefs Collection

The LogoRefs collection is a dispinterface on a class List object. This collection is intended to contain strings. When the GetCDFString method is invoked on an object whose class defines a LogoRefs collection, the strings in this collection are enumerated and each is used to map to a key in a class Project object's Logos collection. Each key in the Logos collection indexes an associated ILogo dispinterface. For each such interface, the GetCDFString method is invoked, and the resulting string output is added to the enumerating object's CDF string.

Type

IList (VT_DISPATCH)

Contains

String (VT_BSTR)

Default

Empty

Remarks

Use the List object's methods to add names to the LogoRefs list. These names must refer to valid logo names in the Project object's Logos collection at the time the element is constructed with GetCDFString.

Note The LogoRefs collection stores strings in a case sensitive manner. However, the Dictionary object that stores the Project object's Logos collection uses case-insensitive keys. Any explicit comparison between the keys and the strings should be done using case-insensitive compares.

If a string exists in the LogoRefs collection that does not have a matching key in the Project.Logos collection, the following element will be produced in lieu of the LOGO element:

<BAD-LOGOREF-PRESENT HREF="…"/>

All objects that have a LogoRefs collection require a IProject dispinterface as an argument to their GetCDFString methods. The keys in this Project object’s Logos collection are used to resolve to Logo objects.

Example

Set Project = CreateObject("Push.Project")
Project.AddLogo "icon","/images/icon.gif"
Set Channel = Project.Channel
Channel.LogoRefs.Add "icon"

See Also

IProject Logos Collections

Class Logo

Class List


Logs Collection

This collection is a dispinterface on a class List object intended to contain strings. When the parent object’s CDF string is being assembled, each string in this collection causes the addition of a <LOG> element. The value of the string becomes the value of the VALUE attribute.

Type

IList (VT_DISPATCH)

Contains

String (VT_BSTR)

Default

Empty

Remarks

As of the authoring of this reference, only “document:view” was a valid value for the LOG element.

Example

VBScript

Set IDispItem = CreateObject("push.item")
IDispItem.Add "document:view"

See Also

Class List


Publishers Collection

This collection is a dispinterface on a class List object intended to contain strings. When the parent object’s CDF string is assembled, each string in this collection causes the insertion of a <PUBLISHER> element. The value of the string is inserted as its content.

Type

IList (VT_DISPATCH)

Contains

String (VT_BSTR)

Default

Empty

Example

VBScript

Set IDispPublishers = IDispItem.Publishers
IDispPublishers.Add "This Publisher's Name"

See Also

Class List


Dispinterface IChannel RefreshOptions Collection

RefreshOptions Collection

This collection is a dispinterface on a class Dictionary object. This collection contains key/value pairs that define options for the refresh cycle. This collection is passed to an agent during the refresh cycle as a Active Scripting Host “named” object to facilitate transferal of the options to the agent scripts.

Type

IDictionary (VT_DISPATCH)

Contains

Key/value pairs identifying options for the refresh cycle.

Default

Empty

Remarks

For a complete list of the options available for the pre-installed agents that ship with Active Channel Server, see Active Channel Server Pre-installed Agents Options.

Example

Set IOptions = IChannel.RefreshOptions
IOptions("Directory") = "c:\somedir\channel1"
IOptions("MatchCriteria") = Array("*.htm","*.asp","*.html")
IOptions("ItemLogoRefs") = Array("smallicon","bigicon")

See Also

Refresh Method


Dispinterface IChannel SoftwarePackages Collection

SoftwarePackages Collection

The SoftwarePackages collection is a dispinterface on a class List object. The list is intended to contain ISoftwarePackage dispinterfaces. Each interface associates a SoftwarePackage object as a subordinate to the parent Channel object.

Type

IList (VT_DISPATCH)

Contains

ISoftwarePackage (VT_DISPATCH)

Default

Empty

Example

IChannel.SoftwarePackages.Add(CreateObject("push.softwarepackage"))


Dispinterface IChannel Subchannels Collection

Subchannels Collection

The Subchannels collection is a dispinterface on a class List object. The list is intended to contain IChannel dispinterfaces. Each interface associates a Channel object as a subordinate to the parent Channel object.

Type

IList (VT_DISPATCH)

Contains

IChannel (VT_DISPATCH)

Default

Empty

Example

IChannel.Subchannels.Add(CreateObject("push.channel"))


Usages Collection

This collection is a dispinterface on a class List object intended to contain IUsage dispinterfaces. When the parent object’s CDF string is assembled, the GetCDFString method is invoked on each interface to fetch the object's CDF string contribution.

Type

IList (VT_DISPATCH)

Contains

IUsage (VT_DISPATCH)

Default

Empty

See Also

Class List Class Usage


CoClass Codebase (Push.Codebase.1)

Class Codebase

Programmatic Identifier: Push.Codebase.1

The Push.Codebase.1 COM class, hereafter referred to as the Codebase class, defines an object that can be used to manage information used to build a CODEBASE XML element as defined by the Open Software Description (OSD) specification.

The Codebase class exposes a dispinterface to the methods listed. Therefore, all invocations must proceed through the IDispatch interface.

The Codebase class exposes a dispinterface to the methods listed below. Therefore, all invocations must proceed through the IDispatch interface.

Dispinterface ICodebase

Methods

Name | Description
AddElement | Adds a user-defined XML element to the Elements collection.
GetCDFString | Builds and returns the CDF string defined by the object and all subobjects in collections.

Properties

Name | Description
Filename | Holds a string value used to build the optional FILENAME attribute for the object's CDF string.
HREF | Holds a string value used to build the optional HREF attribute for the object's CDF string.
Size | Holds a string value used to build the optional SIZE attribute for the object's CDF string.

Collections

Name | Description
Elements | A collection of user-defined XML elements.


GetCDFString Method

The GetCDFString method builds and returns the CDF string defined by an object's properties and collections. For collections of objects whose class also defines a GetCDFString method, a recursive descent mechanism is used. That is, each of these objects has its GetCDFString method invoked, and in turn that object will invoke GetCDFString on its collected objects, and so on down the line. The recursion stops when the hierarchy is exhausted.

This method is standard across all Push COM classes. In some cases, extra parameters are required to successfully invoke the method. The reference information for those implementations are listed in the COM class reference where applicable.

VBScript Syntax

IObject.GetCDFString

Parameters

None

Return Value

The CDF formatted string defined by the object.

Example

VBScript and Windows Scripting Host

WScript.Echo Object.GetCDFString


Dispinterface ICodebase Filename Property

Filename Property

This property holds the value used to build an optional FILENAME attribute. When the CDF string for the object is constructed, the property is checked. If it is not null, the FILENAME attribute is added to the resulting element with the value of the property as the value.

Type

String (VT_BSTR)

Default

null

Remarks

The FILENAME attribute specifies a file within the same archive as specified by the archive identified by the HREF attribute.

Example

VBScript

ICodebase.Filename = "software.exe"


Dispinterface ICodebase Size Property

Size Property

This property holds the value used to build an optional SIZE attribute. When the CDF string for the object is constructed, the property is checked. If it is not null, the SIZE attribute is added to the resulting element with the value of the property as the value.

Type

Integer (VT_I4)

Default

null

Remarks

The SIZE attribute specifies how much disk space the client must have available to install the software package. It is always in units of KiloBytes. (KB)

Example

VBScript

ICodebase.Size = 1024 ' 1024 KB


CoClass HTTPEquiv (Push.HTTPEquiv.1)

Class HTTPEquiv

Programmatic Identifier: Push.HTTPEquiv.1

The Push.HTTPEquiv COM class, hereafter referred to as the HTTPEquiv class, defines an object that can be used to manage information used to build an HTTP-EQUIV XML element, as defined by the XML specification.

The HTTPEquiv class exposes a dispinterface to the methods listed. Therefore, all invocations must proceed through the IDispatch interface.

Dispinterface IHTTPEquiv

Methods

Name | Description
GetCDFString | Builds and returns the CDF string defined by the object and all subobjects in collections.

Properties

Name | Description
Name | Holds a string value used to build the optional NAME attribute for the object's CDF string.
Value | Holds a string value used to build the optional VALUE attributes for the object's CDF string.


Dispinterface IHTTPEquiv Name Property

Name Property

The Name property is used to generate the NAME attribute for the HTTP-EQUIV element's XML formatted string.

Type

String (VT_BSTR)

Default

Null

Remarks

This property can be set by using the AddHTTPEquiv method when adding an HTTPEquiv object to another object's HTTPEquivs collection. The value can be passed as the first argument.

Example

Httpequiv.Name="SomeName"

See Also

AddHTTPEquiv Method


Dispinterface IHTTPEquiv Value Property

Value Property

The Value property is used to generate the VALUE attribute for the HTTP-EQUIV element's XML formatted string.

Type

String (VT_BSTR)

Default

Null

Remarks

This property can be optionally set by using the AddHTTPEquiv method when adding an HTTPEquiv object to another object's HTTPEquivs collection. The value can be passed as the second argument.

Example

Httpequiv.Value="somevalue"

See Also

AddHTTPEquiv Method


CoClass Implementation (Push.Implementation.1)

Class Implementation

Programmatic Identifier: Push.Implementation.1

The Push.Implementation.1 COM class, hereafter referred to as the Implementation class, defines an Automation-compliant object that can be used to manage information used to build an IMPLEMENTATION XML element, as defined by the Open Software Description (OSD) specification.

The Implementation class exposes a dispinterface to the methods listed. Therefore, all invocations must proceed through the IDispatch interface.

Dispinterface IImplementation

Methods

Name | Description
AddCodebase | Adds a Codebase object to the Codebases collection.
AddElement | Adds a user-defined XML element to the Elements collection.
AddOS | Adds an OS and OSVERSION definition to the OS collection.
GetCDFString | Builds and returns the CDF string defined by the object and all subobjects in collections.

Properties

Name | Description
Description | Holds a string specifying a description of the implementation.
DiskSize | Holds a string value used to build the optional DISKSIZE element for the object's CDF string.
MemSize | Holds a string value used to build the optional MEMSIZE element for the object's CDF string.

Collections

Name | Description
Codebases | A collection of Codebase objects.
Elements | A collection of user-defined XML elements.
Languages | A collection of language strings.
OS | A collection of OS and OSVERSION strings.
Processors | A collection of processor strings.
VM | A collection of VM strings.


Dispinterface IImplementation AddCodebase Method

AddCodebase Method

The AddCodebase method first creates an instance of a Codebase class and sets the new object's HREF and Filename properties to the strings passed as arguments to the method. It then adds the dispinterface to the Codebases collection and returns it.

VBScript Syntax

IImplementation.AddCodebase  href [, filename]

Parameters

href

A string to set the HREF property to.

filename

An optional string to set the optional Filename property to.

Return Value

The new Codebase object's dispinterface that was added to the collection.

Remarks

The Codebases collection is an IList dispinterface containing ICodebase dispinterfaces.

Example

' Using Windows Scripting Host and VBScript
Set Impl = CreateObject("Push.Implementation")
oCodebase = Impl.AddCodeBase("URL","filename")
wscript.echo Impl.GetCDFString

produces

<IMPLEMENTATION>
<CODEBASE HREF="http://www.somecompany.com/code"
FILENAME="c:\code\code"/>
</IMPLEMENTATION>

See Also

Codebases Collection


Dispinterface IImplementation AddOS Method

AddOS Method

The AddOS method first creates an instance of the Dictionary class and sets the new object with a key/value pair using the strings passed as parameters to the method. It then adds the dispinterface on the new object to the OS collection and returns it.

VBScript Syntax

IImplementation.AddOS os [, version]

Parameters

os

The string used to build the OS XML element's VALUE attribute. This becomes a key in the class Dictionary object.

version

The string used to build the optional OSVERSION XML element's VALUE attribute. This becomes an optional value in the class Dictionary object.

Return Value

The Dictionary object dispinterface storing OS and OSVERSION attribute strings.

Remarks

Each OS and OSVERSION child XML element can be defined within the class Dictionary object. In this case, there are no predefined keys. The string used for each Dictionary key becomes the OS XML element's VALUE attribute, and the string for each associated Dictionary value becomes the OSVERSION XML element's VALUE attribute. The OSVERSION XML element is contained by the OS XML element. For example, assume the Dictionary has the following key/value pairs:

Key | Value
MacOS | 8.0
WinNT | 4.0

When the GetCDFString method is invoked on the class Implementation object, the following XML elements would be added within the IMPLEMENTATION XML element:

<OS VALUE="macos">
<OSVERSION VALUE="8.0"/>
</OS>
<OS VALUE="winnt">
<OSVERSION VALUE="4.0"/>
</OS>

Note the lowercase strings. This is because the class Dictionary object stores all keys in their lowercase form.

Example

' Using Windows Scripting Host and VBScript
Set Impl = CreateObject("Push.Implementation")
Impl.AddOS "WinNT","4.0"
wscript.echo Impl.GetCDFString

produces

<IMPLEMENTATION>
 <OS VALUE="winnt">
  <OSVERSION VALUE="4.0"/>
 </OS>
</IMPLEMENTATION>

See Also

OS Collection


Dispinterface IImplementation Description Property

Description Property

The Description property is a string used to hold a description of the implementation. It does not result in the generation of any elements or attributes when GetCDFString is invoked.

Type

String (VT_BSTR)

Default

None

Example

' Using Windows Scripting Host and VBScript
Set Implementation = CreateObject("Push.Implementation")
Implementation.Description = "WinNT4.0Alpha"


Dispinterface IImplementation DiskSize Property

DiskSize Property

The DiskSize property is a string used when building the <IMPLEMENTATION></IMPLEMENTATION> element upon invocation of the GetCDFString method. If this property is not empty, the <DISKSIZE VALUE=""> child element is generated, and the string is inserted as the value of the VALUE attribute.

Type

Integer (VT_I4)

Default

None

Remarks

The OSD specification defines the unit of kilobyte for this element.

Example

' Using Windows Scripting Host and VBScript
Set Implementation = CreateObject("Push.Implementation")
Implementation.DiskSize = 1000
Implementation.GetCDFString

produces

<IMPLEMENTATION>
 <DISKSIZE VALUE=1000/>
</IMPLEMENTATION>


Dispinterface IImplementation MemSize Property

MemSize Property

The MemSize property is a string used when building the <IMPLEMENTATION></IMPLEMENTATION> element upon invocation of the GetCDFString method. If this property is not empty, the <MEMSIZE VALUE=""> child element is generated, and the string is inserted as the value of the VALUE attribute.

Type

Integer (VT_I4)

Default

None

Remarks

The MEMSIZE element is defined in units of kilobytes (KB).

Example

' Using Windows Scripting Host and VBScript
Set Implementation = CreateObject("Push.Implementation")
Implementation.MemSize = 12
wscript.echo Implementation.GetCDFString

outputs:

<IMPLEMENTATION>
 <MEMSIZE VALUE="12"/>
</IMPLEMENTATION>


Dispinterface IImplementation Codebases Collection

Codebases Collection

The Codebases collection is a dispinterface on a class List object intended to contain ICodebase dispinterfaces. When the parent object’s CDF string is assembled, the GetCDFString method is invoked on each interface to fetch the object's CDF string contribution.

Type

IList (VT_DISPATCH)

Contains

ICodebase (VT_DISPATCH)

Default

Empty

Example

' Using Windows Scripting Host and VBScript
Set Implementation = CreateObject("Push.Implementation")
Implementation.AddCodebase "http://someserver/code", "C:\code"
For Each Codebase in Implementation.Codebases
 wscript.echo Codebase.GetCDFString
Next
wscript.echo Impl.GetCDFString

outputs

<CODEBASE HREF=&quothttp://someserver/code"
FILENAME="C:\code"/>
<Implementation>
 <CODEBASE HREF=&quothttp://someserver/code"
 FILENAME="C:\code"/>
</Implementation>

See Also

Class List

Class Codebase


Languages Collection

The Languages collection is a dispinterface on a class List intended to contain strings. When the parent object’s CDF string is constructed, each string causes the generation of a <LANGUAGE> element, with the string being the contents.

Type

IList (VT_DISPATCH)

Contains

String (VT_BSTR)

Default

empty

Example

' Using Windows Scripting Host and VBScript
Set Implementation = CreateObject("Push.Implementation")
Implementation.Languages.Add("en")
wscript.echo Implementation.GetCDFString()

this will produce the following string:

<IMPLEMENTATION>
 <LANGUAGE VALUE="en"/>
</IIMPLEMENTATION>

See Also

Class List


Dispinterface IImplementation OS Collection

OS Collection

The OS collection is a dispinterface on a class List object intended to contain class Dictionary object dispinterfaces. Each Dictionary has key/value pairs used to build the <OS> and optionally, the <OSVERSION> elements, respectively. The key name becomes the value of the OS element's VALUE attribute. Optionally, the value associated with the key becomes the VALUE attribute of the OSVERSION element.

Type

IList (VT_DISPATCH)

Contains

IDictionary (VT_DISPATCH)

Default

Empty

Example

' Using Windows Scripting Host and VBScript
Set Impl = CreateObject("Push.Implementation")
Impl.AddOS "WinNT","4.0"
wscript.echo Impl.GetCDFString()

outputs

<IMPLEMENTATION>
 <OS VALUE="winnt">
  <OSVERSION VALUE="4.0"/>
 </OS>
</IMPLEMENTATION>

See Also

Class Dictionary

Class List


Dispinterface IImplementation Processors Collection

Processors Collection

The Processors collection is a dispinterface on a class List object intended to contain strings. When the GetCDFString method is invoked on an object whose class defines this collection, each string is used to build a <PROCESSOR VALUE="string"> child XML element.

Type

IList (VT_DISPATCH)

Contains

String (VT_BSTR)

Default

Empty

Example

Impl.Processors.Add("x86")

See Also

Class List


Dispinterface IImplementation VM Collection

VM Collection

The VM collection is a dispinterface on a class List object intended to contain strings. When the GetCDFString method is invoked on an object whose class defines this collection, each string is used to build a <VM VALUE="string"> child XML element.

Type

IList (VT_DISPATCH)

Contains

String (VT_BSTR)

Default

Empty

Example

Impl.VM.Add("1.2")

See Also

Class List


CoClass Item (Push.Item.1)

Class Item

Programmatic Identifier: Push.Item.1

The Push.Item.1 COM class, hereafter referred to as the Item class, defines an object that can be used to manage information used to build an ITEM XML element as defined by the Channel Definition Format (CDF) specification.

The Item class exposes a dispinterface to the methods listed below. Therefore, all invocations must proceed through the IDispatch interface.

Dispinterface IItem

Methods

Name | Description
AddElement | Adds a user-defined XML element to the Elements collection.
AddHTTPEquiv | Adds an HTTPEquiv object to the HTTPEquivs collection.
AddUsage | Adds a Usage object to the Usages collection.
GetCDFString | Builds and returns the CDF string defined by the object and all subobjects in collections.

Properties

Name | Description
Abstract | Holds a string value used to build the optional ABSTRACT element for the object's CDF string.
Copyright | Holds a string value used to build the optional COPYRIGHT element for the object's CDF string.
DeleteOnRefresh | Specifies whether this object should be deleted by a parent Channel object when DeleteObjects is invoked.
HREF | Holds a string value used to build the optional HREF attribute for the object's CDF string.
ID | Holds a string value used to build the optional ID attribute for the object's CDF string.
ItemFormat | Holds a string value used to build the optional ITEMFORMAT element for the object's CDF string.
ItemScript | Holds a string value used to build the optional ITEMSCRIPT element for the object's CDF string.
LastMod | Holds a string value used to build the optional LASTMOD attribute for the object's CDF string.
Level | Holds a string value used to build the optional LEVEL attribute for the object's CDF string.
MIMEType | Holds a string value used to build the optional MIMETYPE attribute for the object's CDF string.
Precache | Holds a string value used to build the optional PRECACHE attribute for the object's CDF string.
Priority | Holds a string value used to build the optional PRIORITY attribute for the object's CDF string.
PublicationDate | Holds a string value used to build the optional PUBLICATIONDATE element for the object's CDF string.
Title | Holds a string value used to build the optional TITLE element for the object's CDF string.

Collections

Name | Descriptions
Authors | A collection of Author names.
Elements | A collection of user-defined XML elements.
HTTPEquivs | A collection of HTTPEquiv objects.
Keywords | A collection of keywords.
LogoRefs | A collection of Logo references to keys in a Project object's Logos collection.
Logs | Collection of Log strings.
Publishers | A collection of publisher's names.
Usages | A collection of Usage objects.


GetCDFString (IProject) Method

GetCDFString Method

The GetCDFString method builds and returns the CDF string defined by this object's properties and collections. For collections of objects whose class also defines a GetCDFString method, a recursive descent mechanism is used. That is, each of these objects has its GetCDFString method invoked, and in turn that object will invoke GetCDFString on its collected object, and so on down the line. The recursion stops when the hierarchy is exhausted.

VBScript Syntax

IObject.GetCDFString IProject

Parameters

IProject

An IProject dispinterface. (VT_DISPATCH)

Return Value

The CDF formatted string for this item (VT_BSTR).

Remarks

The Project object's dispinterface passed to this method is used to map the strings in the LogoRefs collection to Logo objects contained in the Project Logos collection.

Example

Set Project = CreateObject("Push.Project")
Project.Load "someproject"

' Say we want the CDF string for the first item in the top
' level channel
CDFString = Project.Channel.Items(0).GetCDFString(Project)


Dispinterface IItem MIMEType Property

MIMEType Property

The MIMEType property holds a string. If defined, a MIMETYPE attribute is constructed for the ITEM XML element upon invocation of GetCDFString, with the string becoming the value of the attribute.

Type

String (VT_BSTR)

Default

None

Example

Item.MIMEType = "text/html"


Dispinterface IItem Priority Property

Priority Property

The Priority property holds a string. If defined, a PRIORITY child XML element is constructed for the ITEM XML element upon invocation of GetCDFString, with the string becoming the contents of the attribute.

Type

String (VT_BSTR)

Default

None

Example

IItem.Priority = "value"


CoClass Logo (Push.Logo.1)

Class Logo

Programmatic Identifier: Push.Logo.1

The Push.Logo.1 class, hereafter referred to as the Logo class, defines an object that can be used to manage information used to build a LOGO XML element, as defined by the Channel Definition Format (CDF) specification.

The Logo class exposes a dispinterface to the methods listed. Therefore, all invocations must proceed through the IDispatch interface.

Dispinterface ILogo

Methods

Name | Description
GetCDFString | Builds and returns the CDF string defined by this object.

Properties

Name | Description
HREF | Holds a value used to build the corresponding LOGO element's HREF attribute.
Style | Holds a optional value used to build the corresponding LOGO element's STYLE attribute.


Dispinterface ILogo Style Property

Style Property

The Style property is a string used when building the <LOGO/> element upon invocation of the GetCDFString method. If this property is not empty, the STYLE attribute is added to the element and the string is inserted as the value.

Type

String

Default

None

Remarks

For a description of possible values for this property and their meaning to presentation, see the CDF specification.

Example

Set Prj = CreateObject("Push.Logo")
Prj.HREF="http://someserver.com/images/logo1.gif"
Prj.Style="IMAGE-WIDE"
wscript.echo Prj.GetCDFString

outputs

<LOGO HREF="http://someserver.com/images/logo1.gif"
STYLE="IMAGE-WIDE"/>


CoClass LogTarget (Push.LogTarget.1)

Class LogTarget

Programmatic Identifier: Push.LogTarget.1

The Push.LogTarget.1 COM class, hereafter referred to as the LogTarget class, defines an Automation-compliant object that can be used to manage information used to build a LOGTARGET XML element, as defined by the Channel Definition Format (CDF) specification.

The LogTarget class exposes a dispinterface to the methods listed below. Therefore, all invocations must proceed through the IDispatch interface.

Dispinterface ILogTarget

Methods

Name | Description
AddElement | Adds a user-defined XML element to the Elements collection.
AddHTTPEquiv | Adds an HTTPEquiv object to the HTTPEquivs collection.
GetCDFString | Builds and returns the CDF string defined by the object and all subobjects in collections.

Properties

Name | Description
HREF | Holds a string value used to build the optional HREF attribute for the object's CDF string.
Method | Holds a string value used to build the METHOD attribute for the object's CDF string. Default="POST"
PurgeTime | Holds a string value used to build the optional PURGETIME element for the object's CDF string.
Scope | Holds a string value used to build the optional SCOPE attribute for the object's CDF string.

Collections

Name | Description
Elements | A collection of user-defined XML elements.
HTTPEquivs | A collection of HTTPEquiv objects.


Dispinterface ILogTarget Method Property

Method Property

The Method property is a string used when building the <LOGTARGET></LOGTARGET> element upon invocation of the GetCDFString method. If this property is not empty, the METHOD attribute is added to the element, and the string is inserted as the value.

Type

String (VT_BSTR)

Default

"POST"

Example

' Using Windows Scripting Host and VBScript
Set LogTarget = CreateObject("Push.LogTarget")
LogTarget.HREF="http://somecompany.com/channels/logging"
LogTarget.METHOD = "PUT"
LogTarget.PURGETIME = 8;
wscript.echo LogTarget.GetCDFString

this will produce the following string:

<LOGTARGET HREF="http://somecompany.com/channels/logging" METHOD="PUT">
 <PURGETIME HOUR = "8"/>
</LOGTARGET>


Dispinterface ILogTarget PurgeTime Property

PurgeTime Property

The PurgeTime property is an integer used when building the <LOGTARGET></LOGTARGET> element upon invocation of the GetCDFString method. If this property is not empty, the <PURGETIME></PURGETIME> element is added, with the integer value becoming the contents of the VALUE attribute.

Type

Integer (VT_I4)

Default

Null

Example

' Using Windows Scripting Host and VBScript
Set LogTarget = CreateObject("Push.LogTarget")
LogTarget.HREF="http://somecompany.com/channels/logging"
LogTarget.METHOD = "PUT"
LogTarget.PURGETIME = 8;
wscript.echo LogTarget.GetCDFString

outputs

<LOGTARGET HREF="http://somecompany.com/channels/logging" METHOD="PUT">
  <PURGETIME HOUR = "8"/>
</LOGTARGET>


Dispinterface ILogTarget Scope Property

Scope Property

The Scope property is an integer used when building the <LOGTARGET></LOGTARGET> element upon invocation of the GetCDFString method. If this property is not empty, the SCOPE attribute is added to the element, and the string is inserted as the value.

Type

String (VT_BSTR)

Default

Null

Example

' Using Windows Scripting Host and VBScript
Set LogTarget = CreateObject("Push.LogTarget")
LogTarget.HREF="http://somecompany.com/channels/logging"
LogTarget.METHOD = "PUT"
LogTarget.SCOPE = "ONLINE"
wscript.echo LogTarget.GetCDFString

outputs

<LOGTARGET HREF="http://somecompany.com/channels/logging" METHOD="PUT" SCOPE="ONLINE">
</LOGTARGET>


CoClass Manager (Push.Manager.1)

Class Manager

Programmatic Identifier: Push.Manager.1

The Push.Manager.1 COM class, hereafter referred to as the Manager class, defines an Automation-compliant object that can be used to manage aspects of the Active Channel Server system, including projects and installed agents.

The Manager class exposes a dispinterface to the methods listed below. Therefore, all invocations must proceed through the IDispatch interface.

Dispinterface IManager

Methods

Name | Description
Delete | Deletes a specified project.
GetAgents | Returns information about installed agents.
GetProjects | Returns information about saved projects.
GetTask | Returns task information about a specified project.
GetTimeSaved | Returns the last time a specified project was saved.


Dispinterface IManager Delete Method

Delete Method

The Delete method deletes a specified project.

VBScript Syntax

IManager.Delete name

Parameters

name

A string (VT_BSTR) specifying the name of the project to delete

Return Value

None (void)

Remarks

An exception will occur if a project with the specified name does not already exist.

Example

' Using Windows Scripting Host Runtime Env  (cscript.exe)
Option Explicit
Dim Manager
Set Manager = CreateObject("Push.Manager")
On Error Resume Next
Call Manager.Delete("Project1")
If Err.Number <> 0 Then
  WScript.Echo "Project does not exist!"
  Err.Clear
End If


Dispinterface IManager GetAgents Method

GetAgents Method

The GetAgents method returns a class Dictionary object's dispinterface. The keys are names of installed agents and the associated values are arrays (SAFEARRAYS) of configuration information for the agent.

VBScript Syntax

IManager.GetAgents

Parameters

None

Return Value

The IDictionary dispinterface.

Remarks

The Dictionary object stores key/value pairs that describe the various installed agents. Each key is a name of an agent, and each value is an array (SAFEARRAY) with six elements that define the agent. The table below lists the items in the order in which they appear in the array.

All information returned in the array by this method is contained in the registry at key HKLM\Software\Microsoft\Site Server\3.0\Active Channel Agents. Each agent name is a subkey, and the six values associated are the named values stored under the key.

Array Index | Reg Key named value | Description of indexed value
0 | ASP Property Page | This ASP page is used by the WebAdmin tool to set options for this agent.
1 | ASP Wizard Page | This ASP page is used by the WebAdmin tool to start the agent options wizard.
2 | COM Property Sheet | This value is a GUID identifying the COM class that implements an IPropertySheet interface. This class is "bootstrapped" by the MMC tool when a user requests to set options for this agent.
3 | Display Name | This value is the display name for the agent.
4 | Script Language | This value specifies the scripting language that the Active Scripting Host should use to run the agent.
5 | Script Pathname | This value specifies the path to the agent script.

Example

' Using Windows Scripting Host and VBScript
Option Explicit
Dim Agents
Dim Manager
Dim Items

Set Manager = CreateObject("Push.Manager")
Set Agents = Manager.GetAgents
For Each Agent in Agents
  wscript.echo "Agent Name: " & Agent
  wscript.echo "Agents definition items: "
  Items = Agents(Agent)
  For i = LBOUND(Items) to UBound(Items)
   wscript.echo Items(i)
  Next
Next

See Also

Class Dictionary


Dispinterface IManager GetProjects Method

GetProjects Method

The GetProjects method returns a class List object that contains strings. Each string is the name of a saved project located in the default data directory "c:\microsoft site server\data\pushcfg".

VBScript Syntax

IManager.GetProjects

Parameters

None

Return Value

The IList dispinterface.

Remarks

The List object contains an ordered list of string variables. Each variable contains the name of a project currently defined. One can use the name of a project to load the corresponding Project object.

Example

' VBScript and Windows Scripting Host
Option Explicit
Dim Manager
Dim Projects
Set Manager = CreateObject("Push.Manager")
Set Projects = Manager.GetProjects()
For Each Project in Projects
 wscript.echo Project
Next

See Also

Class List


Dispinterface IManager GetTask Method

GetTask

The GetTask method is used to fetch the interface on a Task object for the specified project, if it exists. This method bypasses a complete loading of the Project object when fetching this interface.

VBScript Syntax

IManager.GetTask ProjectName

Parameters

ProjectName

A string (VT_BSTR) specifying the name of a project to fetch the task object for.

Return Value

If defined, the ITask dispinterface specified by a Project object's Task property. Null (VT_NULL) is returned otherwise.

Remarks

An exception will occur if the project specified does not exist.

The project name can be an absolute pathname, a relative pathname, or just a name, in which case the default path "c:\microsoft site server\data\pushcfg" is assumed. One can skip appending the ".ppr" extension, as it is assumed in all cases.

Example

' Using Windows Scripting Host and VBScript
Option Explicit
Dim Manager
Dim Items
Dim Task

On Error Resume Next
Set Manager = CreateObject("Push.Manager")
Set Task = Manager.GetTask "projname"
If Err.Number <> 0 Then
    WScript.echo "no project by that name"
ElseIf vartype(Task) = vbNull Then
    WScript.Echo "No Task object for that project"
Else
' (do something with the task object)
' (code ommited)

End If

See Also

IProject Task Property

Class Task


Dispinterface IManager GetTimeSaved Method

GetTimeSaved Method

The GetTimeSaved method returns the date a project was last saved.

VBScript Syntax

IManager.GetTimeSaved name

Parameters

name

A string specifying the name of the project

Return Value

A Date (VT_DATE) value containing the date the project was saved.

Example

' Using Windows Scripting Host Runtime Env  (cscript.exe)
Option Explicit

Dim Manager
Dim Time_Saved
Dim Projects

Set Manager = CreateObject("Push.Manager")
Set Projects = Manager.GetProjects
For Each Project in Projects
  wscript.echo Project
  wscript.echo "Saved " & Manager.GetTimeSaved(Project)
Next


CoClass Project (Push.Project.1)

Class Project

Programmatic Identifier: Push.Project.1

The Push.Project.1 COM class, hereafter referred to as the Project class, defines an Automation-compliant object that can be used to manage information used to build content hierarchies, as defined by the Channel Definition Format (CDF) specification. The Project object always contains the top-level channel, and collects all class Logo objects for use by child objects.

The Project class exposes a dispinterface to the methods listed below. Therefore, all invocations must proceed through the IDispatch interface.

Dispinterface IProject

Methods

Name | Description
AddLogo | Adds a logo to the project.
GetCDFString | Builds the CDF string for the project.
GetXMLDocument | Returns the XML object defined by the project.
Load | Loads the specified project from disk.
OuputDebugString | Outputs a debug string.
Refresh | Starts the refresh cycle on the project.
Save | Saves the project.
SetLogTarget | Sets the logging information for clients.
SetTask | Sets the task information used to automate the refresh cycle.
WriteCDFFile | Builds the CDF string for the project and saves it to the specified file.

Properties

Name | Description
CDFEncoding | The optional CDF encoding type. Default is "UTF-8"
CDFFilename | The project's optional CDF filename. Can be specified with Save method.
CDFURL | The optional URL to the project's CDF file.
Channel | The dispinterface to the top level Channel object. Automatically created with the Project object.
DistributionList | An optional email distribution list for the project.
LogTarget | The dispinterface to an optional LogTarget object to associate with the project.
Name | An optional name for the project.
Schedule | The dispinterface to an optional Schedule object to associate with the project.
SelectionListPropName | Holds the name of a Membership directory property in which users can store channel selections.
SelectionStylePropName | Holds the name of a Membership directory service property users can store the type of channel list they desire for the project. 0 = inclusive; 1 = exclusive.
Task | The dispinterface to an optional Task object to associate with the project.

Collections

Name | Description
Logos | A collection of dispinterfaces to Logo objects.


Dispinterface IProject AddLogo Method

AddLogo

The AddLogo method adds a Logo object to the Project object.

VBScript Syntax

IProject.AddLogo description, href [, style ]

Parameters

description

A string specifying a descriptive name of the Logo object. The name is used as a key in the class Dictionary object to index this Logo object.

href

A string specifying the URL of the logo image.

style

An optional string specifying what to set the Logo.Style propery to.

Return Value

The ILogo dispinterface added to the Logos collection.

Remarks

The Logos collection holds Logo objects that can be mapped to any subordinate objects by including the associated Dictionary "key" in their LogoRefs collection.

Example

' Using Windows Scripting Host and VBScript
Option Explicit
Dim Prj
Set Prj = CreateObject("Push.Project")
Prj.AddLogo "My Icon", "c:\icons\myicon.gif", "ICON"
Prj.AddLogo "My Image", "c:\images\myimage.gif", "IMAGE"
Set Channel = Prj.Channel
Channel.LogoRefs.Add "My Icon"
Channel.LogoRefs.Add "My Image"

See Also

Class Dictionary

Class Logo

LogoRefs Collection


Dispinterface IProject GetCDFString Method

GetCDFString Method

The GetCDFString method returns a CDF-formatted string defined by the object. This includes all CDF strings for Channel and Logo objects defined for the Project object, as well as any optionally defined LogTarget and Schedule objects.

VBScript Syntax

IProject.GetCDFString [enconding]

Parameters

encoding

A string specifying an optional encoding style. (VT_BSTR)

Return Value

The CDF formatted string defined by the object. (VT_BSTR)

Remarks

If encoding is specified, it should be either "UTF-8" or "UCS-2". Internet Explorer version 4.0 clients default to "UTF-8" when no encoding is specified.

Example

' Using the Windows Scripting Host (cscript.exe) and VBScript
Set Prj = CreateObject("Push.Project")
call Prj.GetCDFString()

outputs:

<?XML version="1.0"?><CHANNEL></CHANNEL>


Dispinterface IProject GetXMLDocument Method

GetXMLDocument Method

The GetXMLDocument method returns an XML Document object as per the XML object model. This object reflects all objects defined within the Project hierarchy including channels,items,etc.

VBScript Syntax

IProject.GetXMLDocument

Parameters

none

Return Value

The new XML Document object's dispinterface. (VT_DISPATCH)

Remarks

For a complete description of the XML object model, see the Microsoft Developer's Network Online.

This method can be useful to cast the information stored in Push objects into the corresponding XML Objects for use with applications that require this model specifically.

Example

Set XMLDoc = Project.GetXMLDocument
wscript.echo XMLDoc.GetXML()


Dispinterface IProject Load Method

Load Method

The Load method loads a specified project from disk.

VBScript Syntax

IProject.Load name

Parameters

name

a string specifying the name of the project to load. (VT_BSTR)

Return Value

none

Remarks

This method will generate an exception if a project by the name specified does not exist.

The name may be a full pathname, a relative pathname, or just a name, in which case the default directory "c:\microsoft site server\data\pushcfg" is assumed. One need not specify the ".ppr" extension in the file name as it also is assumed.

Example

Set Project = CreateObject("Push.Project")
call Project.Load "ProjectName"


Dispinterface IProject OutputDebugString Method

OutputDebugString Method

The OutputDebugString method prints a debug message.

VBScript Syntax

IProject.OutputDebugString message

Parameters

message

a string specifying the text to output. (VT_BSTR)

Return Value

none

Example

IDispProject.OutputDebugString  "some string"


Dispinterface IProject Refresh Method

Refresh Method

The Refresh method starts the refresh cycle on the project.

VBScript Syntax

IProject.Refresh

Parameters

none

Return Value

none

Remarks

When Refresh is invoked on a Project object, RefreshAll is then invoked on the top level Channel object's dispinterface. This sets off a recursive descent of RefreshAll invocations for all Channel objects defined in the object hierarchy. In each case, the Project object's dispinterface is propagated to all the Channel.RefreshAll methods. For the top level class Channel object only, the fTopLevel flag is set to 1 and the optional Schedule and LogTarget object's dispinterface specified by the Schedule and LogTarget properties are also passed to the Channel.RefreshAll method. These dispinterfaces, however, are not propagated recursively down the heirarchy.

Example

Set Project = CreateObject("Push.Project")
Project.Load("News Project")
call Project.Refresh()

See Also

IChannel RefreshAll Method


Dispinterface IProject Save Method

Save Method

The Save method saves a project with the name specified to disk.

VBScript Syntax

IProject.Save name

Parameters

name

an string specifying the name to save the project under. This can be a full file system path, a relative path, or just a name. (VT_BSTR)

Return Value

none

Remarks

If just a name is specified, the project is saved in the directory "c:\microsoft site server\data\pushcfg". Projects stored in this directory are returned by the Manager class's GetProjects method.

Example

' Using the Windows Scripting Host and VBScript
Set Project = CreateObject("Push.Project")
call Project.Save("c:\\Projects\\ProjectName")

See Also

IManager GetProjects Method


Dispinterface IProject SetLogtarget Method

SetLogTarget Method

The SetLogTarget method creates an instance of the LogTarget class, sets it's HREF property to the string passed as an argument, and then sets the LogTarget property to the new ILogTarget dispinterface.

VBScript Syntax

IProject.SetLogTarget URL

Parameters

URL

a string to set the created class LogTarget object's HREF property.

Return Value

The newly created class LogTarget object's dispinterface.

Remarks

If the Project object's LogTarget property holds a valid dispinterface address, it is passed to the GetCDFString method invoked on the top level channel object when the CDF string is build for the project. This results in a <LOGTARGET> element being included for the top level channel object.

Example

' Using the Windows Scripting Host and VBScript
Set Project = CreateObject("Push.Project")
Project.Load("News Project")
call Project.SetLogTarget("http://somecompany.com/logging")

See Also

GetCDFString Method

IChannel GetCDFString Method

Class LogTarget


Dispinterface IProject SetTask Method

SetTask Method

The SetTask method creates an instance of the Task class, sets it's properties to the values passed as arguments, and then sets the Task property to the new ITask dispinterface.

VBScript Syntax

IProject.SetTask AccountName [, Interval [, StartTime]]

Parameters

AccountName

a string specifying the account to use when running the refresh cycle. Default=""

Interval

an optional integer specifying the interval in minutes between successive refresh cycles. Default=1440. (once a day)

Start

an optional date value after which to start the task. Default=None.

Return Value

None

Example

' Using the Windows Scripting Host and VBScript
Set Project = CreateObject("Push.Project")
call Project.Load("News Project")
call Project.SetTask("ChannelUser",720)

See Also

Class Task


Dispinterface IProject WriteCDFFile Method

WriteCDFFile Method

The WriteCDFFile method generates and writes the CDF formatted string defined by the Project object to a specified file.

VBScript Syntax

IProject.WriteCDFFile [ Filename ]

Parameters

FileName

an optional string specifying the filename to write the CDF formatted text to. Default=None

Return Value

None

Remarks

If a string is passed as an argument, the CDFFilename property is overridden. If no argument is passed, and CDFFilename is defined, that name is used.

The CDF string is generated for the project using the GetCDFString method. The resulting output is sent to a file on disk.

Example

' Using the Windows Scripting Host (cscript.exe) and VBScript
Set Project = CreateObject("Push.Project")
call Project.WriteCDFFile("C:\channels\project1.cdf")

See Also

GetCDFString Method


Dispinterface IProject CDFEncoding Property

CDFEncoding Property

The CDFEncoding property is an optional string specifying the CDF encoding type.

Type

String (VT_BSTR)

Default

None

Remarks

This property is optional. If it is specified, use one of the currently defined encoding types, either "UCS-2" or "UTF-8". If this property is not set, no encoding type is explicitly defined in the CDF string. Clients usually default to "UTF-8".

Example

Set Project = CreateObject("Push.Project")
Project.CDFEncoding = "UCS-2"


Dispinterface IProject CDFFilename Property

CDFFilename Property

The CDFFilename property is a string specifying the CDF filename. This name can be a full file system path, a relative path, or just a name.

Type

String (VT_BSTR)

Default

None

Example

' Using the Windows Scripting Host and VBScript
CreateObject("Push.Project")
Project.CDFFilename = "c:\channels\project1.cdf"


Dispinterface IProject CDFURL Property

CDFURL Property

The CDFURL property is a string specifying the URL to the CDF file for the project.

Type

String (VT_BSTR)

Default

None

Example

Set Project = CreateObject("Push.Project")
Project.CDFURL="http://mycompany/channels/sports.cdf"


Dispinterface IProject Channel Property

Channel Property

The Channel property is an IChannel dispinterface. This is the top-level channel for the project.

Type

IChannel (VT_DISPATCH)

Remarks

A class Channel object is automatically created when the Project object is created, and its Channel property set to the new IChannel interface.

Example

' Using the Windows Scripting Host (cscript.exe) and VBScript
Set Project = CreateObject("Push.Project")
Set Channel = Project.Channel

See Also

Class Channel


Dispinterface IProject DistributionList Property

DistributionList Property

The DistributionList property is a string specifying the name of the Membership directory service email distribution list to associate with this project.

Type

String (VT_BSTR)

Default

None


Dispinterface IProject LogTarget Property

LogTarget Property

The LogTarget property holds an optional class ILogTarget dispinterface. If defined, this dispinterface is passed to the top level class Channel object when Refresh is invoked.

Type

ILogTarget (VT_DISPATCH)

Default

None

Example

Set LogTarget = CreateObject("Push.LogTarget")
Set Project = CreateObject("Push.Project")
Set Project.LogTarget = LogTarget

See Also

Class LogTarget

Channel GetCDFString


Dispinterface IProject Name Property

Name Property

The Name property is a string specifying the name of the project.

Type

String (VT_BSTR)

Default

None

Example

' Using the Windows Scripting Host (cscript.exe) and VBScript
Set Project = CreateObject("Push.Project")
Project.Name = "News Channel"


Dispinterface IProject Schedule Property

Schedule Property

The Schedule property is an optional ISchedule dispinterface on an Schedule object. If defined, this object is passed to the top level class Channel object when GetCDFString is invoked, adding a SCHEDULE element to it.

Type

ISchedule (VT_DISPATCH)

Default

None

Example

Set Schedule1 = CreateObject("Push.Shedule")
'  set up schedule information
Set Project = CreateObject("Push.Project")
Set Project.Schedule = Schedule1
' associated the object with the project

See Also

Class Channel

Channel GetCDFString

Class Schedule


Dispinterface IProject SelectionListPropName Property

SelectionListPropName Property

This property specifies the name of a directory property used to store a user's channel selections.

Type

String (VT_BSTR)

Default

None

Remarks

Indicate the directory property in the Membership directory schema defined for users that store their channel selections using this property. Each project that personalized CDF streams will be used for should have a separate property in the schema. The property must be defined in the schema for the user's data in the container specified by they default Active User Object (AUO) alias. For example, if the default alias defines the ADs path prefix "LDAP://someserver:1010/o=company/ou=members" and Schema "LDAP://someserver:1010/o=company/ou=admin/cn=schema/cn=Member" then that schema object should define a property that can be used to store channel selections. Currently, this should be a property of type "DirectoryString" (i.e. UnicodeString) and be multi-valued.

The upshot is that the channel selection list should be accessible via an instance of the Membership.UserObjects class (AUO) under the given IIS virtual server instance.

Example

Set Project = CreateObject("Push.Project")
Project.SelectionListPropName = "prj1ChannelSelectionList"
call Project.Save("Project1")

Within an ASP page, one should be able to do this:

<% Set IDispUserObjects = Server.CreateObject("Membership.UserObjects")
   Set IDispProject = CreateObject("Push.Project")
   IDispProject.Load "Project1"
   List = IDispProject.SelectionListPropName
   TheUsersList = IDispUserObjects.Get(List)
   ' now we have the list

The Active Channel Server feature provides a COM object that handles all of this internally called the CDFGenerator class. ( Push.CDFGenerator.1)

See Also

Class CDFGenerator

Class CDFGenHelper


Dispinterface IProject SelectionStylePropName Property

SelectionStylePropName

This property specifies the name of a directory property used to store a user's channel selection style.

Type

String (VT_BSTR)

Default

None

Remarks

The Membership directory service user property referred to by Project.SelectionListStyleName should have one of two valid values:

"0" = only include channels from project that are listed.
"1" = include all channels from project except those listed.

The same restrictions for SelectionListPropName apply to this property.

Example

Set Project = CreateObject("Push.Project")
Project.SelectionStylePropName = "IncludeExcludeFlag"

See Also

SelectionListPropName

Class CDFGenerator

Class CDFGenHelper


Dispinterface IProject Task Property

Task Property

The Task property holds an optional Task object's dispinterface. The Task object holds scheduling information for the project's refresh cycle.

Type

ITask (VT_DISPATCH)

Default

Null

Example

Set Task1 = CreateObject("Push.Task")
Set Project = CreateObject("Push.Project")
Set Project.Task = Task1

See Also

Class Task


Dispinterface IProject Logos Collection

Logos Collection

The Logos collection is an object of class Dictionary object intended to contain key/value pairs indexing Logo objects with a simple name. Child objects can uniquely identify the class Logo objects for inclusion of their CDF string by adding the key names to their respective LogoRefs collection. Case is ignored in mapping LogoRefs strings to Logos keys when the CDF string is generated.

Type

IDictionary (VT_DISPATCH)

Contains

Keys to associate Logo objects (any name desired, as long as it is unique)
The values are ILogo dispinterfaces on these Logo objects.

Default

Empty

Remarks

One can add Logo objects to the Logos collection using the AddLogo method, which creates, initializes, and attaches a Logo object, or you may do so explicitly.

If you attempt to do explicit compares of strings found in LogoRefs collections to the keys in this Dictionary object, make sure you do so in a case-insensitive manner as well. The keys in the Dictionary object are always converted to lower case, regardless of how the key was referred to during assignment.

Example

Set Logo1 = CreateObject("Push.Logo")
Set Project = CreateObject("Push.Project")
Set Project.Logos("Main Logo") = Logo1

See Also

Class Dictionary

LogoRefs Collection


CoClass Schedule (Push.Schedule.1)

Class Schedule

Programmatic Identifier: Push.Schedule.1

The Push.Schedule.1 COM class, hereafter referred to as the Schedule class, defines an Automation-compliant object that can be used to manage information used to build a SCHEDULE XML element, as defined by the Channel Definition Format (CDF) specification.

The Schedule class exposes a dispinterface to the methods listed below. Therefore, all invocations must proceed through the IDispatch interface.

Dispinterface ISchedule

Methods

Name | Description
AddElement | Adds a user-defined XML element to the object's Elements collection.
GetCDFString | Builds and returns the object's CDF string.

Properties

Name | Description
EarliestTime | Specifies a value for the EARLIESTTIME attribute.
EndDate | Specifies a value for the ENDDATE element.
IntervalTime | Specifies a value for the INTERVAL element.
StartDate | Specifies a value for the STARTDATE attribute.
LatestTime | Specifies a value for the LATESTTIME element.

Collections

Name | Description
Elements | The collection of user-defined XML elements.


Dispinterface ISchedule EarliestTime Property

EarliestTime Property

This property holds the value used to build an optional EARLIESTTIME CDF element. When the CDF string for the object is constructed, the property is checked. If it is not null, the <EARLIESTTIME> element is added to the string, with the value of the property as the element value.

Type

Integer (VT_I4)

Default

None

Example

' Using Windows Scripting Host (cscript.exe) and VBScript
Set Schedule = CreateObject("Push.Schedule")
Schedule.EarliestTime = 12
wscript.echo Schedule.GetCDFString()

outputs:

<SCHEDULE  TIMEZONE="-0800" >
<EARLIESTTIME MIN="12"/>
</SCHEDULE>


Dispinterface ISchedule EndDate Property

EndDate Property

This property holds the value used to build an optional ENDDATE attribute. When the CDF string for the object is constructed, the property is checked. If it is not null, the ENDDATE attribute is added to the string, with the value of the property.

Type

Date (VT_DATE)

Default

None

Example

' Using Windows Scripting Host (cscript.exe) and VBScript
Set Schedule = CreateObject("Push.Schedule")
Schedule.EndDate = #12/12/97#
wscript.echo Schedule.GetCDFString()

outputs:

<SCHEDULE ENDDATE "1997-12-12" TIMEZONE="-0800" >
</SCHEDULE>


Dispinterface ISchedule IntervalTime Property

IntervalTime Property

This property holds the value used to build an optional INTERVALTIME CDF element. When the CDF string for the object is constructed, the property is checked. If it is not null, the <INTERVALTIME> element is added to the string, with the value of the property as the element value.

Type

Integer (VT_I4)

Default

None

Remarks

The IntervalTime property is in units of minutes.

Example

' Using Windows Scripting Host and VBScript
Set Schedule = CreateObject("Push.Schedule")
Schedule.IntervalTime = 12
wscript.echo Schedule.GetCDFString()

outputs:

<SCHEDULE TIMEZONE="-0800">
<INTERVALTIME MIN="12"/>
</SCHEDULE>


Dispinterface ISchedule LatestTime Property

LatestTime Property

This property holds the value used to build an optional LATESTTIME CDF element. When the CDF string for the object is constructed, the property is checked. If it is not null, the <LATESTTIME> element is added to the string, with the value of the property as the element value.

Type

Integer (VT_I4)

Default

None

Remarks

The value set for LatestTime will be in units of minutes.

Example

' Using Windows Scripting Host and VBScript
Set Schedule = CreateObject("Push.Schedule")
Schedule.LatestTime = 12
wscript.echo Schedule.GetCDFString()

outputs:

<SCHEDULE  TIMEZONE="-0800">
<LATESTTIME MIN="12"/>
</SCHEDULE>


Dispinterface ISchedule StartDate Property

StartDate Property

This property holds the value used to build an optional STARTDATE attribute. When the CDF string for the object is constructed, the property is checked. If it is not null, the STARTDATE attribute is added to the string, with the value of the property.

Type

Date (VT_DATE)

Default

None

Example

' Using Windows Scripting Host and VBScript
Set Schedule = CreateObject("Push.Schedule")
Schedule.StartDate = #12/12/97#
wscript.echo Schedule.GetCDFString()

outputs:

<SCHEDULE STARTDATE "1997-12-12" TIMEZONE="-0800" >
</SCHEDULE>


CoClass SoftwarePackage (Push.SoftwarePackage.1)

Class SoftwarePackage

Programmatic Identifier: Push.SoftwarePackage.1

The Push.SoftwarePackage.1 class, hereafter referred to as the SoftwarePackage class, defines an object that can be used to manage information used to build a SOFTPKG XML element, as defined by the Open Software Description (OSD).

The SoftwarePackage class exposes a dispinterface to the methods listed below. Therefore, all invocations must proceed through the IDispatch interface.

Dispinterface ISoftwarePackage

Methods

Name | Description
AddDependency | Adds a dependency definition to the Dependencies collection.
AddElement | Adds a user-defined XML element to the Elements collection.
AddImplementation | Adds an Implementation object to the Implementations collection.
AddUsage | Adds a Usage object to the Usages collection.
GetCDFString | Builds and returns the CDF string defined by the object and all sub objects in collections.

Properties

Name | Description
Abstract | Holds a string value used to build the optional ABSTRACT element for the object's CDF string.
AutoInstall | Holds a string value used to build the AUTOINSTALL attribute for the object's CDF string.
DeleteOnInstall | Holds a string value used to build the DELETEONINTALL element for the object's CDF string.
DeleteOnRefresh | Specifies whether this object should be deleted by a parent Channel object when DeleteObjects is invoked.
DependentType | Holds a string value used to build the DEPENDENTTYPE element for the object's CDF string.
HREF | Holds a string value used to build the optional HREF attribute for the object's CDF string.
Name | Holds a string value used to build the optional NAME attribute for the object's CDF string.
Precache | Holds a string value used to build the optional PRECACHE attribute for the object's CDF string.
Style | Holds a string value used to build the optional SYTLE attribute for the object's CDF string.
Title | Holds a string value used to build the optional TITLE element for the object's CDF string.
Version | Holds a string value used to build the optional VERSION attribute for the object's CDF string.

Collections

Name | Description
Dependencies | A collection of dependency definitions.
Elements | A collection of user-defined XML elements.
Implementations | A collections of Implementation objects.
Languages | A collection of strings each specifying a language.
LogoRefs | A collection of Logo references to keys in a Project object's Logos collection.
Usages | A collection of Usage objects.


Dispinterface ISoftwarePackage AddDependency Method

AddDependency Method

The AddDependency method creates an instance of the Dictionary class. It then sets the new object's "type" key to the string passed as an argument to the method, adds the object's dispinterface to the Dependencies collection, and then returns it.

VBScript Syntax

ISoftwarePackage.AddDependency type

Parameters

type

A string specifying the value for the ACTION attribute of the <DEPENDENCY> element.

Return Value

The IDictionary interface on the Dictionary object defining the dependency added to the collection.

Example

SoftPkg.AddDependency "value"

See Also

Dependencies Collection

Class Dictionary


Dispinterface ISoftwarePackage AddImplementation Method

AddImplementation Method

The AddImplementation method creates an instance of the Implementation class, adds the object's dispinterface to the Implementations collection, and then returns it.

VBScript Syntax

ISoftwarePackage.AddImplementation

Parameters

None

Return Value

The IImplementation dispinterface on the new object added to the collection.

Example

Impl = Sofkpkg.AddImplementation
Impl.OS.Add "WinNT"
Impl.processors.Add "x86"

See Also

Class Implementation


Dispinterface ISoftwarePackage AutoInstall Method

AutoInstall Property

The AutoInstall property is a string used when building the <SOFTPKG></SOFTPKG> element upon invocation of the GetCDFString method. If this property is not empty, the AUTOINSTALL attribute is generated, and the string is inserted as its value.

Type

String (VT_BSTR)

Default

None

Example

Softpkg.AutoInstall = 1


Dispinterface ISoftwarePackage DeleteOnInstall Method

DeleteOnInstall Property

The DeleteOninstall property is a integer flag used when building the <SOFTPKG></SOFTPKG> element upon invocation of the GetCDFString method. If this property is 1, the <DELETEONINSTALL/> child element is generated.

Type

Integer (VT_I4)

Default

0 (false)

Example

Softpkg.DeleteOnInstall = 1


Dispinterface ISoftwarePackage DependentType Property

DependentType Property

This property, if defined, causes the construction of the <DEPENDENTTYPE VALUE="value"> child XML element upon invocation of the SoftPkg.GetCDFString method.

Type

String (VT_BSTR)

Default

None

Remarks

This type should be one of "ASSERT" or "INSTALL".

Example

SoftPkg.DependentType = "ASSERT"


Dispinterface ISoftwarePackage Name Property

Name Property

The Name property is a string used when building the <SOFTPKG></SOFTPKG> element upon invocation of the GetCDFString method. If this property is not empty, the NAME attribute is added to the element and the string is inserted as the value.

Type

String (VT_BSTR)

Default

None


Dispinterface ISoftwarePackage Style Property

Style Property

The Style property is a string used when building the <SOFTPKG></SOFTPKG> element upon invocation of the GetCDFString method. If this property is not empty, the STYLE attribute is added to the element and the string is inserted as the value.

Type

String

Default

None


Dispinterface ISoftwarePackage Version Property

Version Property

The Version property is a string used when building the <SOFTPKG></SOFTPKG> element upon invocation of the GetCDFString method. If this property is not empty, the VERSION attribute is added to the element, and the string is inserted as the value.

Type

String (VT_BSTR)

Default

None


Dispinterface ISoftwarePackage Dependencies Collection

Dependencies Collection

The Dependencies collection is a dispinterface on a class List object intended to contain class Dictionary object dispinterfaces. When the GetCDFString method is invoked on the object, each object in the collection is enumerated, and the key/value pairs used to build an XML element. Each element is then added to the object's CDF string.

Type

IList (VT_DISPATCH)

Contains

IDictionary (VT_DISPATCH)

Default

Empty

Example

For Each Dep in SoftPkg.Dependencies
  '  (code ommited)
Next

See Also

Class List

Class Dictionary


Dispinterface ISoftwarePackage Implementations Collection

Implementations Collection

This collection is a dispinterface on a class List object intended to contain IImplementation dispinterfaces. When the parent object’s CDF string is assembled, the GetCDFString method is invoked on each interface to fetch the object's CDF string contribution.

Type

IList (VT_DISPATCH)

Contains

IImplementation (VT_DISPATCH)

Default

Empty

Example

For Each Impl in SoftPkg.implementations
  '  each Impl returned is an Implementation object
  ' work with these objects (code ommitted)
Next

See Also

Class Implementation

Class List


CoClass Task (Push.Task.1)

Class Task

Programmatic Identifier: Push.Task.1

The Push.Task.1 COM class, hereafter referred to as the Task class, defines an Automation-compliant object that can be used to set up tasks with the Microsoft® Windows NT® Scheduled Tasks for the purpose of automatic refresh cycles of channel content. Once the task has been registered, Project.Refresh will be called in intervals specified within the object. The starting date can also be specified.

The Task class exposes a dispinterface to the methods listed below. Therefore, all invocations must proceed through the IDispatch interface.

Dispinterface ITask

Methods

Name | Description
Delete | Deletes a task from NT task scheduler.
IsScheduled | Returns whether the task defined by the object is scheduled with the Windows NT task scheduler.
Update | Adds or updates the task defined by the object with the Windows NT task scheduler.

Properties

Name | Description
Accountname | Holds the string specifying the account to use when setting the task with the Windows NT task scheduler.
Interval | Holds an integer value specifying the interval time between successive tasks In units of minutes.
ProjectName | Holds a string specifying the name of the project to refresh.
Start | Holds a date value specifying when the scheduled task should start.
TaskName | Holds a string specifying the name of the task. The task will appear in the Windows NT task scheduler under this name.


Dispinterface ITask Delete Method

Delete Method

The Delete method deletes the task from the task scheduler.

VBScript Syntax

ITask.Delete

Parameters

None

Return Value

None

Example

Set Task = Project.Task
Task.Delete


Dispinterface ITask IsScheduled Method

IsScheduled Method

The IsScheduled method returns true or false, depending on whether this task has been scheduled in the task scheduler.

VBScript Syntax

ITask.IsScheduled

Parameters

None

Return Value

Integer (true/false) (VT_I4) (false=0)

Example

VBScript

Set Task = Project.Task
If Task.IsScheduled Then
  …
Else
  call Task.Update("password")
End If


Dispinterface ITask Update Method

Update Method

The Update method updates or installs this task in the task scheduler.

VBScript Syntax

ITask.Update password

Parameters

password

The password for the account specified by the AccountName property.

Return Values

None

Remarks

The password supplied is used along with the AccountName property as credentials for access to the system's task scheduler.

Example

' VBScript
Set Project = CreateObject("Push.Project")
Set Task = CreateObject("Push.Task")
Task.AccountName = "Administrator"
Task.Interval = 4*60  ' every four hours, run the task.
Task.Start = #10/10/1997#   ' or whatever format is currently set
Task.ProjectName = "SomeProject"

Project.Load "SomeProject"
Set Project.Task = Task
Task.Update "admin-password"


Dispinterface ITask AccountName Property

AccountName Property

The AccountName property specifies the account credential used by the task scheduler to run the task. It is also used in conjunction with a password when tasks are scheduled.

Type

String (VT_BSTR)

Default

None

Example

VBScript

Set Task =  Project.Task
Task.Accountname="pushrefreshuser"


Dispinterface ITask Interval Property

Interval Property

The Interval property specifies how often the task will be run. The interval is in units of minutes.

Type

Integer (VT_I4)

Default

1440 (if set with SetTask)

Example

ITask.interval = 2000


Dispinterface ITask ProjectName Property

ProjectName Property

The ProjectName property specifies the name of the project the task runs for.

Type

String (VT_BSTR)

Default

None

Remarks

The ProjectName property should be the same as the Name property for the Project object.

Example

VBScript

Set Project = CreateObject("Push.Project.1")
Project.Name = "ProjectName"
Set Task = Project.SetTask("refreshUser",2880)
Task.ProjectName = "ProjectName"
call Task.Update("password")


Dispinterface ITask Start Property

Start Property

The Start property specifies when the task should start.

Type

Date (VT_DATE)

Default

None (immediate start with scheduler).

Example

Set Task = CreateObject("Push.Task")
Task.Start = #10/10/1998#
Task.AccountName = "someuser"
call Task.Update("password")


Dispinterface ITask TaskName Property

TaskName Property

The TaskName property specifies the name of this task as it appears in the Scheduled Tasks administration tools.

Type

String (VT_BSTR)

Default

None

Example

Set Task = CreateObject("Push.Task")
Task.TaskName = "Refresh for Project name"


CoClass Usage (Push.Usage.1)

Class Usage

Programmatic Identifier: Push.Usage.1

The Push.Usage.1 class, hereafter referred to as the Usage class, defines an object that can be used to manage information used to build a USAGE XML element as defined by the Channel Definition Format (CDF) specification.

The Usage class exposes a dispinterface to the methods listed below. Therefore, all invocations must proceed through the IDispatch interface.

Dispinterface IUsage

Methods

Name | Description
AddElement | Adds a user-defined XML element to the Elements collection
GetCDFString | Builds and returns the CDF string defined by the object.

Properties

Name | Description
Content | Holds an optional string, which will be inserted as the content of the object's CDF element.
Type | Holds an optional string value used to build the optional HREF attribute for the object's CDF string.

Collections

Name | Description
Elements | A collection of user-defined XML elements.


Dispinterface IUsage Content Property

Content Property

The Content property is a string used when building the <USAGE></USAGE> element upon invocation of the GetCDFString method. If this property is not empty, the string is inserted as the element's content.

Type

String

Default

None

Example

VBScript

Set IDispUsage = CreateObject("push.usage.1")
IDispUsage.Content = "content here"


Dispinterface IUsage Type Property

Type Property

The Type property is a string used when building the <USAGE></USAGE> element upon invocation of the GetCDFString method. If this property is not empty, the TYPE attribute is added to the element, and the string is inserted as the value.

Type

String

Default

None

Example

VBScript

Set IDispUsage = CreateObject("push.usage.1")
IDispUsage.Type = "screensaver"


Core Container Classes (Push)

Core Container Classes

Below is a brief description of various utility classes that are routinely used by Active Channel Server classes to organize information. Examples of use by Active Channel Server classes are listed as well. It should be noted that these objects are not true COM classes, but are native within the Active Channel Server COM classes. Consequently, they cannot be created independently of the various Push COM classes. However, dispinterfaces on each are returned by Push classes, so they act essentially like any other COM object.

The classes are listed below.

Class List

Class Dictionary


Class List (Dispinterface IList)

Class List

The List class stores a collection of variables, with each variable indexed by an integer. The items in the collection can be any valid VARIANT data subtype. It should be stressed that this class is not a SAFEARRAY. This class is also not a COM class, and as such cannot be created stand-alone. It is an intrinsic class used by the other Active Channel Server classes. Collections that are marked as class List are essentially just properties that return the address of an IDispatch interface that exposes the methods and properties of this class. The methods and properties of this dispinterface are listed below.

Dispinterface IList

The methods and properties of a List object are only accessible as a dispinterface. (via a standard IDispatch COM interface.)

Methods and Properties

Name | Return Type | Parameter
Count | Integer (VT_I4) | (property)
Item | VARIANT (VT_XXXX) | Integer index (VT_I4)
Add | void | VARIANT item (VT_XXXX)
Remove | void | Integer index (VT_I4)
_NewEnum | IEnumVariant* (VT_DISPATCH) | (property)

Synopsis

The Count property returns how many items are in the list.

The Item method returns an item from the list

The Add method adds an item to the list

The Remove method removes an item from the list

The _NewEnum property returns an IEnumVariant interface. This object can then be used to enumerate the items in the List collection. For most Automation compliant programming and scripting languages, enumeration of the collection is handled behind the scenes.

Examples

' Windows Scripting Host Runtime using VBScript

Set IDispChannel = CreateObject("push.channel")
Set IDispList = IDispChannel.Subchannels
Set IDispItem = CreateObject("push.item")
call IDispList.Add(IDispItem)

' delete objects with DeleteOnRefresh = TRUE
For i = 1 to IDispList.Count-1
  if IDispList.Item(i).DeleteOnRefresh then
    IDispList.Delete(i)
Next

The "things" in the collection can be enumerated automatically in the normal way:

for each item in IList
 …
next


Class Dictionary (Dispinterface IDictionary)

Class Dictionary

The Dictionary class stores a collection of variables, with each variable indexed by a string key. The variables in the collection can be any valid VARIANT data subtype. This class is also not a COM class, and as such cannot be created stand-alone. It is an intrinsic class used by the other Active Channel Server classes. Collections that are marked as class Dictionary are essentially just properties that return the address of an IDispatch interface that exposes the methods and properties of this class. The methods and properties of this dispinterface are listed below.

Dispinterface IDictionary

The methods and properties of a Dictionary object are only accessible via a standard IDispatch COM interface. The members are listed below.

Methods and Properties

Name | Return Type | Parameters
_NewEnum | IEnumVariant* (VT_DISPATCH) | (property)
Count | Integer (VT_I4) | (property)
Item | VT_XXXXX | String key (VT_BSTR)

Synopsis

The Count property returns how many key/value pairs are in the dictionary.

The Item method returns the value for the key in the dictionary. Because this method is marked with id(DISPID_VALUE), it is the default method called when none is specified.

The _NewEnum property returns an IEnumVariant interface used to enumerate the collection. In most high level languages and scripting languages, this property is never requested directly. In Visual Basic, this property is used when the For Each Item In (Collection) context is encountered.

Since the Item method is marked as [id(0)], it is the default method for the dispinterface. This allows for a nice short hand in languages that invoke methods through the dispinterface it that they need not specify the Item method by name.

Example

' assume we have a dictionary object called Dictionary
Dictionary.Item("favorite beethoven symphony") = "9th"
Dictionary("time")  = "11/12/97"
Dictionary("level") = 42
Set Dictionary("logo") = CreateObject("Push.Logo")
Set Dictionary("channela")    = CreateObject("Push.Channel")
' Note here that we can dispense with .Item since it is the
'  default method for the object.  See below

Note A key can be any string, number, or combination of both. However, case is ignored in the key:

Dictionary("This")
Dictionary("thIS")

Both of the above expressions refer to the same key, and thus the same associated value. If a key and value pair are added where the key passed has capital letters, these will be converted to the lower-case. Be careful with string comparisons that are case sensitive, such as against the strings stored in a LogoRefs collection.


Push CoClass Errors

Errors

The following table lists the errors that can be returned by Active Channel Server COM objects. They are packed into the EXCEPTINFO structure and returned via the disipinterface Invoke method.

The error 0x80400002 is generated during the execution of an agent script. The appropriate error message would be returned in the EXCEPTINFO structure.

These codes can be viewed in a script by using the intrinsic error object, such as Err in the Windows Scripting Hosts.

Code | Description Returned
0x80400001 | "Value is out of range"
0x80400002 | <an agent exception has occurred, description is propagated from the scripting host>
0x80400003 | “Unknown RefreshType assigned to channel.”
0x80400004 | “This project does not have a name.”
0x80400005 | “The CDF filename has not been provided.”

The other errors normally encountered during the execution of a script are listed below.

Error | Description
Internal Error | An error occurred during the call to the Invoke method. A parameter type or the number of parameters was incorrect.
VBScript Runtime Error | Syntax error in the script.

Below are examples given using the intrinsic Err dispinterface within a script. In the first example, no argument is passed to the Refresh method on the IChannel interface. This would generate a VBScript Runtime error.

In the second example, the Err dispinterface is checked for errors encountered during a valid refresh cycle.

On Error Resume Next
Set IProject = CreateObject("Push.Project")
Set IChannel = IProject.Channel
call IChannel.Refresh
If Err.Number <> 0 Then
  WScript.Echo "Error calling refresh!"
  WScript.Echo "Error Number: " & Err.Number
  WSCript.Echo "Error Description: " & Err.Description
End If

On Error Resume Next
Set IProject = CreateObject("Push.Project")
IProject.Refresh
If Err.Number <> 0 Then
     WScript.Echo "Error encountered during the refresh cycle:"
   WScript.Echo Err.Number
   WScript.Echo Err.Description
End If


Introduction

Welcome to the Personalization and Membership (P&M) Programmer's Guide. This guide contains information and examples that will help you start programming with the various parts of this feature. This guide is a part of the Site Server 3.0 Software Development Kit (SDK). For this feature, the kit includes the following parts:

Programmer's Guide

The programmer's guide contains overview information and examples of using the various parts of the P&M feature of Site Server 3.0.

Programmer's Reference

This reference contains information on the various COM classes used to interact with the P&M system. It also includes reference information required to configure the system

Samples

The kit comes with a set of samples that can be used to learn more about the P&M system.

In addition, the Programmer's Guide contains many examples of using the various COM classes.


Setting Up Your Programming Environment

Setting up your build environment to work with P&M depends primarily on the goals of your project. The general requirements for each programming language are listed below. For specific cases such as with examples or with one of the samples, any additional steps required are listed in that respective section.

  • C and C++

  • Visual Basic

  • Java

  • Scripting Languages (VBScript/JavaScript)

C/C++

Base Requirements

The recommended base requirements, meaning what just about everyone planning on using C or C++ to develop applications using Site Server 3.0 should have, are listed below:

  • Microsoft® Site Server 3.0 Product and all prerequisites for its installation.

  • Platform SDK core build environment

  • Platform SDK Windows base services

  • Platform SDK Network and Distributed Services

  • COM compliant Development Environment such Microsoft Visual C++ 5.0

P&M Specific Requirements

Programmers can get the interface declarations and UUIDs used to access the P&M COM objects in a couple of ways. The most straightforward way is to run the MIDL compiler on the IDL file that defines the interface and coclass desired. The SDK comes with the necessary IDL files to do this. A complete list of IDL files, type libraries, and their locations is given here.

If you are unfamiliar with this process, here's how to generate the necessary header files to access the ObjCreator COM object:

MIDL objcreator.idl

This would produce two necessary header files, objcreator.h and objcreator_i.c in the standard fashion. Include these files where appropriate. The .h file contains the interface definitions, and the .c file contains the UUID (GUID) definitions.

Java

If you plan on using Java to develop applications that interact with P&M, you should acquire the latest Java SDK-version 2.01. The J++ Java compiler that ships with DevStudio '97 has been superseded by the compiler. Many COM-related improvements exist in this latest SDK release, so it is well worth your time.

In order to access the COM objects exposed by P&M, you need to generate the necessary interface and COM Java classes. This is done using the Java SDK tool JActiveX, with the primary argument being the path to a type library containing the IDL information. For example, to generate the Java classes necessary to access the P&M administrative objects, you need the coclass ObjCreator and its interfaces translated to Java classes. First make sure you have the Java SDK bin directory defined in your PATH, and then run:

JActiveX c:\winnt\system32\objcreator.dll /d c:\myjavaclasses

This would create the class files in subdirectories of "c:\myjavaclasses" in the standard way. Make sure you specify the /d switch, or the classes will be placed below your TrustedLib directory.

Check here for a complete list of all type library locations for the COM objects used in P&M.

Visual Basic 5.0

Most of the P&M COM objects implement pure dual interfaces. Since all dual interfaces are intended to contain only oleautomation types, VB 5.0 can use the corresponding type library to bind to the COM interface directly. In order to access P&M COM objects through their COM interfaces, you need to add references (under Project/References) to each of the respective type libraries. If you plan on using just the IDispatch interfaces (using CreateObject to fetch interfaces on COM objects), no references are required.

So, for vtable binding:

add a reference to the appropriate type library

  1. Dim all variables that will hold interfaces on the objects as the appropriate type.

For example, when creating an instance of the AuoConfig admin COM object, you would first need to create an instance of the ObjCreator object, and bind to its IObjCreator COM interface. This would then be followed by the creation of an AuoConfig object with the IAuoConfig interface being returned by the ObjCreator object through the CreateObjAuth method. The steps in VB 5.0 for this would be:

  1. For ObjCreator: add the reference to the Site Server 3.0 Search Authentication Client Type Library 1.0

  2. For IAuoConfig: Add the reference to the AUO Type Library 1.0

  3. Dim the objects according to their target types as follows:

   Dim oObjCreator as ObjCreator   ' only works if Type Lib is referenced

   Set oObjCreator = new ObjCreator   ' instance, returns IObjCreator

   Dim oAuoConfig as AuoConfig

   Set oAuoConfig = oObjCreator.CreateObjAuth("MemAdmin.AuoConfig","")

'  go on to use the AuoConfig object

A complete list of the type libraries that can be used to reference type information for all P&M interfaces is available here.

Scripting Languages (Automation)

For automation enabled scripting languages such as VBScript and JavaScript, little extra information is needed to access the COM objects. In some cases, you may want to prepare a list of constant definitions with human readable names to make error identification easier.

In general, to access the functionality of COM Automation compliant objects, simply create the object using the syntax of the particular language:

VBScript using Windows Scripting Host (WSH) | Dim oObjCreator Dim oAuoConfig Set oObjCreator = CreateObject("objcreator.objcreator.1") Set oAuoConfig = oObjCreator.CreateObjAuth("MemAdmin.AuoConfig") ...
JScript using Windows Scripting Host (WSH) | var oObjCreator = new ActiveXObject("objcreator.objcreator.1"); var oAuoConfig = oObjCreator.CreateObjAuth("MemAdmin.AuoConfig.1");

Note that the ASP scripting context provides a separate set of intrinsic objects and nothing more.


Overview

The P&M feature SDK can be broken down into the following broad categories:

The P&M COM Classes

The P&M feature provides a set of COM/Automation compliant classes. Instances of these classes fall into two categories: front-end ASP server-side COM objects, and administrative COM objects. There are a number of examples demonstrating the use of these objects in various programming languages.

Samples

This SDK comes with two complete programming samples. The first sample demonstrates how to customize a client DPA login screen to specify a particular realm. The second is a client/server example that demonstrates how to go about using the Windows NT Security Support Provider Interface (SSPI) in conjunction with the P&M Membership Authentication server.


The P&M COM Classes

The COM Classes

The Personalization and Membership feature provides an extensive set of COM/Automation compliant classes that allow interaction with the system. A list of the classes along with a brief description of each appears below.

The Active User Object (AUO)

The UserObjects Class (Membership.UserObjects)

This class is at the heart of the Active User Object (AUO) system. Programmers and scripters can use instances of this class to automatically and painlessly access directory service information for users in an ASP or other environment.

The SchemaObjects Class (Membership.SchemaObjects)

This class is part of the Active User Object (AUO) system. Programmers and scripters can use objects of this class to view and/or modify the directory service schema definitions for users.

The AuoConfig Class (MemAdmin.AuoConfig)

This class is the administrative tool used to configure the Active User Object (AUO) system. Administrators can use objects of this class to set up the AUO system so that instances of the UserObjects and SchemaObjects classes will function.

Membership Server Front End Class

The VerifUsr Class (Membership.Verifusr)

This class can be used for a variety of tasks in an ASP environment. It can be used to issue appropriate HTTP cookies to users that are required by Membership server instances, as well as provide authentication services for web sites that are using Forms Authentication.

The GuidGen Class (Membership.GuidGen)

This class provides access to the low-level COM library CoCreateGuid function. This class allows script writers to generate GUID values in scripts at runtime.

Administrative Classes

The BrokServers Class (MemAdmin.BrokServers)

Objects of this class can be used to configure Membership virtual server instances.

The BrokConfig Class (MemAdmin.BrokConfig)

Objects of this class can be used to configure specific instances of the Membership virtual server.

The LdapCfg Class (MemAdmin.LdapConfig)

Objects of this class can be used to configure instances of the Lightweight Directory Access Protocol (LDAP) server instances.

The TMAdmin Class (MemAdmin.DMailConfig)

Objects of this class can be used to configure various instances of the Direct Mail instances.

The SetupStore Class (MemAdmin.DSConfig)

Objects of this class can be used to setup backend database information used by LDAP server instances to persist directory information.


P&M Examples

Examples

The following sections demonstrate using the various COM classes provided by the Personalization and Membership feature. Most of the examples can be found within the various tools that come with the product. These include various ASP page examples, the Design-Time Controls, (and supporting VBScript routines) as well as the command-line administration tool pmadmin.vbs.


Working with the Active User Object (AUO)

Working with the Active User Objects (AUO)

The Active User Objects (AUO) are a set of COM classes (objects) that greatly simplify working with directory database data that is accessible through Active Directory Services COM objects. The Active User Objects have coclass logical names UserObjects, SchemaObjects, and AuoConfig. The UserObjects and SchemaObjects coclasses provide the "front-end" services that programmers and scripters can use to automatically access directory information about Membership users with a minimum of hassle. Administrators can use the AuoConfig coclass to configure desired AUO providers, and less-privileged accounts can use it to view the unrestricted information that makes up these provider configurations.

The AUO relies on other COM objects to provide the raw connectivity to various directory services, databases or other data sources. At an absolute minimum, these COM objects must implement the core Active Directory Service COM Interfaces (ADSI) with logical names IADs and IADsContainer. It is through these generic interfaces that these objects provide basic storage/retrieval functionality and hierarchic structuring of data to the client application. Of course, these interfaces allow complete polymorphism on the part of the implementation, in effect hiding all of the "details" of how data is actually gathered or organized from the client application. The Microsoft Site Server 3.0 product comes with a generic set of COM objects that provide standard connectivity to a variety of data services. These include the Lightweight Directory Access Protocol v3 compliant databases (LDAP), the WinNT core directory services (WinNT), and the Internet Information Server (IIS) meta-base (IIS). A quick look in the proper registry location [HKLM\Software\Microsoft\ADs\Providers] in fact lists all the currently installed and available Active Directory Service (ADs) providers.

The examples that follow make use of the following coclasses:

The UserObjects Class (Membership.UserObjects)

The AuoConfig Class (MemAdmin.AuoConfig)

The BrokServers Class

ADSI Namespace Classes (covered in the ADSI 2.0 documentation)


Configuring the AUO

The following code examples demonstrate how to configure the Active User Object (AUO) system for our new Membership Server instance. In this case, we will configure both the default provider as well as add another named provider with the name "Other."

C++

This example demonstrates the process of creating and using the AuoConfig coclass in a C++ program. This class and associated COM interfaces are defined within the IDL file auo.idl.

Create the project directory for the C++ source code. The header files and GUID definitions are required, so we run the MIDL compiler on an appropriate interface definition language (IDL) file. One can either copy the file auo.idl from the \include directory of the SDK into the project directory, or use the OleView.exe application to bind to the type library and list the IDL definition. In the latter case, simply bind to the type library, which is located within the dynamic link library c:\microsoft site server\bin\p&m\auo.dll. Once bound, click on the type library node in the tree. Select all the IDL text in the right pane and paste it into your favorite text editor. Save the text into a file named auo.idl. We now run the MIDL compiler with this file as the argument. This generates the necessary files:

auo.h

auo_i.c

auo.tlb

If you run MIDL on the auo.idl file that accompanies the SDK, two other files would be generated:

auo_p.c

dlldata.c

These files are used to build a proxy dynamic link library that could be used to marshal data to and from an instance of the object. Since the desired interfaces are marked with the dual attribute, the oleautomation attribute is implied. Thus, the automation library can handle all marshalling duties using the type library within the AUO.DLL, and these files can therefore be ignored and/or discarded.

Scripting Languages Example

VBScript and Windows Scripting Host

The following code demonstrates a standard configuration for the AUO system. The important methods are highlighted.

Set IObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set IAuoConfig = IObjCreator.CreateObjAuth("MemAdmin.AuoConfig")

'  configure Membership virtual server that is mapped to IIS virtual server 3
Set IBrokServers = IObjCreator.CreateObjAuth("MemAdmin.BrokServers")
call IBrokServers.MappedTo("W3SVC",3,MemId,MemComment)

'  MemId now has the Membership virtual server instance ID
wscript.echo "Configuring Membership Server named: " & MemComment

IBrokServers = Nothing '  release interface ref
IAuoConfig.GetInfo(MemId)

Name = "LDAP2"
AdsPathPrefix = "LDAP://server:1000/o=company/ou=members"
Class = "member"
Schema = "LDAP://server:1000/o=company/ou=admin/cn=schema/cn=member"
Suffix = 1 '  registered user names used for this instance
' this is the DN of the directory user and password to use when binding
' to all ADSI objects from this DS.
BindAsName = "o=company/ou=membersh/cn=administrator"
BindAsPassword = "password"

Call IAuoConfig.SetEntry(Name,
                     AdsPathPrefix,
                     Class,
                     Schema,
                     Suffix,
                     "",   ' DepObject; not used here
                     "",   ' DepProp;  not used here
                     BindAsUsername,
                     BindAsPassword )
IAuoConfig.SetInfo
Set IAuoConfig = Nothing   ' release interface ref

Here's an ASP example that will list the Names (aliases) and Namespace (providers) for the AUO for a given Membership virtual server instance.

ASP and VBScript

<%
Set IObjCreator = Server.CreateObject("ObjCreator.ObjCreator.1")
Set IAuoConfig = IObjCreator.CreateObjAuth("MemAdmin.AuoConfig")

'  configure Membership virtual server that is mapped to IIS virtual server 3
Set IBrokServers = IObjCreator.CreateObjAuth("MemAdmin.BrokServers")
call IBrokServers.MappedTo("W3SVC",3,MemId,MemComment)

IAuoConfig.GetInfo MemId
IAuoConfig.GetEntries names,namespaces

Response.Write "The AUO entries for Membership Server " & MemId & "<br>"
Response.Write "Server Name: " & MemComment & "<br><br>"

For I = LBound(names) to UBound(names)
  if names(I) = "" Then
   names(I) = "Default"
  end if
  Response.write "Name: " & names(I) & "<br>"
  Response.write "Namespace: " & namespaces(I) & "<br><br>"
Next
%>


Accessing the New User's Attributes

Accessing a User's Attributes

This section now demonstrates how to access a user's attributes. We have configured the AUO system with a necessary default AUO provider so we can use the UserObjects and SchemaObjects coclasses to create objects that can be used to easily access this information.

C++

C and C++ programmers can use the P&M COM classes in the standard way. A file containing the interface definitions (IDL) is included with the SDK. One can elect to run the MIDL compiler on these IDL files and generate the necessary header files and GUID definitions, or simply "import" the IDL file into a project in the standard way.

Example

This example demonstrates the process of creating and using the UserObjects coclass in a C++ program. This class and its COM interfaces are defined within the IDL file auo.idl. The step-by-step procedure is given below.

Create the project directory for the C++ source code. The header files and GUID definitions are required, so we run the MIDL compiler on an appropriate interface definition language (IDL) file. One can either copy the file auo.idl from the \include directory of the SDK into the project directory, or use the OleView.exe application to bind to the type library and list the IDL definition. In the latter case, simply bind to the type library, which is located within the dynamic link library c:\microsoft site server\bin\p&m\auo.dll. Once bound, click on the type library node in the tree. Select all the IDL text in the right pane and paste it into your favorite text editor. Save the text into a file named auo.idl. We now run the MIDL compiler with this file as the argument. This generates the necessary files:

auo.h

auo_i.c

auo.tlb

If you run MIDL on the auo.idl file that accompanies the SDK, two other files would be generated:

auo_p.c

dlldata.c

These files are used to build a proxy dynamic link library that could be used to marshal data to and from an instance of the object. Since the desired interfaces are marked with the dual attribute, the oleautomation attribute is implied. Thus, the automation library can handle all marshalling duties using the type library within the AUO.DLL, and these files can therefore be ignored and/or discarded.

The UserObjects coclass has multiple COM interfaces exposed, and among these are the Active Directory Service Interfaces (ADSI) IADs and IADsContainer. In order to provide forward declarations of these, we must either include the appropriate header files or use the type library to generate them. We'll use the include file that comes with the Platform SDK as it contains declarations for the low-level functions that might come in handy. The actual type library that will be used to provide marshalling information for the Automation system depends on the namespace we use to access directory information. For the LDAP namespace, the type library information for these interfaces is located in the dynamic link library: c:\mircosoft site server\bin\Commerce.dll. If you are unfamiliar with the ADSI system, see the documentation in the Platform SDK under Network and Distributed Systems.

The file we will use is located in the directory <PlatformSDK_Install_Dir>\include\iads.h. If you do not have the Network and Distributed Services portion of the Platform SDK, this file will not be present. In this case, you can either download this portion from the Microsoft Developers Network (http://www.microsoft.com/msdn) or build an IDL file using the type library information and the OleView application.

Now that we have all the necessary declarations and GUIDs defined, we can proceed to use the UserObjects coclass in a program. The example below is a simple program that will fetch some properties from the directory service.

This example ignores all runtime exceptions for the sake of brevity.

#include "iostream.h"
#include "auo.h"
#include "auo_c.h"
#include "iads.h"

int main() {
  CoInitialize(NULL);
  IUserObjects* pIUserObj = NULL;

  HRESULT hR = CoCreateInstance(
               CLSID_UserObjects,
               NULL,
               CLSCTX_ALL,
               IID_IUserObjects,
               (PVOID*)&pIUserObj
               );

                     // we have the interface to the UserObjects object
                     // we now initialize the object
  BSTR bszUserName = ::SysAllocString("JohnS");
  BSTR lIISInstanceId = ::SysAllocString(L"1");

  hR = pIUserObj->Init( lIISInstanceId, bszUserName ) ;

                     // We now fetch the IADs interface on
                     // the object
  IADs* pIAds = NULL;
  hR = pIUserObj->QueryInterface( IID_IADS, (void**)&pIADs ) ;

                     // we don’t need the IUserObjects interface anymore
  hR = pIUserObj->Release();

                     // Now say we want to fetch the GUID property
                     //  of the object
  BSTR bszObjGUID = 0;
  hR = pIADs->get_GUID( &bszObjGuid ) ;

                     // for simplicy, convert the BSTR to char
  char AdsPath[100];
  extern OLECHAR wszGUID[];
  wcscpy(wszGUID,bszObjGUID);
  SysFreeString(bszObjGUID);

  wsctombs(AdsPath,wszGuid);
  cout << "The ADsPath is: %s\n",AdsPath) ;

Java

In order to use Java to access the various COM objects provided by the P&M feature, the necessary classes need to be defined and imported into the source code. To do this, run the JactiveX tool which will generate the necessary .java files. You can specify either the .idl file or the type library. For example: JactiveX "c:\microsoft site server\bin\p&m\auo.dll" /d C:\myclasses. One then imports these classes into source code using the import directive.

It is highly recommended that you install the latest Microsoft Java SDK, Version 2.01 and use only the classes and tools provided in that release. The low-level COM support from earlier Java releases can cause byte-compile and runtime errors.

Example

File: MyClass.java

import auo.*;
import com.ms.com.Variant;
 class MyClass {
  public static void main( String args[] ) {
   IUserObjects pIUserObjects = (IUserObjects) new UserObjects();
 }
}

Visual Basic 5.0

One can use low-level COM interface binding in Visual Basic 5.0 by adding the appropriate type library into the references in the project. The names of the type libraries are listed in the reference section for each COM class. Alternately, one can use late-binding via the dispinterfaces for each object. In this case, no type information is required before run-time.

Example

Vtable (early) binding: (IUserObjects)

Dim IUserObjects as UserObjects
Set IUserObjects = New UserObjects

or do late binding: (IDispatch)

Dim IUserObjects as Object
Set IUserObjects = CreateObject("Membership.UserObjects")

The first example requires the reference to the type library and will do compile-time type checking. The second example proceeds directory through the IDispatch interface and type mismatch errors can only by found at runtime.

Visual Basic, Scripting Edition (VBScript)

VBScript does only late binding through the IDispatch interface, so one can access the services of the classes by creating and instance and calling methods on the dispinterface is the standard way.

Using VBScript requires some sort of Active Scripting Host, such as the Active Server Pages (ASP) or the Windows Scripting Host (WSH). Of course, any Active Scripting Host that can load the appropriate VBScript parsing engine will do.

Example

Set IUserObjects = CreateObject("Membership.UserObjects")
Call IUserObjects.Init(1,"JohnS")

One could then run the script in an ASP page or with the Windows Scripting Host using a command such as: cscript myscript.vbs.

In this case, the appropriate scripting engine is identified by the extension on the file name.

JavaScript

JavaScript also does only late binding through the dispinterfaces. An example is shoen below.

Example

var IUserObj = new ActiveXObject("Membership.UserObjects");
var arg1 = 1;
var arg2 = "JohnS";
IUserObj.Init(arg1,arg2);

One could then run the script in an ASP page or with the Windows Scripting Host using a command such as: cscript myscript.js.

In this case, the appropriate scripting engine is identified by the extension on the file name: .js loads the JavaScript engine.


Setting a User's Attributes

The following example demonstrates how to go about adding information about a user into a directory service in an ASP script. This example will demonstrate working with both single and multi-value attributes.

Example 1

The first example updates a user's attribute in the directory service specified by the default AUO entry. For this example, assume the schema definition for "objects" of type "member" has an attribute called "FavoriteColor." Assume further that the default AUO provider has the named value Class equal to "member" and the appropriate ADsPathPrefix named value contains a valid ADSI path prefix to a container "object" of objects of class "member." One could then proceed as follows:

<%
   ' Create the UserObjects object.  We use the built-in Server "object"
   ' or dispinterface to create the object.  This automatically
   ' innitializes the UserObjects object with the IIS server instance
   ' and the requesting user's username

   Set IUserObjects = Server.CreateObject("Membership.UserObjects")

   ' set the target attribute name
   Attribute1 = "FavoriteColors"

   ' Here we build an array of values to be put in a multivalue attribute
   dim usArray
   usArray = Array("blue","green","voilet","orange")

   ' define these ADSI related values here so they have "English"
   ' descriptions
   const ADS_PROP_ERASE = 1
   const ADS_PROP_UPDATE = 2
   const ADS_PROP_APPEND = 3


(Untitled)

   '  Update the attribute for the current user
   IUserObject.PutEx ADS_PROP_UPDATE, Attribute1, (usArray)
%>

One could use the Put method here instead of PutEx. Most ADSI implementations allow setting multi-value attributes with Put. However, more functionality is exposed for the PutEx method such as erasing as well as appending data to the user's attribute. It simply requires one extra argument.


Samples

This SDK comes with two samples. The source code for each can be found in the <sdk-install-root>\Samples\Microsoft Site Server\PM\ directory of the SDK. The samples are listed below.

Included Samples

Custom DPA Login User Interface

This sample demonstrates how one can build custom login interfaces identifying different realms when using Distributed Password Authentication (DPA).

Sample Client/Server

This sample demonstrates how one could use the Membership Authentication server as a Security Support Provider Interface (SSPI) package to authenticate clients.

Other Examples

Examples of using the various COM Classes can be found in many places in the product. Two great resources for examples of use are listed below.

pmadmin.vbs

This file resides in the c:\microsoft site server\bin\P&M directory on a system with Site Server installed. This tool has many examples using the various administrative COM classes to configure the P&M system

dtclib.inc

Another good place to look is in the Design Time Control (DTC) "include" file called dtclib.inc. This file is included in pages that use the DTCs and define a set of stock methods used by them. The functionality includes adding and retrieving properties for users as well as common things such as migration of anonymous cookie users to a fully registered account.


Custom DPA Login User Interface

The Customui sample allows you to customize the Sign In user interface for each Realm by changing the bitmap that is used to brand the user interface, and by changing the text that appears on each screen. This Sign In user interface only appears when you select DPA as your authorization protocol and Membership security as your security for the system.

Each Membership System service provider can upload a customized resource DLL to client computers for each Realm it contains. The client will then be presented with a custom login dialog for the realm when authentication is required.

The source can be found in the directory <sdk install root>\Samples\Microsoft Site Server\PM\customui\


Sample Client/Server

The ICPServ and ICPclnt samples demonstrate how the SSPI can be used to authenticate a client with a server running on a system with P&M installed. The source can be found at <sdk install root>\Samples\Microsoft Site Server\PM\Security\ICPProject\


CoClass AuoConfig (MemAdmin.AuoConfig.1)

Class AuoConfig

This COM class defines an object that programmers and administrators can use to configure the Active User Object (AUO) entries for a given Membership virtual server instance.

COM Class Identification

The following values identify this COM class. These values are set in the registry when the Site Server 3.0 product is installed.

Programmatic Identifier

MemAdmin.AuoConfig.1

CLSID

0b9ae1d6-b696-11d0-bbd7-00c04fb615e5

COM Class Name

AuoConfig

Type Information

The complete Interface Definition Language (IDL) definition of this class is contained in the file <sdk_install_root>\include\AUO.idl. Run the MIDL compiler to generate include files for C/C++. Include the AUO.h and AUO_i.c to have the interface definitions, CLSID, IID and their associated GUID values made available to your application at compile time.

The type library for this class is available as a resource in the auo.dll dynamic link library (DLL). The location of this DLL is c:\microsoft site server\bin\p&m\auo.dll.

COM Class IDL Definition

[
   uuid(0b9ae1d6-b696-11d0-bbd7-00c04fb615e5),
   helpstring("AuoConfig Class")
]
coclass AuoConfig
{
   [default] interface IAuoConfig;
};

Creating Instances of this Class

Programmers must use the special COM class ObjCreator.ObjCreator.1 to create instances of this class.

When an instance of the AuoConfig class is created, it is registered with the context CLSCTX_LOCAL_SERVER. Thus, do not attempt to create an instance of the class with type CLSCTX_INPROC_SERVER as the CoGetClassObject call will fail.

Interfaces

The AuoConfig COM class exposes the IAuoConfig dual interface, providing both a custom COM interface as well as a dispinterface to the methods and properties.

Security Issues

Most methods exposed by the IAuoConfig interface require the process or thread invoking them to have NT administrator credentials. The exceptions are listed below

  • The GetInfo method does not require this credential.

  • The GetEntries method does not require this credential.

  • The GetEntry method will not return the AUO entry's BindAsPassword if the account invoking the method does not have NT administrator credentials. If it does, all the entry data will be returned.

Interface IAuoConfig

IDL Defintion

[
   object,
   uuid(4b928606-b685-11d0-bbd7-00c04fb615e5),
   dual,
   pointer_default(unique)
]
interface IAuoConfig : IDispatch
{
   HRESULT GetInfo( LONG lVirtServId );
   HRESULT SetInfo();
   HRESULT SetEntry(   [in] BSTR bszName,
                       [in] BSTR bszADsPathPrefix,
                       [in] BSTR bszSchema,
                       [in] BSTR bszClass,
                       [in] LONG lSuffix,
                       [in] BSTR bszDepObject,
                       [in] BSTR bszDepProp,
                       [in] BSTR bszBindAsName,
                       [in] BSTR bszBindAsPassword
                     );

   HRESULT GetEntry(   [in] BSTR bszName,
                       [in,out] VARIANT *pbszADsPathPrefix,
                       [in,out] VARIANT *pbszSchema,
                       [in,out] VARIANT *pbszClass,
                       [in,out] VARIANT *plSuffix,
                       [in,out] VARIANT *pbszDepObject,
                       [in,out] VARIANT *pbszDepProp,
                       [in,out] VARIANT *pbszBindAsName,
                     [in,out] VARIANT *pbszBindAsPassword
                     );

   HRESULT RemoveEntry([in]BSTR bszName);

   HRESULT GetEntries(
                     [in,out] VARIANT *pNames,   // VT_ARRAY|VT_VARIANT
                     [in,out]VARIANT *pProviders // VT_ARRAY_VT_VARIANT
                      );

   HRESULT DeleteInstance();
};


Interface IAuoConfig DeleteInstance Method

DeleteInstance Method

This method clears all entries defined for the specified Membership virtual server instance.

IDL Definition

HRESULT DeleteInstance();

Return Value

a standard HRESULT value

Remarks

You must have previously called GetInfo and specified a Membership virtual server instance. If GetInfo has not been called, an error is returned.

This method only clears the entries within the AuoConfig object. Call SetInfo to commit the changes.

The process or thread invoking this method must have NT administrative credentials associated with it for the method to succeed.

Example

' Using Windows Scripting Host and VBScript
Option Explicit

' First the AuoConfig object gets instantiated
' using the special creator object
Dim ObjCreator
Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")

Dim AuoConfig
set AuoConfig = Obj.Creator.CreateObjAuth("MemAdmin.AuoConfig.1")

' get the entries for Membership Instance ID = 1
AuoConfig.GetInfo(1)

'  Say we wish to redefine all the entries for this ID
'  We call DeleteInstance to remove all the current entries

AuoConfig.DeleteInstance()


Interface IAuoConfig GetEntries Method

GetEntries Method

GetEntries retrieves AUO entry names and their associated ADSI namespaces (also called Providers). The namespace is determined from the ADsPathPrefix value defined for each entry.

IDL Definition

HRESULT GetEntries(
[in,out] VARIANT* pNames,
[in,out] VARIANT* pNamespaces
) ;

Parameters

pNames

upon return, the VARIANT subtype SAFEARRAY contains VARIANT subtype BSTR variables that are the AUO entry names defined for the current Membership virtual server instance. (VT_ARRAY|VT_VARIANT)

pNamespaces

upon return, the VARIANT subtype SAFEARRAY contains VARIANT subtype BSTR variables each of which contains the namespace portion of the ADsPathPrefix for the associated AUO entry. (VT_ARRAY|VT_VARIANT)

Return Value

a standard HRESULT value

Remarks

The names and namespaces are associated by index in the arrays. For example, the array elements Names(1) and Namespaces(1) (using VB syntax) represent an AUO name/namespace association.

You must have previously called GetInfo and specified a Membership server instance. If GetInfo has not been called, this method will return an error.

The returned variant type discriminator is of type VT_ARRAY|VT_VARIANT. Each VARIANT variable in the array has the discriminator type VT_BSTR.

Example

' Using Windows Scripting Host and VBScript
Option Explicit

'  Here we wish to fetch all the entry names and their
'  associated providers  for Membership Instance 1

' First the AuoConfig object gets instantiated
' using the special creator object
Dim ObjCreator
Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")

Dim AuoConfig
set AuoConfig = Obj.Creator.CreateObjAuth("MemAdmin.AuoConfig.1")

'  Call Getinfo for ID = 1
call AuoConfigObjRef.GetInfo ( 1 )

'  Now get a list of the defined entries
Dim Names
Dim ADSProv
call AuoconfigObj.GetEntries( Names, NameSpaces )

'  We'd now have an array of names and providers for ID = 1
Dim i
For i = LBound(Names) to UBound(Names)
  wscript.echo "Name: " & Names(i)
  wscript.echo "Namespace: " & NameSpaces(i)
Next


Interface IAuoConfig GetEntry Method

GetEntry Method

The GetEntry method gets the configuration information for the specified entry.

IDL Definition

HRESULT GetEntry(
[in]        BSTR  bszName,        /* the entry to get elements for */
[in,out] VARIANT* pbszADsPathPrefix, //VT_BSTR
[in,out] VARIANT* pbszSchema,        //VT_BSTR
[in,out] VARIANT* pbszClass,         //VT_BSTR
[in,out] VARIANT* plSuffix,          //VT_LONG
[in,out] VARIANT* pbszDepObject,     //VT_BSTR
[in,out] VARIANT* pbszDepProp,       //VT_BSTR
[in,out] VARIANT* pbszBindAsName,    //VT_BSTR
[in,out] VARIANT* pbszBindAsPassword //VT_BSTR
) ;

Parameters

bszName

specifies the name of the entry to get configuration information for.

pbszADsPathPrefix

upon return, the VARIANT subtype BSTR (VT_BSTR) variable contains the current ADsPathPrefix value for the specified entry.

pbszSchema

upon return, the VARIANT subtype BSTR (VT_BSTR) variable contains the current Schema value for the specified entry.

pbszClass

upon return, the VARIANT subtype BSTR (VT_BSTR) variable contains the current Class value for the specified entry.

plSuffix

upon return, the VARIANT subtype LONG (VT_I4) variable contains the current Suffix value for the specified entry.

pbszDepObject

upon return, the VARIANT subtype BSTR (VT_BSTR) variable contains the current DepObject value for the specified entry.

pbszDepProp

upon return, the VARIANT subtype BSTR (VT_BSTR) variable contains the current DepProp value for the specified entry.

pbszBindAsName

upon return, the VARIANT subtype BSTR (VT_BSTR) variable contains the current BindAsName value for the specified entry.

pbszBindAsPassword

upon return, the VARIANT subtype BSTR (VT_BSTR) variable contains the current BindAsPassword value for the specified entry.

Return Value

a standard HRESULT value

Remarks

Set bszName to NULL to retrieve information about the default entry.

You must have previously called GetInfo and specified a Membership virtual server instance. If GetInfo has not been called, this method will return an error.

The process invoking this method should have NT administrative credentials associates with it. If it does not, the method will still succeed, but the pbszBindAsPassword will not be populated with the AUO entry's BindAsPassword value.

Example

' Using Windows Scripting Host and VBScript
'
Option Explicit

' First the AuoConfig object gets instantiated
' using the special creator object
Dim ObjCreator
Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")

Dim AuoConfig
set AuoConfig = Obj.Creator.CreateObjAuth("MemAdmin.AuoConfig.1")

' Call GetInfo
AuoConfigObjRef.GetInfo(1)
' We want the list of currently defined entries and their providers

Dim Name, Path, Schema, Class, Suffix,DepObj,DepProp,BindAsName,BindAsPassword

Name = ""  ' default entry
AuoConfigObjRef.GetEntry(Name,Path,Schema,Class,Suffix,
DepObj,DepProp,BindAsName,BindAsPassword)


Interface IAuoConfig GetInfo Method

GetInfo Method

GetInfo fetches the AUO entries defined for a specified Membership virtual server instance.

IDL Definition

HRESULT GetInfo( [in] LONG lVirtServId  );

Parameters

lVirtServId

a Membership virtual server instance identifier (id).

Return Value

a standard HRESULT value

Remarks

GetInfo is the first method you call when you want to view and/or update the AUO entries for a specified Membership virtual server instance. GetInfo will "succeed" even if the integer "ID" has not been defined. In this case, one may proceed to define the entries for this new Membership virtual server instance.

Example

' Using Windows Scripting Host and VBscript
Option Explicit

' First the AuoConfig object gets instantiated
' using the special creator object
Dim ObjCreator
Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")

Dim AuoConfig
set AuoConfig = Obj.Creator.CreateObjAuth("MemAdmin.AuoConfig.1")

' now we want to work with Membership Instance 7, which has previously
'  been defined

call AuoConfig.GetInfo(7)
' here we view, update the entries.
AuoConfig.SetInfo   ' commits the changes for ID=7

' Now we wish to define a new Membership Instance #8
call AuoConfig.GetInfo(8)
' here we define the new entries  (code omitted)
AuoConfig.SetInfo     ' commits the entries for ID=8


Interface IAuoConfig RemoveEntry Method

RemoveEntry Method

The RemoveEntry method deletes a specified entry from the configuration.

IDL Definition

HRESULT RemoveEntry( [in] BSTR  bszName ) ;

Parameter

bszName

the name of the AUO entry to remove

Return Value

a standard HRESULT value

Remarks

You must have previously called GetInfo and specified a Membership virtual server instance. If GetInfo has not been called, this method will return an error.

This method only deletes the entry in the object. To permanently commit the changes for the virtual server instance, invoke the SetInfo method.

The process or thread invoking this method must have NT administrative credentials associated with it for the method to succeed.

Example

' Using Windows Scripting Host and VBScript
Option Explicit

' First the AuoConfig object gets instantiated
' using the special creator object
Dim ObjCreator
Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")

Dim AuoConfig
set AuoConfig = Obj.Creator.CreateObjAuth("MemAdmin.AuoConfig.1")
'  Work with Membership Instance 3
AuoConfigObjRef.GetInfo(3)

' now we want to remove an entry in the AuoConfig object
' Say the entry with friendly name "ThisOne"
AuoConfigObjRef.RemoveEntry("ThisOne")


Interface IAuoConfig SetEntry Method

SetEntry Method

SetEntry creates or updates the specified AUO entry.

IDL Definition

HRESULT SetEntry(
[in] BSTR bszName,
[in] BSTR bszADsPathPrefix,
[in] BSTR bszSchema,
[in] BSTR bszClass,
[in] LONG lSuffix,
[in] BSTR bszDepObject,
[in] BSTR bszDepProp,
[in] BSTR bszBindAsName,
[in] BSTR bszBindAsPassword
);

Parameter

bszName

the name of the entry.

pbszADsPathPrefix

the ADsPathPrefix value for the entry.

pbszSchema

the Schema value for the entry.

pbszClass

the Class value for the entry.

plSuffix

the Suffix value for the entry. (1=username;2=dependent property;3=cookie)

pbszDepObject

the DepObject value for the entry. (an AUO entry name)

pbszDepProp

the DepProp value for the entry.

pbszBindAsName

the BindAsName value for the entry.

pbszBindAsPassword

the BindAsPassword value for the entry.

Return Value

a standard HRESULT value

Remarks

SetEntry puts an entry in the AuoConfig object with the specified name. If an entry with the specified name does not exist in the object, SetEntry creates a new one.

You must have previously called GetInfo and specified a Membership virtual server instance. If GetInfo has not been called, this method will return an error.

The process or thread invoking this method must have NT administrative credentials associated with it for the method to succeed.

Example

' Using Windows Scripting Host Runtime Env  (cscript.exe)
Option Explicit

' First the AuoConfig object gets instantiated
' using the special creator object
Dim ObjCreator
Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")

Dim AuoConfig
set AuoConfig = Obj.Creator.CreateObjAuth("MemAdmin.AuoConfig.1")

' We want to work with Membership Instance 1
AuoConfig.GetInfo(1)

Dim Name, Path, Schema, Class, Suffix
Name = ""   ' default entry
Path = "LDAP://ldapsvr1:389/o=somecompany/ou=members"
Schema = "LDAP://ldapsvr1:389/o=somecompany/cn=schema/cn=member"
Class = "member"
Suffix = "1"
AuoConfig.SetEntry(Name,Path,Schema,Class,Suffix, "","","","")


Interface IAuoConfig SetInfo Method

SetInfo Method

The Setinfo method commits (saves) the current configuration as defined in the object.

IDL Definition

HRESULT SetInfo() ;

Return Value

a standard HRESULT value

Remarks

You must have previously called GetInfo and specified a Membership virtual server instance. If GetInfo has not been called, this method will return an error.

This method must be used with care. When SetInfo is invoked, all changes, deletions and additions to AUO entries that have occurs during the lifetime of this object will be committed. This method essentially "saves" the entries as they appear in the AuoConfig object.

The process or thread invoking this method must have NT administrative credentials associated with it for the method to succeed.

Example

' Using Windows Scripting Host and VBScript
Option Explicit

' First the AuoConfig object gets instantiated
' using the special creator object
Dim ObjCreator
Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")

Dim AuoConfig
set AuoConfig = Obj.Creator.CreateObjAuth("MemAdmin.AuoConfig.1")

AuoConfig.Getinfo(1)

' change or define some entries here
'  < code ommited >
'  Now we commit these changes so they take effect
AuoConfig.SetInfo()


P&M General Error Values

Errors

The table below lists the HRESULT return values that are returned by the AuoConfig object.

Value | Meaning
S_OK | Success
E_OUTOFMEMORY | Insufficient memory for allocation
E_FAIL | A critical operation failed
E_EXCEPTION | An exception has occurred
DISP_E_EXCEPTION | An exception has occurred. Check the ErrorInfo object for more detailed information

Some classes support the ErrorInfo object. For a DISP_E_EXCEPTION HRESULT, one can call GetErrorInfo to retrieve a more verbose description of the exception from the object.


CoClass BrokConfig (MemAdmin.BrokConfig.1)

Class BrokConfig

This COM class defines an object that administrators can use to configure Membership virtual server instances.

COM Class Identification

The following values can be used to identify this COM class. These values are set in the registry when the Site Server 3.0 product is installed.

Programmatic Identifier

MemAdmin.BrokConfig.1

CLSID

c78fa6e6-c4ac-11d0-bbda-00c04fb615e5

COM Class Name

BrokConfig

Type Information

The complete Interface Definition Language (IDL) definition of this class is contained in the file <sdk_install_root>\include\Brokcfg.idl. Run the MIDL compiler to generate include files for C/C++. Include the Brokcfg.h and Brokcfg_i.c to have the interface definitions, CLSID, IID and their associated GUID values made available to your application at compile time.

The type library for this class is available as a resource in the auo.dll dynamic link library (DLL). The default location of this DLL is c:\microsoft site server\bin\p&m\brokcfg.dll.

IDL Definition

Creating Instances of this Class

Programmers must use the special COM class with programmatic identifier ObjCreator.ObjCreator.1 to create an instance of this class using the CreateObjAuth method. Direct creation of the class will render all methods inoperable.

Interfaces

The BrokConfig COM class exposes the dual custom COM interface IBrokConfig. The methods and properties are accessible through the COM interface IBrokConfig, or through the dispinterface IBrokConfig. (through a standard IDispatch interface)

Security Issues

The process/thread invoking methods on the IBrokConfig interface must have the NT administrator credentials if the method is to succeed.

Interface IBrokConfig

[

object,

uuid(19edab12-c4a4-11d0-bbda-00c04fb615e5),

dual,

pointer_default(unique)

]

interface IBrokConfig : IDispatch

{

[hidden]

HRESULT LoadDefaults(LONG lVirtServId);

HRESULT GetConfig(LONG lVirtServId);

HRESULT SetConfig();

HRESULT CheckAcct(BSTR bszDomain, BSTR bszName, BSTR bszPassword);

PROPERTY_RW(LONG, lVirtServId, 1);

PROPERTY_RW(BOOL, bLocal, 2);

PROPERTY_RW(BSTR, bszServerName, 3);

PROPERTY_RW(LONG, lPort, 4);

PROPERTY_RW(BOOL, bSecure, 5);

PROPERTY_RW(LONG, lSecurePort, 6);

PROPERTY_RW(LONG, lTimeLimit, 7);

PROPERTY_RW(LONG, lSizeLimit, 8);

PROPERTY_RW(BSTR, bszBaseDN, 9);

PROPERTY_RW(LONG, lCacheTimeout, 10);

PROPERTY_RW(BSTR, bszGroupPrefix, 11);

PROPERTY_RW(BOOL, bCreateGroups, 12);

PROPERTY_RW(BSTR, bszDomain, 13);

PROPERTY_RW(BSTR, bszDsName, 14);

PROPERTY_RW(BSTR, bszDsPwd, 15);

PROPERTY_RW(BSTR, bszProxyName, 16);

PROPERTY_RW(BSTR, bszProxyPwd, 17);

PROPERTY_RW(BSTR, bszProxyDomain, 21);

PROPERTY_RW(BOOL, bUseTrackCookie, 18);

PROPERTY_RW(LONG, lPwdCookieTimeout, 19);

PROPERTY_RW(BOOL, bEnabled, 20);

PROPERTY_RW(BSTR, bszComment, 22);

PROPERTY_RW(BOOL, bPwdCookiePersist, 23);

PROPERTY_RW(BSTR, bszRealm, 24);

PROPERTY_RW(LONG, lTokenCacheTimeout, 25);

PROPERTY_RW(BSTR, bszTokenCreatorDll, 26);

[propget, id(27)] HRESULT bDirty([out, retval] BOOL * pRetVal);

};


Interface IBrokConfig CheckAcct Method

CheckAcct Method

This method verifies the account credentials specified have NT administrative privileges.

IDL Definition

HRESULT CheckAcct(BSTR bszDomain, BSTR bszName, BSTR bszPassword);

Parameters

bszDomain

The domain of the account.

bszName

The name of the account.

bszPassword

The password of the account.

Return Value

a standard HRESULT value.

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1")
call BrokConfig.CheckAcct("domain","username","password")


Interface IBrokConfig LoadDefaults Method

LoadDefaults Method

The LoadDefaults method resets the configuration information for the specified Membership virtual server instance with default settings. The changes only affect the information stored in the object. To commit the changes, invoke SetConfig.

IDL Definition

HRESULT LoadDefaults ( LONG lvirtserverID ) ;

Parameters

lvirtserverID

The Membership virtual server instance ID.

Return Values

A standard HRESULT value.

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1")
BrokConfig.GetInfo 1
BrokConfig.LoadDefaults 1  'reset the server to default settings
BronConfig.SetConfig


Interface IBrokConfig GetConfig Method

GetConfig Method

The GetConfig method initializes the object with configuration settings for a specified Membership virtual server instance.

IDL Definition

HRESULT GetConfig ( LONG lvirtserverID ) ;

Parameters

lvirtserverID

The Membership virtual server instance ID.

Return Values

A standard HRESULT value.

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1")
BrokConfig.GetConfig 1


Interface IBrokConfig SetConfig Method

SetConfig Method

The SetConfig method commits the changes to the configuration settings for a specified Membership virtual server instance.

IDL Definition

HRESULT SetConfig() ;

Return Values

A standard HRESULT value.

Remarks

Call SetConfig to persist the changes made with the BrokConfig object.

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth ("MemAdmin.BrokConfig.1")
BrokConfig.GetConfig 1
'  change config for instance(code ommited)
BrokConfig.SetConfig


Interface IBrokConfig lVirtServId Property

lVirtServId Property

The lVirtServId property is the Membership Virtual server instance identifier. This property is read-only and is always the same as the integer passed to the GetConfig method.

Type

LONG

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1")
BrokConfig.GetConfig 1
'  do some things with this instance
'  echo instance
WScript.Echo "Server Instance " & BrokConfig.lVirtServId


Interface IBrokConfig bLocal Property

bLocal Property

The bLocal property specifies whether the LDAP server hosting the directory service for this instance of the Membership virtual server is local. Set bLocal to FALSE to specify the name of the server and the TCP/IP port. This property defaults to FALSE.

Type

BOOL

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1")
BrokConfig.GetConfig 1
BrokConfig.bLocal = FALSE
' go on to configure


Interface IBrokConfig bszServerName Property

bszServerName Property

The bszHostName property specifies the host name of the remote machine on which the LDAP server is running. This property is used only if bLocal is set to FALSE. Any valid DNS name can be used here. This property defaults to "localhost".

Type

BSTR

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1")
BrokConfig.GetConfig 1
BrokConfig.bLocal=0
BrokConfig.bszServerName="localhost"


Interface IBrokConfig lPort Property

lPort Property

The lPort property specifies the port number the LDAP server is running on. This property is used to bind the TCP/IP socket with the LDAP server instance if bSecure is FALSE and bLocal is false. This property defaults to 389.

Type

LONG

Example

BrokConfig.lPort = 389


Interface IBrokConfig bSecure Property

bSecure Property

The bSecure property specifies whether the Membership virtual server instance should bind a TCP/IP socket with the remote LDAP server instance that has the Secure Sockets Layer (SSL) protocol enabled. Set to TRUE to use the SSL port. If TRUE, the lSecurePort value will be used when binding the socket. This property is used only if bLocal is set to FALSE.

Type

BOOL

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1") BrokConfig.GetConfig 1
BrokConfig.bSecure = TRUE
BrokConfig.lSecurePort=443
BrokConfig.SetConfig


Interface IBrokConfig lSecurePort Property

lSecurePort Property

The lSecurePort property specifies the port number for the LDAP service instance that is running with the Secure Sockets Layer (SSL) protocol enabled. This property is used in conjunction with the bszServerName property when binding the TCP/IP socket between the Membership virtual server instance and the remote LDAP server instance. The lSecurePort port number is used if bSecure is set to TRUE and bLocal is set to FALSE.

Type

LONG

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1")
BrokConfig.GetConfig 1
BrokConfig.bSecure=1
BrokConfig.lSecurePort = 443
BrokConfig.SetConfig


Interface IBrokConfig lTimeLimit Property

lTimeLimit Property

The lTimeLimit property specifies how long the Membership virtual server instance will wait for a response from the LDAP server after a search query has been made. This property is set in units of seconds.

Type

LONG

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1")
BrokConfig.GetConfig 1
BrokConfig.lTimeLimit = 60
BrokConfig.SetConfig


Interface IBrokConfig lSizeLimit Property

lSizeLimit Property

The lSizeLimit property specifies how large, in bytes, the results of an LDAP search query can be.

Type

LONG

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1")
BrokConfig.GetConfig 1
BrokConfig.lSizeLimit = 2048 ' 2 KB max result set size
'  …
BrokConfig.SetConfig


Interface IBrokConfig bszBaseDN Property

bszBaseDN Property

The bszBaseDN property specifies the base Distinguished Name (DN) for the Membership directory service. This is an X.500 name in ascending order. (e.g. "ou=members") This DN is used as a prefix when fetching data from the directory service.

Type

BSTR

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1")
BrokConfig.GetConfig 1
BrokConfig.bszBaseDN="ou=members"
BrokConfig.SetConfig


Interface IBrokConfig lCacheTimout Property

lCacheTimeout Property

The lCacheTimeout property specifies how long user properties will remain in the Membership virtual server instance without a retrieval request before being purged. This property is in units of seconds. Note that this timeout period resets after each request for the user's properties by an instance of the UserObjects object.

Type

LONG

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1")
BrokConfig.GetConfig 1
BrokConfig.lCacheTimeout = 120
BrokConfig.SetConfig


Interface IBrokConfig bszGroupPrefix Property

bszGroupPrefix Property

The bszGroupPrefix property is a string attached to the beginning of all Membership group names when mapping these groups to Windows NT groups. In order to avoid name clashes, it is a good idea to relate the prefix to the Membership virtual server instance identifier.

Type

BSTR

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1") BrokConfig.GetConfig 1
BrokConfig.bszGroupPrefix = "MemInstGrp1"
BrokConfig.SetConfig


Interface IBrokConfig bCreateGroups Property

bCreateGroups Property

The bCreateGroups property is a true/false flag specifying whether the Membership virtual server instance should attempt to create NT groups that do not exist within the domain for the purposes of mapping Membership groups to NT groups. Set bCreateGroups to TRUE to have the Membership virtual server instance create groups.

Type

BOOL

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1") BrokConfig.GetConfig 1
BrokConfig.bCreateGroups = TRUE
BrokConfig.SetConfig


Interface IBrokConfig bszDomain Property

bszDomain Property

The bszDomain property specifies an optional NT domain to use when mapping Membership groups to NT groups. If bszDomain is defined, the NT groups are assumed to reside in this domain.

Type

BSTR

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1") BrokConfig.GetConfig 1
BrokConfig.bszDomain = "SomeDomain"
BrokConfig.SetConfig


Interface IBrokConfig bszDsName Property

bszDsName Property

The bszDsName is the full distinguished name (DN) of the user account the Membership virtual server instance will use to authenticate itself to the LDAP server. This is an X.500 name.

Type

BSTR

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1") BrokConfig.GetConfig 1
BrokConfig.bszDsName = "/o=somecompany/ou=members/cn=Administrator"
' using LDAP
BrokConfig.SetConfig


Interface IBrokConfig bszDsPwd Property

bszDsPwd Property

This write-only property is the password presented when the Membership server instance authenticates itself to the LDAP directory service.

Type

BSTR

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1") BrokConfig.GetConfig 1
BrokConfig.bszDsPwd = "thepassword"
BrokConfig.SetConfig


Interface IBrokConfig bszProxyName Property

bszProxyName Property

The bszProxyName property specifies the Windows NT account name to use as a proxy account for the Membership virtual server instance.

Type

BSTR

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1") BrokConfig.GetConfig 1
BrokConfig.bszProxyName = "MembershipProxyUser"
BrokConfig.SetConfig


Interface IBrokConfig bszProxyPwd Property

bszProxyPwd Property

The bszProxyPwd property specifies the password that accompanies the username specified by the bszProxyName property.

Type

BSTR

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1") BrokConfig.GetConfig 1
BrokConfig.bszProxyPwd = "somepassword"
BrokConfig.SetConfig


Interface IBrokConfig bszProxyDomain Property

bszProxyDomain Property

The bszProxyDomain property specifies an optional NT domain for the bszProxyName account.

Type

BSTR

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1") BrokConfig.GetConfig 1
BrokConfig.bszProxyDomain = "somedomain"
BrokConfig.SetConfig


Interface IBrokConfig bUseTrackCookie Property

bUseTrackCookie Property

This property specifies whether the Membership virtual server instance should issue tracking cookies. Set this property to TRUE to issue tracking cookies. This property defaults to FALSE.

Type

BOOL

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1") BrokConfig.GetConfig 1
BrokConfig.bUseTrackCookie = TRUE
BrokConfig.SetConfig


Interface IBrokConfig lPwdCookieTimout Property

lPwdCookieTimeout Property

This property specifies how long the authentication cookies issued to clients by the server instance remain valid before a new login is required. The timeout is in minutes since the last received client request. This property value is used if "cookie authentication" is set for this instance.

Type

LONG

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1") BrokConfig.GetConfig 1
BrokConfig.lPwdCookieTimeout = 5
BrokConfig.SetConfig


Interface IBrokConfig bEnabled Property

bEnabled Property

The bEnabled property is a boolean flag specifying whether this instance of a Membership virtual server will provide authentication services using the Membership directory database. Set to FALSE to disable authentication. This property defaults to TRUE. If set to FALSE, the NTLM system will provide authentication services to clients.

Type

BOOL

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1") BrokConfig.GetConfig 1
BrokConfig.bEnabled = FALSE
BrokConfig.SetConfig


Interface IBrokConfig bszComment Property

bszComment Property

The bszComment property specifies a name to associate with this instance of a Membership virtual server. For example, this name appears as the instance name on the Microsoft Management Console. It is a good idea to specify the type of authentication the server supports, if any, in this name.

Type

BSTR

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1") BrokConfig.GetConfig 1
BrokConfig.bszComment = "Intranet Membership Instance #1 (NT Authentication)"
BrokConfig.SetConfig


Interface IBrokConfig bPwdCookiePersist Property

bPwdCookiePersist Property

This property defines whether the Membership server instance should persist authentication (password) cookies. This property defaults to TRUE. This property is only used if "cookie authentication" is set for this instance.

Type

BOOL

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1") BrokConfig.GetConfig 1
BrokConfig.bPwdCookiePersist = TRUE
BrokConfig.SetConfig


Interface IBrokConfig bszRealm Property

bszRealm Property

The bszRealm property optionally specifies the directory service realm to associate with this instance of the Membership virtual server.

Type

BSTR

Example

LdapCfg.Realm = “MyCompanyA”


Interface IBrokConfig lTokenCacheTimeout Property

lTokenCacheTimeout Property

This property specifies how long a Membership virtual server instance that is configured to handle authentication will cache the security tokens issued on behalf of clients. This property is in units of minutes.

Type

LONG

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1") BrokConfig.GetConfig 1
BrokConfig.lTokenCacheTimeout = 12 ' 12 minutes before new token 'generated
BrokConfig.SetConfig


Interface IBrokConfig bszTokenCreatorDll Property

bszTokenCreatorDll Property

This property specifies the dynamic link library that a Membership virtual server instance that is configured to handle authentication will use to generate security tokens for clients.

Type

BSTR

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokConfig = ObjCreator.CreateObjAuth("MemAdmin.BrokConfig.1") BrokConfig.GetConfig 1
BrokConfig.bszTokenCreatorDll = "c:\mydlls\tokencreator.dll"
BrokConfig.SetConfig


CoClass BrokServers (MemAdmin.BrokServers)

Class BrokServers

The BrokServers COM class defines an object that can be used to configure information relating to Membership virtual server instances. This includes the mappings to services, IIS meta-base information, and authentication types.

COM Class Identification

The following values can be used to identify this COM class. These values are set in the registry when the Site Server 3.0 product is installed.

Programmatic Identifier

MemAdmin.BrokServers.1

CLSID

cd8f114e-c4ac-11d0-bbda-00c04fb615e5

COM Class Name

Brokservers

Creating Instances of this Class

Programmers must use the special COM class ObjCreator.ObjCreator.1 to create instances of this class. Directly creating instances will render all methods inoperable.

Interfaces

The BrokConfig COM class exposes the IBrokServers dual interface, exposing both a custom COM interface and a dispinterface to its properties and methods.

Security Issues

The account invoking methods on an instance of this class must have NT administrative privileges.


Interface IBrokServers ClearMapping Method

ClearMapping Method

The ClearMapping method clears a mapping of a Membership virtual server instance to a specified service. (e.g. "W3SVC")

IDL Definition

HRESULT ClearMapping(
BSTR bszServiceName,
LONG lVirtServId
);

Parameters

bszServiceName

The name of the service to "un-map" from the Membership virtual server instance.

lvirtServId

The Membership virtual server instance identifier to "un-map" from the service bszServiceName.

Return Values

A standard HRESULT value

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokServers = ObjCreator.CreateObjAuth("MemAdmin.BrokServers.1")
BrokServers.CleapMapping "W3SVC" , "1"


Interface IBrokServers CreateServer Method

CreateServer Method

The CreateServer method creates a Membership virtual server instance.

IDL Definition

HRESULT CreateServer([out] VARIANT* plVirtServId);

Parameters

plVirtServId

on return, the address of a VT_I4 variable containing the new Membership virtual server instance identifier.

Return Values

A standard HRESULT value

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokServers = ObjCreator.CreateObjAuth("MemAdmin.BrokServers.1")
BrokServers.CreateServer InstanceID
WScript.Echo "New Instance: " & InstanceID


Interface IBrokServers DeleteServer Method

DeleteServer Method

The DeleteServer method deletes the membership virtual server instance.

IDL Definition

HRESULT DeleteServer(LONG lVirtServId);

Parameters

lVirtServId

The Membership virtual server instance identifier of the instance to delete.

Return Values

A standard HRESULT value

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokServers = ObjCreator.CreateObjAuth("MemAdmin.BrokServers.1")
BrokServers.DeleteInstance "3"


Interface IBrokServers GetAuthTypes Method

GetAuthTypes Methods

The GetAuthTypes method returns an integer specifying the allowed authentication methods for the specified IIS meta-base path.

IDL Definition

HRESULT GetAuthTypes(
BSTR bszPath,
[out, retval] LONG *plTypes
);

Parameters

bszPath

the URL to get the authentication type for

plTypes

on return, the address of a LONG variable containing the integer specifying the allowed authentication types. The integer is a bit-wise "OR" of the allowed types listed above.

Return Values

a standard HRESULT value

Remarks

The integer is composed of an "OR" bit-mask of the values listed below. (e.g. val | val2 | val3 ). The bits, all being powers of "2", are listed below in their base 10 integer equivalents.

Authentication Method | Integer value
Anonymous | 1
PwdCookie | 2
Basic | 4
DPA | 8

The following definitions are available through the type library when using C/C++:

const LONG BROK_AUTH_TYPE_ANON =           0x0001;
const LONG BROK_AUTH_TYPE_PWDCOOKIE =      0x0002;
const LONG BROK_AUTH_TYPE_BASIC =          0x0004;
const LONG BROK_AUTH_TYPE_DPA =            0x0008;

Example

Path = "/LM/W3SVC/3/ROOT/dir1"
Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set MemServers = ObjCreator.CreateObjAuth("MemAdmin.BrokServers.1")
call MemServers.GetAuthTypes(Path,ltypes)
if ltypes And 1 Then
  wscript.echo "Anonymous allowed"
Else if ltypes And 2 Then
  wscript.echo "PwdCookie allowed"
Else If ltypes And 4 Then
  wscript.echo "Basic allowed"
Else if ltypes And 8 Then
  wscript.echo "DPA allowed"
End If


Interface IBrokServers GetSecurityMode Method

GetSecurityMode Method

The GetSecurityMode method returns a BOOL specifying whether NT authentication is the configured mode for the service instance. TRUE means that NTLM is set to handle authentication and credentials issuance. FALSE means that a Site Server Authentication server instance is set to handle authentication and credentials issuance.

IDL Definition

HRESULT GetSecurityMode(
BSTR bszServiceName,
LONG lVirtServId,
[out, retval] BOOL *pbNTSecurity
);

Parameters

bszServiceName

the name of the service.

lVirtServId

the virtual server instance identifier

pbNTSecurity

on return, the address of a BOOL variable. The value is TRUE if NT authentication is set for this service's instance. FALSE means Membership Authentication is set for this service's instance.

Return Value

a standard HRESULT value

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set MemServers = ObjCreator.CreateObjAuth("MemAdmin.BrokServers.1")
call MemServers.GetSecurityMode("W3SVC",1,fIsNTMode)
If fIsNTMode Then
  wscript.echo "IIS Instance 1: NTLM for auth"
Else
  wscript.echo "IIS instance 1: Site Server Auth"
End If


Interface IBrokServers GetServers Method

GetServers Method

The GetServers method returns a list of all currently defined Membership virtual server instances and their associates names.

IDL Definition

HRESULT GetServers(
[in,out] VARIANT* plVirtServIds,
[in,out] VARIANT* pComments
);

Parameters

plVirtServIds

on return, a SAFEARRAY of LONG variables holding Membership virtual server instance identifiers.

pComments

on return, a SAFEARRAY of BSTR variables holding Membership virtual server instance names

Return Values

A standard HRESULT value

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokServers = ObjCreator.CreateObjAuth("MemAdmin.BrokServers.1")

call BrokServers.GetServers(Ids, Names)
For i = LBound(Ids) to UBound(Ids)
 wscript.echo Ids(i)
 wscript.echo Names(i)
Next


Interface IBrokServers HasNTAdminPrivilege Method

HasNTAdminPrivilege Method

The HasNTAdminPrivilege method succeeds if the current user has NT administrative privileges on the local machine. It fails otherwise.

IDL Definition

HRESULT HasNTAdminPrivilege();

Return Values

A standard HRESULT value

Example

On Error Resume Next
Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokServers = ObjCreator.CreateObjAuth("MemAdmin.BrokServers.1")
'  Check error number to see if it succeeded
if Err.Number <> 0 Then
  wscript.echo "Error:  Account does not have proper credentials"
End If


Interface IBrokServers HasWritePrivilege Method

HasWritePrivilege Method

The HasWritePrivilege method succeeds if the current user has the privileges to update configuration settings.

IDL Definition

HRESULT HasWritePrivilege();

Return Values

A standard HRESULT value

Example

On Error Resume Next
Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokServers = ObjCreator.CreateObjAuth("MemAdmin.BrokServers.1")
BrokServers.HasWritePrivilege
'  Check error number to see if it succeeded
if Err.Number <> 0 Then
  wscript.echo "Error:  Account does not have proper credentials"
End If


Interface IBrokServers MappedTo Method

MappedTo Method

This method returns the Membership virtual server identifier mapped to specified service instance.

IDL Definition

HRESULT MappedTo(
BSTR bszServiceName,
LONG lVirtServInstId,
[in,out] VARIANT* plVirtMemInstId,
[in,out] VARIANT* pbszComment
);

Parameters

bszServiceName

The service name to find mapping for.

lVirtServInstId

The virtual server ID for the service specified by bszServiceName.

plVirtMemInstId

Upon return, a VT_I4 variable containing the corresponding Membership virtual server instance identifier.

pbszComment

Upon return, a VT_BSTR variable containing the Membership virtual server instance name.

Return Values

A standard HRESULT value

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokServers = ObjCreator.CreateObjAuth("MemAdmin.BrokServers.1")

BrokServers.MappedTo "W3SVC",1, MemVirtId, MemVirtName
wscript.echo "World Wide Web Service Virtual Server ID =1 mapped to "
wscript.echo MemVirtName & " which is virtual server ID = " & MemVirtId


Interface IBrokServers MapToBroker Method

MapToBroker Method

The MapToBroker method maps a specified instance of some service to a Membership virtual server instance.

IDL Definition

HRESULT MapToBroker(
[in] BSTR bszServiceName,
[in] LONG lVirtServInstId,
[in] LONG lvirtMemInstId
);

Parameters

bszServiceName

The service to map.

lVirtServInstId

The virtual server ID for the service to map to a Membership virtual server instance.

lVirtMemInstId

The Membership virtual server ID to map the above service's virtual server instance.

Return Values

A standard HRESULT value

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokServers = ObjCreator.CreateObjAuth("MemAdmin.BrokServers.1")

BrokServers.MapToBroker "W3SVC", 1, 2
' this maps IIS instance 1 to Mem instance 2


Interface IBrokServers SetAuthTypes Method

SetAuthTypes Method

The SetAuthTypes method sets the authentication type for a specified IIS meta-base URL.

IDL Definition

HRESULT SetAuthTypes(BSTR bszPath, LONG lTypes);

Parameters

bszPath

the IIS meta-base path to set the authentication type for.

lTypes

the types to set.

Return Value

a standard HRESULT value

Remarks

In C++, the const values listed below can be used to create the value to send the object in the lTypes parameter. The can be combined in the standard bitwise "OR" to represent multiple types. In higher level languages, one can pass the sum instead.

The typedef values found in the type library are listed below.

const LONG BROK_AUTH_TYPE_ANON =           0x0001;
const LONG BROK_AUTH_TYPE_PWDCOOKIE =      0x0002;
const LONG BROK_AUTH_TYPE_BASIC =          0x0004;
const LONG BROK_AUTH_TYPE_DPA =            0x0008;

This information updates the IIS meta-base.

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokServers = ObjCreator.CreateObjAuth("MemAdmin.BrokServers.1")

tbasic = 4
tAnon = 1
ltypes = tbasic + tAnon
' this works because the values are bitwise, so no carrying is
'  required.
Path = "/LM/W3SVC/2/ROOT/dir1/dir2"
BrokServers.SetAuthTypes (Path,ltypes)


Interface IBrokServers StartServer Method

StartServer Method

The StartServer method starts a specified instance of a Membership virtual server.

IDL Definition

HRESULT StartServer ( [in] LONG  lVirtServId ) ;

Parameters

lVirtServId

The Membership virtual server instance ID.

Return Values

A standard HRESULT value

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokServers = ObjCreator.CreateObjAuth("MemAdmin.BrokServers.1")

BrokServers.StartServer 1   ' start server # 1


Interface IBrokServers StopServer Method

StopServer Method

The StopServer method stops a specified instance of a Membership virtual server.

IDL Definition

HRESULT StopServer ( [in] LONG lVirtServId ) ;

Parameters

lVirtServId

The Membership virtual server instance ID.

Return Values

A standard HRESULT value

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set BrokServers = ObjCreator.CreateObjAuth("MemAdmin.BrokServers.1")

BrokServers.StopServer 1 '   stops server # 1


CoClass GuidGen

Class GuidGen

The GuidGen class defines a COM object that can be used to generate GUID values in a scripting environment. This class of object is useful when low-level COM library functions cannot be accessed directly, such as in a Windows Scripting Host (WSH) script or an ASP script.

COM Class Identification

The following values can be used to identify this COM class. These values are set in the registry when the Site Server 3.0 product is installed.

Programmatic Identifier

Membership.GuidGen.1

CLSID

CB7865A2-E677-11D0-BDC7-00C04FB6163F

COM Class Name

GuidGen

Type Information

Type library information about this COM class and its associated interfaces can be found as a resource in the following dynamic link library:

c:\microsoft site server\bin\p&m\autoobj.dll

It exports the standard ITypeLib COM interface.

Interfaces

The GuidGen COM class exposes the custom dual interface IGuidGen. Client applications may access the method via the COM interface IGuidGen or through the dispinterface IGuidGen via the IDispatch interface.


Interface IGuidGen GenerateGUID Method

GenerateGUID

This method returns a generated Globally Unique IDentifier when invoked.

IDL Definition

HRESULT GenerateGUID( [out,retval] BSTR* pVal ) ;

Parameters

pVal

on return, the variable contains the GUID value in standard registry format. (e.g. {3050F53D-98B5-11CF-BB82-00AA00BDCE0B})

Return Values

a standard HRESULT value

Example

VBScript in a Windows Scripting Host script

Set IGuidGen = CreateObject("Membership.GuidGen")
GUIDVal = IGuidGen.GenerateGuid


CoClass LdapCfg (MemAdmin.LdapConfig.1)

Class LDAPCfg

The LDAPCfg COM class defines an object that administrators can use to administer and/or configure instances of the Lightweight Directory Access Protocol (LDAP) server used by Site Server 3.0.

COM Class Identification

The following values can be used to identify this COM class. These values are set in the registry when the Site Server 3.0 product is installed.

Programmatic Identifier

MemAdmin.LDAPConfig.1

CLSID

40E9AD64-E2A1-11D0-920F-00C04FB954C7

COM Class Name

ldapcfg

Type Information

Type information is available for this class through a type library attached to the following DLL as a resource:

"c:\microsoft site server\bin\p&m\ladmin2.dll"

One can view this information in the standard way.

Interfaces

The ldapcfg COM class exposes the single dual custom COM interface Ildapcfg. Thus, the methods and properties are accessible through the COM interface, or through the dispinterface Ildapcfg. (IDispatch)


Interface ILdapCfg AttachToRemoteMachine Method

AttachToRemoteMachine Method

This method binds to the LDAP service on the machine specified.

IDL Definition

HRESULT AttachToRemoteMachine([in] VARIANT szMachineName /* VT_BSTR */ );

Parameters

bszMachineName

a VT_BSTR variable containing the UNC, DNS name, or IP address of the machine running an instance of the LDAP server to administer.

Return Values

A standard HRESULT value

Remarks

This method is used to prepare configuration of a instance of the LDAP service hosted on a remote machine. The name passed can be an UNC, a DNS resolvable name, or an IP address in dot (quad) notation. Always call this method first to administer a remote instance.

For performance and ease-of-use reasons, the object that implements the Ildapcfg interface is a COM object. This object, in turn, connects to a DCOM object that is part of the LDAP server in order to perform the necessary configuration activities.

By default, the Ildapcfg object connects to the LDAP server on the local machine. Using this method, however, connections can be established to an LDAP server on some other machine. This allows the use of the Ildapcfg methods and properties in the administration of that remote server.

The AttachToRemoteMachine must be called before any attempt to configure a remote LDAP server. The effects of thismethod last until the next call to AttachToRemoteMachine, or a call to AttachToLocalMachine.

Example

Set LdapConf = CreateObject("MemAdmin.LDAPConfig.1")
BrokServers.AttachToRemoteMachine "SomeServer"


Interface ILdapCfg AttachToLocalMachine Method

AttachToLocalMachine Method

This method attaches the LDAP Administration object to the LDAP server on the local machine. This is the default behavior. This method can be used to reset the effects of AttachToRemoteMachine.

IDL Definition

HRESULT AttachToLocalMachine();

Parameters

none

Return Values

a standard HRESULT value

Example

VBScript

Set ILdapcfg = CreateObject("MemAdmin.LdapConfig")
ILdapcfg.AttachToRemoteMachine "RemoteServerName"
ILdapcfg.LoadConfig 4
… '  configure this LDAP server instance, etc
ILdapcfg.AttachToLocalMachine


Interface ILdapCfg LoadConfig Method

LoadConfig Method

This method loads the server instance's configuration information into the object.

IDL Definition

HRESULT LoadConfig([in] VARIANT InstanceId );

Parameters

InstanceId

a VT_I4 (integer) value specifying the server instance to configure

Return Values

a standard HRESULT value

Remarks

Once a configuration has been loaded with LoadConfig, the various properties can be used to modify the configuration. The configuration is saved with the SaveConfig method.

Example

VBScript

Set ILdapcfg = CreateObject("MemAdmin.Ldapconfig")
ILdapcfg.LoadConfig 4  ' loads config info for server 4 on local machine


Interface ILdapCfg SaveConfig Method

SaveConfig Method

This method commits the changes made in the object for the currently loaded LDAP server instance.

IDL Definition

HRESULT SaveConfig();

Parameters

none

Return Values

a standard HRESULT value

Example

VBScript

Set ILdapcfg = CreateObject("MemAdmin.Ldapconfig")
ILdapcfg.LoadConfig 4  ' loads config info for server 4 on local machine
… ' change some properties
ILdapcfg.Saveconfig


Interface ILdapCfg CreateConfig Method

CreateConfig Method

This method creates a new instance of an LDAP server using the specified identifier. this identifier should not currently be used.

IDL Definition

HRESULT CreateConfig([in] VARIANT InstanceId);

Parameters

InstanceId

a VT_I4 (integer) value specifying the new server instance identifier

Return Values

a standard HRESULT value

Remarks

The CreateConfig method creates a new default configuration with a given instance number. In essence, therefore, a new LDAP server instance is created, in a STOPPED state and with a completely default configuration.

Once the new instance has been created, its properties can be set using the properties described in this reference. To commit the changes, one must call SaveConfig.

Example

VBScript

Set ILdapcfg = CreateObject("MemAdmin.Ldapconfig")
ILdapcfg.CreateConfig 4  '


Interface ILdapCfg DeleteConfig Method

DeleteConfig Method

This method immediately deletes the specified virtual server instance configuration.

IDL Definition

HRESULT DeleteConfig( [in]  VARIANT lInstanceId );

Parameters

lInstanceId

A VT_I4 (integer) value specifying the server instance number to delete the configuration for

Return Values

a standard HRESULT value

Remarks

The DeleteConfig method acts immediately. No call to SaveConfig is required. Once the specified instance has been deleted, the identifier can be reused to create a new instance.

Example

VBScript

Set ILdapcfg = CreateObject("MemAdmin.Ldapconfig")
ILdapcfg.DeleteConfig 4 ' delete instance 4


Interface ILdapCfg IsAddrInUse Method

IsAddrInUse Method

This method will check to see if the IP and port specified are currently in use by attempting to bind a socket using them.

HRESULT IsAddrInUse(
 [in]   long lIP,
 [in]   long lPort
);

Parameters

lIP

the IP address

lPort

the TCP port

Return Values

a standard HRESULT value. The method will succeed if the socket is successfully bound, or an error otherwise.

Remarks

The IP address should be in a standard packed 4 byte integer.


Interface ILdapCfg CreateDSPartition Method

CreateDSPartition Method

This method creates a directory service partition for a specified container.

IDL Definition

HRESULT CreateDSPartition(
 [in] VARIANT lInstanceId,
 [in] VARIANT szDn,
 [in] VARIANT lCount,
 [out] VARIANT * plPartitionID,
 [out] VARIANT * plObjectID
);

Parameters

lInstanceId (VT_I4)

the virtual server instance hosting the container to partition

szDn (VT_BSTR)

the distinguished name (DN) of the container to partition (e.g. o=realm/ou=members)

lCount (VT_I4)

the number of sub-partitions to put on this partition

plPartitionID (VT_I4)

on return, the partition identifier of the object to be converted to a subref

plObjectID (VT_I4)

on return, the target object identifier being converted

Return Values

a standard HRESULT value


Interface ILdapCfg AddPartitionDbServer Method

AddPartitionDbServer Method

This method adds a SQL server database to the LDAP server's internal partition map for the specified container.

IDL Definition

HRESULT AddPartitionDbServer(
 [in] VARIANT lInstanceId,
 [in] VARIANT szContainerPartition,
 [in] VARIANT lSubPartitionNumber,
 [out] VARIANT * dwServerId,
 [in] VARIANT szServerName,
 [in] VARIANT szDatabaseName,
 [in] VARIANT szLogin,
 [in] VARIANT szPassword,
 [in] VARIANT dwMaxCnx,
 [in] VARIANT dwTimeout,
 [in] VARIANT dwReplicationType,
 [in] VARIANT lSubrefPartitionID,
 [in] VARIANT lSubrefObjectID
);

Parameters

lInstanceId (VT_I4)

The LDAP virtual server instance

szContainerPartition (VT_BSTR)

The name of the namespace partition for which the addition is targeted

lSubPartitionNumber (VT_I4)

The number of the sub-partition for which the addition is targeted

dwServerId (VT_I4)

The server/database combination identifier for which the addition is targeted; this value is generated by the database and is returned here

szServerName (VT_BSTR)

The server hosting the SQL server

szDatabaseName (VT_BSTR)

The targeted database on the supporting SQL server

szLogin (VT_BSTR)

The login name for the supporting SQL server

szPassword (VT_BSTR)

The login password for each the supporting SQL server

dwMaxCnx (VT_I4)

The maximum number of concurrent connections allowed from the LDAP server to the SQL server

dwTimeout (VT_I4)

The maximum time a request will be allowed to remain outstanding on the SQL server (how long before the LDAP server gives up on getting a response back from the SQL server)

dwReplicationType (VT_I4)

The replication type of the supporting SQL server - A SQL server can be of types U2_REPLTYPE_WRITE, U2_REPLTYPE_READ, or U2_REPLTYPE_BOTH

lSubrefPartitionID (VT_I4)

If this is a sub-ref partition, this identifies which partition the sub-ref that references the new database lives on. If this is not a partition this value MUST be bit-wise NOT ZERO (~0, or 0xffffffff)

lSubrefObjectID (VT_I4)

If this is a sub-ref partition, this tells us the DSID of the object which references the new database. If this is not a partition this value MUST be bit-wise NOT ZERO (~0, or 0xffffffff)

Return Values

a standard HRESULT value


Interface ILdapCfg EditPartitionDbServer Method

EditPartitionDbServer Method

This method can be used to configure the information about an SQL server that hosts a database used to support a specified partition.

IDL Definition

HRESULT EditPartitionDbServer(
 [in] VARIANT lInstanceId,
 [in] VARIANT szContainerPartition,
 [in] VARIANT lSubPartitionNumber,
 [in] VARIANT dwServerId,
 [in] VARIANT szServerName,
 [in] VARIANT szDatabaseName,
 [in] VARIANT szLogin,
 [in] VARIANT szPassword,
 [in] VARIANT dwMaxCnx,
 [in] VARIANT dwTimeout,
 [in] VARIANT dwReplicationType
);

Parameters

lInstanceId (VT_I4)

the LDAP virtual server instance

szContainerPartition (VT_BSTR)

The name of the target namespace partition

lSubPartitionNumber (VT_I4)

The number of the sub-partition to be edited

dwServerId (VT_I4)

the server/database identifier combination to be edited

szServerName (VT_BSTR)

the name of the machine hosting the SQL server

szDatabaseName (VT_BSTR)

The targeted database name on the supporting SQL server

szLogin (VT_BSTR)

The login name for the supporting SQL server

szPassword (VT_BSTR)

The login password for each the supporting SQL server

dwMaxCnx (VT_I4)

The maximum number of concurrent connections allowed from the LDAP server to the SQL server

dwTimeout (VT_I4)

The maximum time a request should be allowed to remain outstanding on the SQL server (how long before the LDAP server gives up on getting a response back from the SQL server)

dwReplicationType (VT_I4)

The replication type of the supporting SQL server. A SQL server can be of types U2_REPLTYPE_WRITE, U2_REPLTYPE_READ, or U2_REPLTYPE_BOTH

Return Values

a standard HRESULT value


Interface ILdapCfg GetPartitionDbInfo Method

GetPartitionDbInfo Method

This method requests all the information about the various SQL server databases that support a specified partition for the LDAP server instance.

IDL Definition

HRESULT GetPartitionDbInfo(
 [in] VARIANT lInstanceId,
 [in] VARIANT szContainerPartition,
 [in] VARIANT lSubPartitionNumber,
 [out] VARIANT * rgdwServerId,
 [out] VARIANT * rgszServerName,
 [out] VARIANT * rgszDatabaseName,
 [out] VARIANT * rgszLogin,
 [out] VARIANT * rgszPassword,
 [out] VARIANT * rgdwMaxCnx,
 [out] VARIANT * rgdwTimeout,
 [out] VARIANT * rgdwReplicationType
);

Parameters

lInstanceId (VT_I4)

The virtual server instance

szContainerPartition (VT_BSTR)

The name of the namespace partition for which the information is requested

lSubPartitionNumber (VT_I4)

The number of the sub-partition for which the information is requested - NOTE: Indices on the remaining parameters are correlated (e.g. rgdwServerId[n] correlates to rgszServerName[n])

rgdwServerId

A VT_ARRAY containing VT_I4 integers indicating the server id of each supporting server/database combination.

rgszServerName

A VT_ARRAY containing VT_BSTR strings indicating the name of each of the supporting SQL servers.

rgszDatabaseName

A VT_ARRAY containing VT_BSTR strings indicating the targeted database on each of the supporting SQL servers.

rgszLogin

A VT_ARRAY containing VT_BSTR strings indicating the login name for each of the supporting SQL servers.

rgszPassword

A VT_ARRAY containing VT_BSTR strings indicating the associated login password for each of the supporting SQL servers.

rgdwMaxCnx

A VT_ARRAY containing VT_I4 integers indicating the maximum number of concurrent connections allowed from the LDAP server to the SQL server.

rgdwTimeout

A VT_ARRAY containing VT_I4 integers indicating the maximum time a request should be allowed to remain outstanding on the SQL server (how long before the LDAP server gives up on getting a response back from the SQL server.

rgdwReplicationType

A VT_ARRAY containing VT_I4 values indicating the replication type of the supporting SQL server. A SQL server can be of types U2_REPLTYPE_WRITE, U2_REPLTYPE_READ, or U2_REPLTYPE_BOTH

Return Values

a standard HRESULT value


Interface ILdapCfg GetPartitionDbServer Method

GetPartitionDbServer Method

This method returns information about a specified database server used to host a portion of a specified partition. Each partition maps a partition number to a database hosted by a particular server.

IDL Definition

HRESULT GetPartitionDbServer(
 [in] VARIANT lInstanceId,
 [in] VARIANT szContainerPartition,
 [in] VARIANT lSubPartitionNumber,
 [in] VARIANT dwServerId,
 [out] VARIANT * szServerName,
 [out] VARIANT * szDatabaseName,
 [out] VARIANT * szLogin,
 [out] VARIANT * szPassword,
 [out] VARIANT * dwMaxCnx,
 [out] VARIANT * dwTimeout,
 [out] VARIANT * dwReplicationType
);

Parameters:

lInstanceId (VT_I4)

The LDAP virtual server instance the root database information is requested for

szContainerPartition (VT_BSTR):

The name of the namespace partition for which the information is requested

lSubPartitionNumber (VT_I4)

The number of the sub-partition for which the information is requested

dwServerId (VT_I4)

The server id of the server/database combination for which the information is requested

szServerName (VT_BSTR)

The name of the supporting SQL server

szDatabaseName (VT_BSTR)

The targeted database on the supporting SQL server.

szLogin (VT_BSTR)

The login name for the supporting SQL server.

szPassword (VT_BSTR)

The login password for each the supporting SQL server.

dwMaxCnx (VT_I4)

The maximum number of concurrent connections allowed from the LDAP server to the SQL server.

dwTimeout (VT_I4)

The maximum time a request should be allowed to remain outstanding on the SQL server (how long before the LDAP server gives up on getting a response back from the SQL server).

dwReplicationType (VT_I4)

The replication type of the supporting SQL server - A SQL server can be of types U2_REPLTYPE_WRITE, U2_REPLTYPE_READ, or U2_REPLTYPE_BOTH

Return Values

a standard HRESULT value


Interface ILdapCfg GetSubPartitions Method

GetSubPartitions Method

This method retrieves a list of the sub-partitions for a specified container.

IDL Definition

HRESULT GetSubPartitions(
 [in] VARIANT lInstanceId,
 [in] VARIANT szContainer,
 [out] VARIANT*  rgdwSubPartitionNumber
);

Parameters

lInstanceId

the virtual server instance the root database information is requested for

szContainer

The container for which the list of partitions (or value partitions) is requested (e.g. "o=somecompany/ou=members"

rgdwSubPartitionNumber

on return, a VT_ARRAY of VT_I4 values. Each integer specifies each of the available sub-partitions on a namespace partition.

Return Values

a standard HRESULT value


Interface ILdapCfg RemovePartitionDbServer Method

RemovePartitionDbServer Method

This method will remove the specified partition SQL server from the internal partition map.

IDL Definition

HRESULT RemovePartitionDbServer(
 [in] VARIANT lInstanceId,
 [in] VARIANT szContainerPartition,
 [in] VARIANT lSubPartitionNumber,
 [in] VARIANT dwServerId
);

Parameters

lInstanceId

the LDAP virtual server instance to remove

szContainerPartition

The targetted namespace partition with the partition to remove

lSubPartitionNumber

The number of the sub-partition for which the removal is targeted

dwServerId

the server/database combination server identifier for which the removal is targeted

Return Values

a standard HRESULT value


Interface ILdapCfg AddReplica Method

AddReplica Method

This method will add a specified LDAP virtual server instance to the list of replication targets.

IDL Definition

HRESULT AddReplica(
 [in]   long   lServerId,
 [in]   BSTR   szServerName,
 [in]   BSTR   szRpcGuid
);

Parameters

lServerId

the target LDAP virtual server instance identifier

szServerName

the host the LDAP virtual server instance is running on

szRpcGuid

the RPC UUID for the targetted instance

Return Values

a standard HRESULT value

Remarks

The RPC UUID should be generated using the ConfigLocalReplica method.


Interface ILdapCfg ConfigLocalReplica Method

ConfigLocalReplica Method

This method will set up a specified LDAP virtual server instance as a target instance for replication from the primary server.

IDL Definition

HRESULT ConfigLocalReplica(
 [in]   long   lNewServerId,
 [out]   VARIANT *szRpcGuid
);

Parameters

lNewServerId

the LDAP virtual server instance identifier

szRpcGuid

on return, a VT_BSTR value containing the RPC UUID representing this replication target server instance.

Return Values

a standard HRESULT value


Interface ILdapCfg DelReplica Method

DelReplica Method

This method will delete the specified LDAP virtual server instance from the list of target replication server instances.

IDL Definition

HRESULT DelReplica(
 [in]   long   lServerId
);

Parameters

lServerId

the LDAP virtual server instance identifier

Return Values

a standard HRESULT value


Interface ILdapCfg GetDynamicReplicationList Method

GetDynamicReplicationList Method

Retrieves the list of LDAP/ILS servers that replicate to each other.

IDL Definition

HRESULT GetDynamicReplicationList(
 [in]  VARIANT lInstanceId,
 [out] VARIANT* rgszReplNames,
 [out] VARIANT* rgszReplIDs
);

Parameters

lInstanceId: (VT_I4)

The instance number of the server of interest.

rgszReplNames: (VT_ARRAY of VT_BSTR)

on return, the list of machine names. The VT_ARRAY (SAFEARRAY) contains VT_BSTR values.

rgszReplIDs: (VT_ARRAY of VT_BSTR)

on return, the list of machine IDs. The VT_ARRAY (SAFEARRAY) contains VT_BSTR values.

Return Values

a standard HRESULT value


Interface ILdapCfg ListAllReplica Method

ListAllReplica Method

This method will list all LDAP virtual server instance identifiers and their respective Server names and RPC UUID values.

IDL Definition

HRESULT ListAllReplica(
 [out] VARIANT * rgServerId,         // SAFEARRAY OF VARIANT OF LONG
 [out] VARIANT * rgszServerName,      // SAFEARRAY OF VARIANT OF BSTR
 [out] VARIANT * rgszRpcGuid         // SAFEARRAY OF VARIANT OF BSTR
);

Parameters

rgServerId

on return, a VT_ARRAY containing VT_LONG values each of which is an LDAP virtual server instance identifier

rgszServerName

on return, a VT_ARRAY containing VT_BSTR values each of which is the server name hosting the corresponding virtual server instance

rgszRpcGuid

on return, a VT_ARRAY containing VT_BSTR values each of which is the RPC UUID for the corresponding virtual server instance

Return Values

a standard HRESULT value

Remarks

The items in the array are correlated by their position in the array. (i.e. array item 1 in each returned array are the instance id, server name, and GUID for a target replication virtual server instance.)


Interface ILdapCfg QueryLocalReplica Method

QueryLocalReplica Method

This method returns the LDAP virtual server instance identifier for the local replica.

HRESULT QueryLocalReplica(
 [out]   VARIANT* lServerId
);

Parameters

lServerId

the LDAP virtual server instance identifier

Return Values

a standard HRESULT value


Interface ILdapCfg GetServerstate Method

GetServerState Method

This method returns the current state of the LDAP server instance specified.

IDL Definition

HRESULT GetServerState([in] VARIANT Instance, [out] VARIANT *lState);

Parameters

Instance

The instance number of the server of interest.

lState

on return, a VT_I4 value indicating the state of the server.

Possible values for lState are:

1 - "Server is Starting"

2 - "Server has been Started"

3 - "Server is Stopping"

4 - "Server has been Stopped"

5 - "Server is Pausing"

6 - "Server has been Paused"

7 - "Server is trying to Continue after a Pause"

Return Values

a standard HRESULT value


Interface ILdapCfg StartServer Method

StartServer Method

This method attempts to start the specified LDAP server instance.

IDL Definition

HRESULT StartServer( [in] VARIANT lInstanceId );

Parameter

lInstanceId

The instance number of the server of interest

Return Values

a standard HRESULT value


Interface ILdapCfg StopServer Method

StopServer Method

This method attempts to stop the specified LDAP server instance.

IDL Definition

HRESULT StopServer( [in] VARIANT lInstanceId );

Parameter

lInstanceId

The instance number of the server of interest

Return Values

a standard HRESULT value


Interface ILdapCfg PauseServer Method

PauseServer Method

This method attempts to pause the specified LDAP server instance.

IDL Definition

HRESULT PauseServer( [in] VARIANT lInstanceId );

Parameter

lInstanceId

The instance number of the server of interest

Return Values

a standard HRESULT value


Interface ILdapCfg ContinueServer Method

ContinueServer Method

This method attempts to restart a previously paused LDAP server instance specified.

IDL Definition

HRESULT ContinueServer( [in] VARIANT lInstanceId );

Parameter

lInstanceId

The instance number of the server of interest

Return Values

a standard HRESULT value


Interface ILdapCfg CompactDatabase Method

CompactDatabase Method

This method will compact the backend Access database used by the specified LDAP server instance.

IDL Definition

HRESULT CompactDatabase( [in] VARIANT lInstanceId);

Parameter

lInstanceId

The LDAP server instance identifier.

Return Values

a standard HRESULT value

Remarks

This procedure is only applicable to LDAP servers that use Access as an underlying database.

WARNING: The given LDAP server instance will be stopped and restarted during the compaction process. This is necessary in order for the Access DB driver to obtain an exclusive lock on the database as mandated by its compaction procedure.

The CompactDatabase method will fail if another LDAP instance, aside from the given one, is also using the same Access Database. Such instances must be stopped in order for the compact operation to succeed.


Interface ILdapCfg RepairDatabase Method

RepairDatabase Method

This method will perform repairs on the backend Access database used by the specified LDAP server instance.

IDL Definition

HRESULT RepairtDatabase( [in] VARIANT lInstanceId);

Parameter

lInstanceId

The LDAP server instance identifier.

Return Values

a standard HRESULT value

Remarks

This procedure is only applicable to LDAP servers that use Access as an underlying database.

WARNING: The given LDAP server instance will be stopped and restarted during the repair process. This is necessary in order for the Access DB driver to obtain an exclusive lock on the database as mandated by its repair procedure.

The RepairDatabase method will fail if another LDAP instance, aside from the given one, is also using the same Access Database. Such instances must be stopped in order for the repair operation to succeed.


Interface ILdapCfg GetDirectoryProperties Method

GetDirectoryProperties Method

This method returns all the properties for the specified LDAP server instance. These properties appear as the server's properties on the Microsoft Management Console property page.

IDL Definition

HRESULT GetDirectoryProperties(
 [in] VARIANT lInstanceId,
 [out] VARIANT *szRealm,
 [out] VARIANT *szDnPrefix,
 [out] VARIANT * fIsSQL,
 [out] VARIANT * fExtSec,
 [out] VARIANT * rgszContainerPartitions
);

Parameters

lInstanceId

the virtual server instance the root database information is requested for

szRealm

the NT security realm

szDnPrefix

the naming prefix

fIsSQL

indicates whether this directory has SQL server database backend. Zero (0) indicates false, one (1) indicates TRUE.

fExtSec

indicates whether this directory uses NT Security or Membership Security. Zero (0) indicates Membership security. One (1) means NT security.

rgszContainerPartitions

this is a VT_ARRAY containing VT_BSTR values. The strings represent the names of the namespace partitions of the directory, e.g. c=us or o=somecompnay/ou=members.

Return Values

a standard HRESULT value


Interface ILdapCfg SetDirectoryProperties Method

SetDirectoryProperties Method

This method sets the Realm and Naming prefix for a specified LDAP server instance. This method is used by the Microsoft Management Console to update properties changed on the property page for the instance.

IDL Definition

HRESULT SetDirectoryProperties(
 [in] VARIANT lInstanceId,
 [in] VARIANT szRealm,
 [in] VARIANT szDnPrefix
);

Parameters

lInstanceId (VT_I4)

the virtual server instance the root database information is to be set for

szRealm (VT_BSTR)

the NT security realm

szDnPrefix (VT_BSTR)

the naming prefix

Return Values

a standard HRESULT value


Interface ILdapCfg Port Property

Port Property

This property specifies the TCP/IP port the LDAP server instance will bind and listen for client requests.

IDL Definition

[propget]
HRESULT Port([out, retval] VARIANT* pData);
[propput]
HRESULT Port([in] VARIANT Data );

Type

VT_I4 (integer)

Example

VBscript

Set ILdapCfg = CreateObject("MemAdmin.LdapConfig")
ILdapCfg.LoadConfig 3
ILdapCfg.Port = 2000


Interface ILdapCfg SecurePort Property

SecurePort Property

This property specifies the TCP/IP port the server instance will bind using the Secure Sockets Layer (SSL) protocol.

IDL Definition

[propget]
HRESULT SecurePort([out, retval] VARIANT* pData);
[propput]
HRESULT SecurePort([in] VARIANT Data);

Type

VT_I4 (integer)


Interface ILdapCfg IP Property

IP Property

This property specifies the Internet Protocol (IP) address the LDAP server instance will use along with a specified port to bind a socket and listen for client requests.

IDL Definition

[propget]
HRESULT IP([out, retval] VARIANT* pData);
[propput]
HRESULT IP([in] VARIANT Data);

Type

VT_BSTR (string)

Remarks

Set this property to the empty string to allow the instance to bind using any of the available IP addresses on the local machine.

The list of valid IP Addresses on the machine can be obtained from the SupportedIPs read-only property. This valid IP address list is checked whenever an IP change is attempted. An error is returned on an attempt to change the LDAP server IP to one that is not valid on the machine.

Example


Interface ILdapCfg SupportedIPs Property

SupportedIPs Property

This property lists the available IP addresses on the local machine.

IDL Definition

HRESULT SupportedIPs([out, retval] VARIANT* pData);

Type

VT_ARRAY (SAFEARRAY)

Contains

VT_BSTR (string)

Remarks

A list of IP addresses supported on the LDAP server machine. This list is automatically checked when the IP or DNSName properties are modified to make sure the new IP address is supported. This property should be used primarily for UI elements (such as a list box that allows the user to select only valid IP addresses).

SupportedIPs is a read-only property.


Interface ILdapCfg DNSName Property

DNSName Property

This property specifies the Domain Name Service (DNS) name for the machine hosting the LDAP server instance.

IDL Definition

[propget]
HRESULT DNSName([out, retval] VARIANT* pData );
[propput]
HRESULT DNSName([in] VARIANT Data );

Type

VT_BSTR (string)

Remarks

This property reads as the local machine's name if an IP address is unspecified.

Setting this property makes appropriate changes to the IP property and vice-versa.

Example


Interface ILdapCfg ReadOnlyMode Property

ReadOnlyMode Property

This property specifies whether the LDAP server instance is set to read-only mode.

IDL Definition

[propget]
HRESULT ReadOnlyMode([out, retval] VARIANT* pData );
[propput]
HRESULT ReadOnlyMode([in] VARIANT Data );

Type

VT_BOOL (boolean)

Remarks

If the server is set to read-only mode, no database updates are allowed.

Example


Interface ILdapCfg EnableAllSub Property

EnableAllSub Property

This property specifies whether, during a search on a string, the server should look for all substrings that match or just the first substring.

IDL Definition

[propget]
HRESULT EnableAllSub([out, retval] VARIANT* pData);
[propput]
HRESULT EnableAllSub([in] VARIANT Data);

Type

VT_BOOL (boolean)

Example


Interface ILdapCfg MaxPageSize Property

MaxPageSize Property

This property specifies the maximum page size for a LDAP search query requested for this instance.

IDL Definition

[propget]
HRESULT MaxPageSize([out, retval] VARIANT* pData);
[propput]
HRESULT MaxPageSize([in] VARIANT Data);

Type

VT_I4 (integer)


Interface ILdapCfg MaxResultSet Property

MaxResultSet Property

This property specifies the maximum size of the result set for a requested query.

IDL Definition

[propget]
HRESULT MaxResultSet([out, retval] VARIANT* pData);
[propput]
HRESULT MaxResultSet([in] VARIANT Data);

Type

VT_I4 (integer)

Remarks

This property is in units of kilobytes. (KB)

Example


Interface ILdapCfg MaxQueryTime Property

MaxQueryTime Property

This property specifies the time, in milliseconds, the LDAP server instance will wait for a query to complete before it should time out.

IDL Definition

[propget]
HRESULT MaxQueryTime([out, retval] VARIANT *pData);
[propput]
HRESULT MaxQueryTime([in] VARIANT Data);

Type

VT_I4 (integer)

Example


Interface ILdapCfg MaxConnection Property

MaxConnection Property

This propery specifies how many concurrent TCP/IP sockets can be open for the LDAP server instance before connections are refused.

IDL Definition

[propget]
HRESULT MaxConnection([out, retval] VARIANT *pData);
[propput]
HRESULT MaxConnection([in] VARIANT Data);

Type

VT_I4 (integer)

Example


Interface ILdapCfg ConnectionTimeout Property

ConnectionTimeout Property

This property specifies the time limit in seconds on idle socket connections in the TIME_WAIT state before they are dropped by the LDAP server instance.

IDL Definition

[propget]
HRESULT ConnectionTimeout([out, retval] VARIANT *pData);
[propput]
HRESULT ConnectionTimeout([in] VARIANT Data);

Type

VT_I4 (integer)

Example


Interface ILdapCfg EnableShortTermIPBlacklisting Property

EnableShortTermIPBlacklisting Property

This property, if set to TRUE (1), informs the LDAP server instance that is should "blacklist" an IP address from connecting if the client process fails to propertly authenticate after a certain number of tries.

IDL Definition

[propget]
HRESULT EnableShortTermIPBlacklisting([out, retval] VARIANT *pData);
[propput]
HRESULT EnableShortTermIPBlacklisting([in] VARIANT Data);

Type

VT_I4 (integer)

Remarks

FALSE = 0; TRUE = 1


Interface ILdapCfg EnableShortTermAccountBlacklisting Property

EnableShortTermAccountBlacklisting Property

This property, if set to TRUE, directs the LDAP server instance to "blacklist" accounts that have failed to property authenticate a certain number of times in a specified period of time.

IDL Definition

[propget]
HRESULT EnableShortTermAccountBlacklisting([out, retval] VARIANT *pData);
[propput]
HRESULT EnableShortTermAccountBlacklisting([in] VARIANT Data);

Type

VT_I4 (integer)


Interface ILdapCfg Authorization Property

Authorization Property

This property specifies the authorization mode (type) for the server.

IDL Definition

[propget]
HRESULT Authorization([out, retval] VARIANT *pData);
[propput]
HRESULT Authorization([in] VARIANT Data);

Type

VT_I4 (integer)

Remarks

Valid values are

MD_AUTH_ANONYMOUS (1)

MD_AUTH_BASIC (2) - Clear Text

MD_AUTH_NT (4) - NTLM or DPA

or any additive combination (bitwise or) of the three.


Interface ILdapCfg EnableSSL Property

EnableSSL Property

This property, if set to TRUE, directs the LDAP server instance to enable the Secure Sockets Layer (SSL) protocol for client requests. The server uses the SecurePort property TCP/IP port value when binding its SSL listening socket.

IDL Definition

[propget]
HRESULT EnableSSL([out, retval] VARIANT *pData);
[propput]
HRESULT EnableSSL([in] VARIANT Data);

Type

VT_BOOL (boolean)


Interface ILdapCfg EnableSSL128 Property

EnableSSL128 Property

This property, if set to TRUE, directs the LDAP server instance to enable the Secure Sockets Layer (SSL) protocol with 128 bit keys for network connections. The server instance uses the SecurePort property port value when binding its listening TCP/IP socket.

IDL Definition

[propget]
HRESULT EnableSSL128([out, retval] VARIANT *pData);
[propput]
HRESULT EnableSSL128([in] VARIANT Data);

Type

VT_BOOL (boolean)


Interface ILdapCfg EnableDynamic Property

EnableDynamic Property

If this property is set to TRUE, the server will allow dynamic directory objects. (ILS)

IDL Definition

[propget]
HRESULT EnableDynamic([out, retval] VARIANT *pData);
[propput]
HRESULT EnableDynamic([in] VARIANT Data);

Type

VT_BOOL (boolean)


Interface ILdapCfg MinTTL Property

MinTTL Property

This property defines the minimum time to live for dynamic objects. It is in units of seconds.

IDL Definition

[propget]
HRESULT MinTTL([out, retval] VARIANT *pData);
[propput]
HRESULT MinTTL([in] VARIANT Data);

Type

VT_I4 (integer)


Interface ILdapCfg MaxDynamObj Property

MaxDynamObj Property

This property specifies the maximum number of concurrent dynamic objects that the LDAP server instance will allow.

IDL Definition

[propget]
HRESULT MaxDynamObj([out, retval] VARIANT *pData);
[propput]
HRESULT MaxDynamObj([in] VARIANT Data);

Type

VT_I4 (integer)


Interface ILdapCfg EnableRTPersion Property

EnableRTPerson Property

Set this property to TRUE if the server should support LDAP v1 backward compatibiliy.

IDL Definition

[propget]
HRESULT EnableRTPerson([out, retval] VARIANT *pData);
[propput]
HRESULT EnableRTPerson([in] VARIANT Data);

Type

VT_BOOL (boolean)


Interface ILdapCfg EnableReplicate Property

EnableReplicate Property

Set this property to TRUE if the LDAP server instance will replicate to other instances that support dynamic objects (ILS).

IDL Definition

[propget]
HRESULT EnableReplicate([out, retval] VARIANT *pData);
[propput]
HRESULT EnableReplicate([in] VARIANT Data);

Type

VT_BOOL (boolean)


Interface ILdapCfg EnableLog Property

EnableLog Property

Set this property to "TRUE" to have the LDAP server instance log requests.

IDL Definition

[propget]
HRESULT EnableLog([out, retval] VARIANT *pData);
[propput]
HRESULT EnableLog([in] VARIANT Data);

Type

VT_BOOL (boolean)


Interface ILdapCfg DBName Property

DBName Property

For SQL server backends, this property should specify the name of the database.

IDL Definition

[propget]
HRESULT DBName([out, retval] VARIANT *pData);
[propput]
HRESULT DBName([in] VARIANT Data);

Type

VT_BSTR (string)


Interface ILdapCfg DBPassword Property

DBPassword Property

This property is used in conjunction with the DBUsername property by the LDAP server instance to authenticate with the SQL or JET backend database.

IDL Definition

[propget]
HRESULT DBPassword([out, retval] VARIANT *pData);
[propput]
HRESULT DBPassword([in] VARIANT Data);

Type

VT_BSTR (string)


Interface ILdapCfg DBSource Property

DBSource Property

This property specifies the database source. If an SQL server is being used, this property should contain the server name. If a JET database is being used, this property should contain the filesystem path to the .MDB file.

IDL Definition

[propget]
HRESULT DBSource([out, retval] VARIANT *pData);
[propput]
HRESULT DBSource([in] VARIANT Data);

Type

VT_BSTR (string)


Interface ILdapCfg DBType Property

DBType Property

This property specifies whether the backend database used to persist (store) the directory data is a SQL server or Jet (access) database. SQL = 1; Jet DB = 2.

IDL Definition

[propget]
HRESULT DBType([out, retval] VARIANT *pData);
[propput]
HRESULT DBType([in] VARIANT Data);

Type

VT_I4 (integer)


Interface ILdapCfg DBUsername Property

DBUsername Property

This property is used along with the DBPassword property by the LDAP server instance to authenticate when logging in to the backend SQL Server or JET database.

IDL Definition

[propget]
HRESULT DBUsername([out, retval] VARIANT *pData);
[propput]
HRESULT DBUsername([in] VARIANT Data);

Type

VT_BSTR (string)


CoClass ObjCreator (ObjCreator.Objcreator.1)

CoClass ObjCreator

The CoClass ObjCreator implements a set of methods that programming languages like Visual Basic can use to indirectly call CoCreateInstanceEx and be able to specify the target machine they desire an instance of an object to run on. This is in contrast to the VB function CreateObject that only connects to the host specified under the AppID for the target coclass. This object also provides a separate method that implements a standard Security Support Provider Interface (SSPI) handshake between a client application and a requested COM object implemented to work with the ObjCreator object using the NTLM security support provider (SSP). This process is completely analogous to the SSPI handshake that Distributed COM (DCOM) uses when providing authentication information about clients to COM objects that are either out-of-process or remote.

COM Class Identifiers

Programmatic Identifier | ObjCreator.ObjCreator.1
CLSID | {C9C419D1-8B6A-11D0-BCD9-00805FCCCE04}
Logical Name | ObjCreator Class
Type Library | c:\winnt\system32\objcreator.dll (resourse in DLL)
Threading Model | "Both"

COM Interfaces Implemented

IUnknown

the standard base COM interface.

IDispatch

the standard Automation COM interface.

IObjCreator

IID C9C419D0-8B6A-11D0-BCD9-00805FCCCE04
Type Library
c:\winnt\system32\objcreator.dll
This dual interface defines two methods for requesting the services of COM classes either on a local or remote machine. The CreateObj method allows creation of objects with a particular Programmatic Identifier on the host specified, via DCOM. The CreateObjAuth does the same, but forces a two-way SSPI handshake to authenticate the requesting client to the target object. If the newly created object is satisfied that the client requesting its services has sufficient credentials, the object will allow the client to invoke the set of protected methods. If the credentials are not sufficient, the client will only be able to execute methods that do not require special privilege by the target object.
HRESULT  CreateObj (
    [in]            BSTR      bstrProgId, // programmatic ID of coclass
    [in, optional]  BSTR      bstrServer, // remote server name
    [out, retval]   VARIANT  *pVarObject  // if successful, VT_DISPATCH
);
HRESULT  CreateObjAuth (
    [in]            BSTR      bstrProgId, // progID of coclass
    [in, optional]  BSTR      bstrServer, // remote server name
    [out, retval]   VARIANT   *pVarObject // if successful, VT_DISPATCH
);

In each case, the user specifies the ProgID of the class desired, and optionally, the name of the server to create the object on. If no server name is given, the name localhost” is assumed. The method then populates the third, (or second if no server name is specified) argument with the IDispatch interface address of the requested object. In CreateObjAuth, if the authentication handshake was not successful with the target object, the HRESULT value S_FALSE is returned.

Note The use of CreateObjAuth is restricted to creating COM objects that have been implemented strictly for use with the ObjCreator. The SSPI handshake will not occur if the target object has not been implemented to work with this coclass.

IObjCreatorAuth

IID 0B63E394-9CCC-11D0-BCDB-00805FCCCE04
Type Library
c:\winnt\system32\objcreator.dll
This interface provides a pure COM interface for C/C++ or pointer-enabled client applications. In this case, there is only one method, and it performs the same function as IObjCreator::CreateObjectAuth above. However, one must supply the CLSID of the coclass desired, rather than the programmatic identifier. Similarly, the IUnknown interface address is returned in the third argument. This method performs a custom SSPI handshake to establish the credentials of the calling client process to the target coclass instance. If the authentication was not successful, the method returns the HRESULT value S_FALSE, If successful, S_OK. In either case, the IUnknown address is returned on an instance of the requested COM object or a standard HRESULT exception is returned.
HRESULT CreateClsObjAuth(
     [in]    GUID*      rClsid, // the CLSID for the class desired
     [in]    BSTR       bstrServer, // the server to run object on
     [out]   IUnknown** ppUnknown   // if successful, the IUnknown
);

Remarks

Note This interface and method are designed strictly for creating instances of COM objects that have been implemented to work specifically with the ObjCreator coclass. One cannot use this interface or method to create arbitrary COM objects


CoClass Schemaobjects (Membership.SchemaObjects.1)

Class SchemaObjects

The SchemaObjects class defines a COM object that can be used to access ADSI objects that define the schemas for users in various directory services. Objects of this class use predefined Active User Object (AUO) entries to bind the appropriate ADSI schema objects. These schema objects are ADSI objects that provide connectivity and cacheing services for the data stored for the schema definitions.

An exhaustive discussion of working with the schemas defining directory service databases is beyond the scope of this reference. For more information about schema definitions, directory service use, and the Active Directory Service Interfaces (ADSI), see the ADSI 2.0 documentation which can be found in the Platform SDK on the Microsoft Developer's Network.

In order for objects of this class to operate correctly, the Active User Objects (AUO) entries for the desired Membership virtual server instance must have been previously configured. For more information about configuring the AUO entries for a Membership virtual server instance, see the AuoConfig Class reference.

COM Class Identification

The following values can be used to identify this COM class. These values are set in the registry when the Site Server 3.0 product is installed.

Programmatic Identifier

Membership.SchemaObjects.1

CLSID

40E9AD64-E2A1-11D0-920F-00C04FB954C7

COM Class Name

ldapcfg

Type Information

Type library information about this COM class and its associated interfaces can be found as a resource in the following dynamic link library:

c:\microsoft site server\bin\p&m\auo.dll

It exports the standard ITypeLib COM interface.

Interfaces

The SchemaObjects class exposes the following dual interfaces:

IADs

IADsContainer

IADsClass

ISchemaObjects


CoClass SchemaObjects, Interface IADs

Interface IADs

The IADs interface exposed by the SchemaObjects class is a strictly contained interface on an associated ADSI object. This interface is covered in detail in the ADSI 2.0 SDK documentation that can be found on the Microsoft Developer's Network. It is under the Platform SDK in the Network and Distributed Services sub-section. The properties and methods exposed with this interface are listed below for convenience.

Properties

Name | Description
Name | Gets the object's relative name.
Class | Gets the object's schema class name.
GUID | Gets the object's globally unique identifier.
ADsPath | Gets the object's ADsPath that uniquely identifies this object from all others.
Parent | Gets the object's ADsPath string for its parent container.
Schema | Gets the ADsPath string to the schema class definition object for this object.

Methods

Name | Description
GetInfo | Reloads the property values for this object as they exist in the underlying directory service.
SetInfo | Saves the changes on this object and its dependents.
Get | Gets the value for a property by name.
Put | Sets the value for a property by name.
GetEx | Gets the value for a single or multi-valued property by name.
PutEx | Sets the value for a single or multi-valued property by name.
GetInfoEx | Reloads specific property values for this object as they exist in the underlying directory service.


CoClass SchemaObjects, Interface IADsContainer

Interface IADsContainer

The IADsContainer interface exposed by the SchemaObjects class is a strictly contained interface on an associated ADSI object. This interface is covered in detail in the ADSI 2.0 SDK documentation that can be found on the Microsoft Developer's Network. It is under the Platform SDK in the Network and Distributed Services sub-section. The properties and methods exposed with this interface are listed below for convenience.

Properties

Name | Description
Count (RO) | Gets the number of Schema objects defined by the current set of AUO provider definitions.
_NewEnum (RO) | Get interface on an enumerator object. This enumerator will step through all the Schema objects defined by the current set of AUO provider definitions.
Filter | Not implemented.
Hints | Not implemented.

Methods

Name | Description
GetObject | Gets an interface on a named object. This name must be an AUO provider alias. The ADSI object loads will have Ads path equal to the path defined in the AUO provider under the name Schema.
Create | Not implemented.
Delete | Not implemented.
CopyHere | Not implemented.
MoveHere | Not implemented.


CoClass SchemaObjects, Interface IADsClass

Interface IADsClass

The IADsClass interface exposed by the SchemaObjects class is a strictly contained interface on an associated ADSI object. This interface is covered in detail in the ADSI 2.0 SDK documentation that can be found on the Microsoft Developer's Network. It is under the Platform SDK in the Network and Distributed Services sub-section. The properties and methods exposed with this interface are listed below for convenience.

Properties

Name | Description
IID | Interface identifer.
IOD | Directory service-specific Object Identifier.
Abstract | Whether or not this schema class is abstract.
Auxiliary | Whether or not this schema class is auxiliary.
MandatoryProperties | List of required properties needed before saving this object.
OptionalProperties | List of optional properties for this object.
NamingProperties | List of naming attributes for this object.
DerivedFrom | Immediate superclasses of this schema class.
AuxDerivedFrom | Immediate superclasses of this schema class.
PossibleSuperiors | List of classes that can contain instances of this class.
Containment | Legal objects types that can be contained within this container.
Container | Whether or not this is a container object.
HelpFilename | Optional help file name.
HelpFileContext | Optional help file context ID.

Methods

Name | Description
Qualifiers | Optional collection of provider-specific qualifiers for this property.


CoClass SchemaObjects, Interface ISchemaObjects

Interface ISchemaObjects

The ISchemaObjects interface exposes a dual interface. Therefore, clients can access the methods either through the associated dispinterface (through IDispatch* implementation) or as a pure COM interface.

The methods this interface provides are listed below, along with the implementation presented by the SchemaObjects COM class.

Methods

Name | Description
BindAs | Sets the credentials the object will use when binding to ADSI objects.
Init | Initializes the object.
InitEx | Initializes the object along with the Credentials flag.
GetEntrySchemaPath | Gets the Schema path for the AUO alias specified.
GetRelativeName | Gets the relative name of the ADSI schema object requested.
OnStartPage | Standard ASP callback method. This method automatically calls Init and passes the current IIS instance identifier.
OnEndPage | Standard ASP callback method.


Interface ISchemaObjects BindAs Method

BindAs Method

The BindAs method sets the ADSI binding credentials used when binding to ADSI objects defined by the specified Active User Object (AUO) provider alias.

IDL Definition

[id(5)] HRESULT BindAs(
BSTR bszAlias,
BSTR bszUserName,
BSTR bszPassword
);

Parameters

bszAlias

The AUO alias to set binding credentials for.

bszUserName

The name to use when binding. This name should be a distinguished name. (e.g. "c=us/o=comp/ou=admin/cn=admin")

bszPassword

The password to use when binding.

Return Values

a standard HRESULT value.

Remarks

The Init or InitEx method must be called first before any other methods are invoked on objects of class SchemaObjects. If one uses the built-in ASP object Server to create the object via its CreateObject method, Init is called automatically in the ISchemaObjects OnStartPage callback method invoked by the ASP scripting context.

The BindAs method can only be invoked prior to any binding of ADSI objects. If an ADSI object has been bound, the method will return a COM exception.

One can permanently set the binding credentials using the BindAsName and BindAsPassword values for the AUO provider definition.

Example

ASP and VBScript

<%
Set ISchemaObjects = Server.CreateObject("Membership.SchemaObjects")
BindUser = "c=US/o=company/ou=members/cn=Administrator"
BindPwd = "password"
call ISchemaObjects.BindAs( BindUser, BindPwd )
%>

See Also

Init

Class AuoConfig


Interface ISchemaObjects Init Method

Init Method

This method initializes the object with an Internet Information Server instance identifier. This identifier is used to map to the associated Membership server instance and the AUO entries defined for it.

IDL Definition

HRESULT Init( BSTR bszHostName ) ;

Parameters

bszHostName

The Internet Information Server instance identifier.

Return Values

a standard HRESULT value.

Remarks

The Init method is automatically called if the built-in ASP Server object is used to create the instance of the SchemaObjects COM class via the CreateObject method. This is done in the ISchemaObjects OnStartPage method which is called by the ASP scripting context after the instance is created.

Example

VBScript in an ASP script

<%
Set ISchemaObjects = Server.CreateObject("Membership.SchemaObjects")
'  init called automatically
%>

Alternately, we can call this method ourselves:

<% Set ISchemaObjects = CreateObject("Membership.SchemaObjects")
   call IschemaObjects.Init(2) ' IIS virt server 3

Note that in the first example, the Server object method CreateObject is used to create the instance. The scripting context automatically invokes ISchemaObjects OnStartPage that in turn invokes the Init method.

See Also

OnStartPage


Interface ISchemaObjects InitEx Method

InitEx Method

The InitEx method initializes the object with a Internet Information Server instance identifier and a boolean flag specifying whether a login credentials prompt should be presented to the user.

IDL Definition

HRESULT InitEx(
[in] BSTR bszHostName,
[in] VARIANT_BOOL fPromptCredentials
);

Parameters

bszHostName

The Internet Information Server instance identifier

fPromptCredentials

A flag specifying whether to prompt the user for credentials.

Return Values

a standard HRESULT value

Remarks

This method is identical to the Init method except that it allows the Credentials flag to be set. This flag is meaningful in the following situations:

  • If the credentials flag is set to TRUE

  • The mapped Membership server instance is set to handle authentication (Membership Authentication)

  • The Authentication (SSPI) package for the Membership server configured to use the MBS_BASIC (Basic clear text or forms authentication) SSPI package.

In this case, an interactive user (not a web user) will be prompted with a standard dialog box whenever they attempt to load a specific ADSI schema object defined by one of the AUO provider definitions. The dialog asks whether they want to log on anonymously or specify a username and password. The name they specify should be a username in the corresponding Membership Directory Service.

Avoid using the InitEx method within ASP pages. Simply create the object using the Server.CreateObject method. This will automatically call the Init method for you.

Example

Visual Basic 5.0 (stand alone EXE)

Dim SchemaObj as SchemaObjects
Set SchemaObj = new SchemaObjects

SchemaObj.InitEx “3”, TRUE

Dim IADs as IADs
Dim List as Variant  ‘ an array

Set IADs = SchemaObj

List = IADs.Get(“mustContain”)   ‘ this causes the schema defined for the
                                 ‘  default AUO provider to be loaded
                                 ‘  However…
‘  AT THIS POINT, the interactive user running the VB app would
‘  be presented with a login dialog.  In order to proceed, they would
‘  have to authenticate against the membership directory service
‘  database.

‘… go on to use the schema object


Interface ISchemaObjects getEntrySchemaPath Method

GetEntrySchemaPath Method

This method returns the value set in the specified Active User Object (AUO) provider definition under the name Schema.

IDL Definition

HRESULT GetEntrySchemaPath(
[in]          BSTR  bszEntryName,
[out, retval] BSTR* pbszSchemaPath
);

Parameters

bszEntryName

The name of the AUO provider

pbszSchemaPath

On return, the ADSI path to the schema object.

Return Values

a standard HRESULT value

Remarks

This value is fetched directly from the AUO provider definition under the name Schema. See the AuoConfig class for information about how to set this value.

Example

VBScript in an ASP script

<%
Set ISchemaObjects = Server.CreateObject("Membership.SchemaObjects")
' the default AUO entry schema path
DefPath = ISchemaObjects.GetEntrySchemaPath("")

' a named AUO entry schema path
Path2 = ISchemaObjects.GetEntrySchemaPath("SomeAUOAlias")
%>

See Also

Class AuoConfig


Interface ISchemaObjects GetRelativeName Method

GetRelativeName Method

The GetRelativeName method returns the AUO provider name for the object whose current IUnknown interface address is passes as the first argument.

IDL Definition

HRESULT GetRelativeName(
[in]          IUnknown* pUnk,
[out, retval] BSTR*     pbszName
);

Parameters

pUnk

The IUnknown interface to the ADSI schema object.

pbszName

On return, the relative name of the object.

Return Values

a standard HRESULT value


Interface ISchemaObjects OnStartPage Method

OnStartPage Method

The OnStartPage method is automatically invoked when the Server object is used to create an instance of the SchemaObjects class. When invoked, the Init method is invoked, and the current Internet Information Server instance identifier is passed. This is the instance identifier that can be fetched in an ASP environment using the Request object ServerVariables collection under the key INSTANCE_ID.

Example

<% Set oSchemaObjects = Server.CreateObject(“Membership.SchemaObjects”) %>
‘  in this case, the OnStartPage is called by the scripting context automatically
‘  so one need not invoke Init explicitly.


Interface ISchemaObjects OnEndPage Method

OnEndPage Method

This method is automatically invoked by the ASP scripting context when the Server object is used to create an instance of the SchemaObjects class using the CreateObject method. It performs any necessary memory de-allocations and reference releases to held interfaces.


CoClass SchemaObjects, IADsContainer::GetObject

SchemaObjects IADsContainer::GetObject Method

The GetObject method returns the Idispatch interface on an ADSI schema object specified in the AUO provider configuration whose alias is passed as the object name.

IDL Definition

HRESULT GetObject (
  [in] BSTR Class,
  [in] BSTR Name,
  [out,retval] VARIANT* pIDisp
) ;

Parameters

Class

This argument is not supported, and should always be “”

Name

The AUO provider alias

pIDisp

On return, the VT_DISPATCH variable contains the interface on the ADSI schema object

Return Values

A standard HRESULT value

Remarks

Unlike the UserObjects implementation of the IADsContainer::GetObject method, the name specified must be an AUO provider alias. It is assumed that all schema objects defined for the AUO providers have no children, and are thus all leaf objects.

One must call Init or InitEx before using GetObject.


CoClass SetupStore (MemAdmin.DSConfig.1)

Class SetupStore

Programmers and administrators can use instances of the SetupStore (MemAdmin.DSConfig.1) COM class to setup directory service database backends. This object will generate the default LDAP backend core database schema required for the LDAP server to function. The backend database can be either Microsoft SQL Server or an Access database.

Programmers must use the special COM class ObjCreator.ObjCreator.1 to create an instance of this class. Direct creation of the class will render all methods useless.

The user executing methods on an instance of this class must have NT administrative privileges.

All examples are in VBScript using the Windows Scripting Host (WSH) objects.

COM Class Identifiers

The following values can be used to identify this COM class. These values are set in the registry when the Site Server 3.0 product is installed.

Programmatic Identifier

MemAdmin.DSConfig.1

CLSID

40E9AD64-E2A1-11D0-920F-00C04FB954C7

COM Class Name

setupstr

Type Library

Type information is available for this class through a type library attached to the following DLL as a resource:

"c:\microsoft site server\bin\p&m\setupstr.dll"

Creating Instances of this Class

Programmers must use the special COM class ObjCreator.ObjCreator.1 to create instances of this class. Directly creating instances will render all methods inoperable.

Interfaces

The SetupStore COM class exposes the the ISetupStore dual interace, providing both a custom COM interface as well as a dispinterface to the methods and properties.


Interface ISetupStore CreateSQLDB Method

CreateSQLDB Method

This method populates a database in a Microsoft SQL Server with the necessary tables to host an LDAP database. Once created, the database can be assigned as the store for an LDAP server instance.

IDL Definition

HRESULT CreateSQLDB(
[in] BSTR bstrServerName,
[in] BSTR bstrDatabaseName,
[in] BSTR bstrDirectoryName,
[in] BSTR bstrDBUserName,
[in] BSTR bstrDBPassword,
[in] BSTR bstrSuperDSPassword,
[in] BOOLEAN fUseMemSecurity
);

Parameters

bstrServerName

the name of the computer hosting the Microsoft SQL server.

bstrDatabaseName

the name of the database to house the LDAP tables, stored procedures,etc.

bstrDirectoryName

the top level name of the directory.

bstrDBUserName

the name to use to authenticate to the SQL server when logging on. This user usually is has administrative privilege in SQL server.

bstrDBPassword

the password to use to authenticate to the SQL server when logging on.

bstrSuperDSPassword

the password to set for the Directory administrator. This password must be set up in a special manner. The username in the directory service is always "administrator".

fUseMemSecurity

a flag specifying whether the LDAP directory service using the database will provide user authentication services to the Membership virtual server. 0=False, 1=True

Return Value

a standard HRESULT value

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set DSConfig = ObjCreator.CreateObjAuth("MemAdmin.DSConfig.1")
Server="dbsvr1"
Database="some-name"
DName="some-name"
DBUser="sa"
DBPass="password-here"
DSSuperPass="other-password"
fUseMemSec=TRUE
call DSConfig.CreateSQLDB(Server,DName,DBUSer,DBPass,DSSuperPass,fMemSec)
If Err.Number <> 0 Then
  WScript.Echo "Error creating database backend"
End If


Interface ISetupStore CreateJetDB Method

CreateJetDB Method

This method creates an Access database and populates it with the necessary tables to host a Membership LDAP directory service.

IDL Definition

HRESULT CreateJetDB(
[in] BSTR bstrFileName,
[in] BSTR bstrDirectoryName,
[in] BSTR bstrDBUserName,
[in] BSTR bstrDBPassword,
[in] BSTR bstrSuperDSPassword,
[in] BOOLEAN fUseMemSecurity
);

Parameters

bstrFileName

the filesystem path to the access database. All relative paths are from the c:\winnt\system32 directory.

bstrDirectoryName

the top level name of the directory. (.eg. "MyCompany" names the directory and the distinguished name becomes "o=MyCompany" in the directory.)

bstrDBUserName

not used currently.

bstrDBPassword

not used currently.

bstrSuperDSPassword

the password to set for the Directory administrator. This password must be set up in a special manner. The username in the directory service is always "administrator".

fUseMemSecurity

a flag specifying whether the LDAP service using this database as a backend will provide user authentication services to a Membership virtual server. 0=false, 1=True

Return Value

a standard HRESULT value

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set DSConfig = ObjCreator.CreateObjAuth("MemAdmin.DSConfig.1")
Filename="inetsvr\myldapdb.mdb"
DirName="company1"
DBUserName=""
DBUserPass=" "
DBSuperPass="superpass"
fUseMembershipSecurity=1 ' true
call DSConfig.CreateJetDB(Filename, DirName, DBUserName, DBUserPass, DBSuperPass, fUseMembershipSecurity)
If Err.Number <> 0 Then
  WScript.Echo "Error creating access database: " & Err.Description
End If


Interface ISetupStore CreatePartition Method

CreatePartition Method

This method sets up a necessary tables and configuration information in a target server and database when partitioning a logical directory container across multiple SQL servers and databases.

IDL Definition

HRESULT CreatePartition(
[in] BSTR bstrServerName,
[in] BSTR bstrDatabaseName,
[in] BSTR bstrDBUserName,
[in] BSTR bstrDBPassword
);

Parameters

bstrServerName

a name for the computer hosting the SQL server for this partition.

bstrDatabaseName

the name of the database to use for the partition.

bstrDBUserName

the username presented when authenticating to the SQL server.

bstrDBPassword

the password presented when authenticating to the SQL server.

Return Value

a standard HRESULT value

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set DSConfig = ObjCreator.CreateObjAuth("MemAdmin.DSConfig.1")
DBUser="sa"
DBPass="password-here"
Database="some-database"
Server="someserver"
call DSConfig.CreatePartition(Server,Database,DBUser,DBPass)
If Err.Number <> 0 Then
  WScript.Echo "Error creating partition: " & Err.Description
End If


Interface ISetupStore SetDirectoryPropertiesPage Method

SetDirectoryPropertiesPage Method

This method updates the meta-base information for a given LDAP server instance. The realm and the optional DN Prefix are added.

HRESULT SetDirectoryPropertiesPage(
[in] long lInstanceId,
[in] BSTR szRealm,
[in] BSTR szDnPrefix
);

Parameters

lInstanceId

the LDAP server instance identifier.

szRealm

the Realm name of the directory service.

szDnPrefix

the prefix to use when constructing the full distinguished name.

Return Values

a standard HRESULT value

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set DSConfig = ObjCreator.CreateObjAuth("MemAdmin.DSConfig.1")
call DSConfig.SetDirectoryPropertiesPage(1,"somecompany","o=companies")


Interface ISetupStore ValidateJetFileName Method

ValidateJetFileName Method

This method performs file existence verifications. It checks to see if a file specified by name exists, and returns a TRUE/FALSE value depending on the value passed as the second argument.

IDL Definition

HRESULT ValidateJetFileName(
[in] BSTR bstrFileName,
[in] BOOL fWantNew,
[out, retval] BOOL *pfValid
);

Parameters

bstrFileName

the full or relative path to the file. All relative names are from the c:\winnt\system32 directory. (e.g. "mydb.mdb" -> "c:\winnt\system32\mydb.mdb"

fWantNew

a flag specifying the intent of the validation check. If fWantNew is TRUE (1), then the returned BOOL will indicate FALSE if any file already exists by that name. If fWantNew is FALSE, then the returned BOOL will return TRUE if a file by that name exits, and FALSE otherwise.

pfValid

on return, the address of a BOOL variable. (TRUE/FALSE)

Return Values

a standard HRESULT.

Remarks

This method does not check to see whether the file specified is an access database or not. It simply checks to see if the file exists.

The matrix of possible BOOL values "returned" (i.e. the address of the BOOL contained in the third argument on return) is listed below.

fWantNew (second argument) | File by that name already exists? | Returned BOOL variable address contains
TRUE | yes | FALSE
TRUE | no | TRUE
FALSE | yes | TRUE
FALSE | no | FALSE

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set DSConfig = ObjCreator.CreateObjAuth("MemAdmin.DSConfig.1")
fWantNew=TRUE
Filename="c:\databases\db1.mdb"
if DSConfig.ValidateJetFilename(Filename,fWantNew) Then
  DSConfig.CreateJetDB(…)
Else
  WScript.Echo "Name conflict encountered. DB not created"
End If


Interface ISetupStore GenerateJetFileName Method

GenerateJetFileName Method

This method can be used to automatically generate a filename for an access database that does not conflict with others. The names are all of the form "c:\winnt\system32\inetsvr\mpinstX.mdb" where "X" is a number. The idea here is to correlate the instance number for the LDAP server using the access database with the name of the database itself. Read mpinst3.mdb as "Membership and Personalization for LDAP instance 3."

IDL Definition

HRESULT GenerateJetFileName(
[in] DWORD dwID,
[out, retval] BSTR *pbstrFileName
);

Parameters

dwID

the identifier to attempt to append to the "mpinst" prefix in the database name. If the number conflicts with another database name, the next possible value is added, and that filename is returned.

pbstrFileName

on return, the address of a BSTR variable containing the generated filename.

Return Values

a standard HRESULT value

Remarks

The argument to this method is the "suggested" id for the name. If we are setting up LDAP instance number 3, we would send 3 as the argument. Filename clashed permitting, we would receive "c:\winnt\system32\inetsvr\mpinst3.mdb" from the method. However, if this file already exists, we would receive the next name available in the sequence. That is, if all numbers up to 6 are used (mpinst1.mdb … mpinst6.mdb") are used, the method would return "c:\winnt\system32\inetsvr\mpinst7.mdb"

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set DSConfig = ObjCreator.CreateObjAuth("MemAdmin.DSConfig.1")
Filename = DSconfig.GenerateJetFilename(3) ' hope to use 3

DirName="company1"
DBUserName="ldapuser"
DBUserPass="passwordhere"
DBSuperPass="superpass"
fUseMembershipSecurity=1 ' true
call DSConfig.CreateJetDB(Filename, DirName, DBUserName, DBUserPass, DBSuperPass, fUseMembershipSecurity)
' go on to configure LDAP instance


Interface ISetupStore LocalPathToFullPath Method

LocalPathToFullPath Method

This method simply inserts "c:\winnt\system32\inetsvr\" at the beginning of the string passed as the first argument. If "somedb" is passed, the BSTR at the address returned as the second argument would contain "c:\winnt\system32\inetsvr\somedb".

IDL Definition

HRESULT LocalPathToFullPath(
[in] BSTR bstrLocal,
[out, retval] BSTR *pbstrFull
);

Parameters

bstrLocal

the string to insert the standard filesystem path "c:\winnt\system32\inetsvr" at the beginning of.

pbstrFull

on return, the address of a BSTR variable containing the standard full path.

Return Values

a standard HRESULT value

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set DSCfg = ObjCreator.CreateObjAuth("MemAdmin.DSConfig.1")
LName="mpinst5.mdb"
If DSCfg.ValidateJetFileName(DSCfg.localnametofullname(Lname),0) Then
  WScript.Echo "File " & Lname & " exists in standard location"
End If


Interface ISetupStore GetDriveInformation Method

GetDriveInformation Method

This method can be used to identify the type of drive a path refers to.

IDL Definition

HRESULT GetDriveInformation(
[in] BSTR bstrPath,
[out, retval] DWORD *pdwdt
);

Parameters

bstrPath

the path to interrogate information about.

pdwdt

on return, the address of a DWORD variable containing information about the drive. The values are the same as the Win32 API GetDriveType function.

Return Values

a standard HRESULT value

Example

Set ObjCreator = CreateObject("ObjCreator.ObjCreator.1")
Set DSConfig = ObjCreator.CreateObjAuth("MemAdmin.DSConfig.1")
DriveType = DSConfig.GetDriveInformation("f:\somedir")


CoClass TMAdmin

Class TMAdmin

Objects of this class can be used to configure information relating to Direct Mail virtual server instances.

COM Class Identification

Programmatic Identifier

MemAdmin.TMAdmin.1

CLSID

2DAA5B81-A873-11D0-8397-0080C7824F8A

COM Class Name

TMAdmin

Creating Instances of this Class

Programmers must use the special COM class ObjCreator.ObjCreator.1 to create instances of this class. Directly creating instances will render all methods inoperable.

Interfaces

The TMAdmin COM class exposes the dual interface ITMAdmin. Client applications may access the methods and properties through the COM interface ITMAdmin or through the dispinterface ITMAdmin via the IDispatch COM interface.

Security Issues

The account invoking methods on an instance of this class must have NT administrative privileges.


Interface ITMAdmin StartPackage Method

StartPackage

This method starts the mail package specified by the passed GUID value.

IDL Definition

HRESULT StartPackage([in] BSTR bstrGUID );

Parameters

BstrGUID

The package's GUID.

Return Values

A standard COM HRESULT.

Example


Interface ITMAdmin StopPackage Method

StopPackage

This method stops the package specified by the passed GUID value.

IDL Definition

HRESULT StopPackage ([in] BSTR bstrGUID );

Parameters

BstrGUID

The package's GUID.

Return Values

a standard HRESULT.


Interface ITMAdmin CancelPackage Method

CancelPackage

This method deletes the package specified by the passed GUID value.

IDL Definition

HRESULT CancelPackage ([in] BSTR bstrGUID );

Parameters

BstrGUID

The package's GUID value.

Return Values

a standard HRESULT value


Interface ITMAdmin ResetEnum Method

ResetEnum Method

This method resets the enumerator to the first package in the list.

IDL Definition

HRESULT ResetEnum([in]  long lVInst );

Parameters

lVInst

The virtual server instance identifier to enumerate packages for.

Return Values

a standard HRESULT value


Interface ITMAdmin NextPackages Method

NextPackages Method

This method returns a package from the enumeration. A programmer can call NextPackages continually, enumerating all packages, until the enumeration is exhausted.

IDL Definition

HRESULT NextPackages([out] VARIANT* pVar, [out]  long* pFetched );

Parameters

pVar

a VT_BSTR holding the address of the GUID value for the package.

pFetched

a VT_I4 variable indicating the number of the package in the sequence.

Return Values

a standard HRESULT value


Interface ITMAdmin CheckLDAPPassword Method

CheckLDAPPassword Method

This method attempts to bind a TCP/IP socket to the LDAP server instance running on the machine and port number specified. If successful, it presents the account name and password to attempt authentication with the LDAP server instance. This method uses the LDAP protocol when authenticating.

IDL Definition

HRESULT CheckLDAPPassword(
[in] BSTR bstrDS,
[in] BSTR bstrAcct,
[in] BSTR bstrPwd,
[in] unsigned long ulPort
);

Parameters

bstrDS

a name of the machine hosting the LDAP service. Must be a valid network name or DNS name. This name will be used to lookup an IP address when binding a TCP/IP socket to the machine hosting the LDAP server.

bstrAcct

the account name to present when authenticating with the LDAP server.

bstrPwd

the account password to present when authenticating with the LDAP server.

ulPort

the port to use when binding the TCP/IP socket to the machine specified by bstrDS.

Return Values

the HRESULT can have one of the following values:

#define Name | Description
S_OK | success.
TMAIL_E_CONNECT_FAILED | a TCP/IP connection could not be established with the target machine.
TMAIL_E_LOGIN_FAILED | a connection was established, but the server refused the credentials.


Interface ITMAdmin CheckSMTPServer Method

CheckSMTPServer Method

This method attempts to bind a TCP/IP socket to the SMTP server port 25 on the machine specified. If successful, it immediately closes the socket. Use this method to verify the connectivity to an SMTP server before starting a mailing package.

IDL Definition

HRESULT CheckSMTPServer([in] BSTR bstrSMTP);

Parameters

bstrSMTP

the name of the machine hosting the SMTP server. The name must be a valid DNS name for the machine. This name is used to do an IP address lookup when creating the TCP/IP socket connection to the server. The well-known SMTP port 25 is used when binding the socket.

Return Value

the HRESULT returned can have one of the following values:

#define Name | Description
S_OK | success.
E_INVALIDARG | the name passed could not be resolved to a valid IP address..
E_OUTOFMEMORY | an error occurred during a memory initialization routine. The system has run out of memory..
TMAIL_E_CONNECT_FAILED | a TCP/IP connection could not be established with the specified machine.


Interface ITMAdmin CheckPOP3Password Method

CheckPOP3Password Method

This method attempts to bind a TCP/IP socket to the POP3 server port 110 on the machine specified. If successful, it attempts to properly authenticate using the username and password specified. It then closes the socket. Use this method to check the connectivity to the POP3 server before starting a mailing package.

IDL Definition

HRESULT CheckPOP3Password(
[in] BSTR bstrPOP3,
[in] BSTR bstrAcct,
[in] BSTR bstrPwd
);

Parameters

bstrPOP3

the name of the machine hosting the POP3 server. This name must be a valid DNS name for a machine on the network. The name is resolved to an IP address which is used to bind a TCP/IP socket to that machine using the default POP3 port 110.

bstrAcct

the USER value to present when authenticating.

bstrPwd

the PASS value to present when authenticating.

Return Values

the HRESULT can have one of the following values:

#define Name | Description
S_OK | success.
TMAIL_E_CONNECT_FAILED | a TCP/IP connection could not be established with the target machine.


Interface ITMAdmin CheckKeywords Method

CheckKeywords Method

This method will check the keywords in the directory service.

IDL Definition

HRESULT CheckKeywords(
[in] BSTR bstrNDRKeys,
[in] BSTR bstrUnsubKeys,
[in] BSTR bstrRcptKeys
);

Parameters

bstrGUID

bstrUnsubKeys

bstrRcptKeys

Return Values

a standard HRESULT value


Interface ITMAdmin CheckPath Method

CheckPath Method

This method attempts to create the directory specified by the value passed. If successful, it removes the directory. Use this method to make sure the directory does not already exist before starting a mail package.

IDL Definition

HRESULT CheckPath([in] BSTR bstrPath);

Parameters

BstrPath

The filesystem path to the directory.

Return Values

a standard HRESULT that can have the following special values:

#define name | description
S_OK | path is valid.
E_FAIL | unspecified error
ERROR_ALREADY_EXISTS | the directory already exists.


Interface ITMAdmin CreateInstance Method

CreateInstance Method

This method creates an instance of the Targetted Mail server and assigns the passed integer as the associated instance identifier.

IDL Definition

HRESULT CreateInstance([in] long lInst);

Parameters

lInst

The instance identifier to assign this instance.

Return Values

a standard HRESULT value


Interface ITMAdmin DeleteInstance Method

DeleteInstance Method

This method deletes the specified server instance.

IDL Definition

HRESULT DeleteInstance([in] long lInst);

Parameters

lInst

The instance identifier indicating the instance to delete.

Return Values

a standard HRESULT value


Interface ITMAdmin StartInstance Method

StartInstance Method

This method starts the specified server instance.

IDL Definition

HRESULT StartInstance([in] long lInst);

Parameters

lInst

the instance identifier indicating the instance to start.

Return Values

a standard HRESULT value


Interface ITMAdmin StopInstance Method

StopInstance Method

This method stops the indicated server instance.

IDL Definition

HRESULT StopInstance([in] long lInst);

Parameters

lInst

the instance identifier indicating the instance to stop.

Return Values

a standard HRESULT value


Interface ITMAdmin GetCurrentStatus Method

GetCurrentStatus Method

This method returns the status of the indicated Targetted Mail server instance.

IDL Definition

HRESULT GetCurrentStatus(
[in] long lInst,
[out] VARIANT *pStatus /* VT_I4 */
);

Parameters

lInst

the instance identifier indicating the instance to check.

pStatus

on return, an integer specifying the status. The table below enumerates the possible return values

Typedef | Meaning
VINST_STOPPED = 0 | the instance is not running.
VINST_PAUSED = 1 | the instance is idling.
VINST_STARTED = 2 | the instance is running.

Return Values

a standard HRESULT value


Interface ITMAdmin SaveConfig Method

SaveConfig Method

This method commits the current configuration in memory to the metabase.

IDL Definition

HRESULT SaveConfig();

Return Values

a standard HRESULT value


Interface ITMAdmin GetPeakMessageRate Method

GetPeakMessageRate Method

This method returns the currently configured peak message delivery rate.

IDL Definition

HRESULT GetPeakMessageRate(
[out] VARIANT *rate,
[out] VARIANT *time_start,
[out] VARIANT *time_stop
);

Parameters

rate

the peak message rate in units of message per second

time_start

the time the delivery will begin

time_stop

the time the delivery will stop

Return Values

a standard HRESULT values


Interface ITMAdmin SetPeakMessageRate Method

SetPeakMessageRate Method

This method can be used to configure the peak message delivery rate for a specified server instance.

IDL Definition

HRESULT SetPeakMessageRate(
[in] long rate,
[in] long time_start,
[in] long time_stop
);

Parameters

rate

the peak message rate in units of messages per second

time_start

the time the delivery will begin

time_stop

the time the delivery will stop

Return Values

a standard HRESULT value

Remarks


Interface ITMAdmin CurrentInstance Property

CurrentInstance Property

This property is used to indicate the current Targetted Mail server instance. All configuration change subsequently made are applied to this instance.

IDL Definition

[propget]
HRESULT CurrentInstance([out, retval] VARIANT *pvVal );
[propput]
HRESULT CurrentInstance([in] long newVal);

Type

LONG


Interface ITMAdmin DSName Property

DSName Property

This property specifies the directory service name.

IDL Definition

[propget]
HRESULT DSName([out, retval] VARIANT *pVal /* VT_BSTR */);
[propput]
HRESULT DSName([in] BSTR newVal);

Type

BSTR


Interface ITMAdmin LDAPPort Property

LDAPPort Property

This property specifies the TCP/IP port number for the LDAP service.

IDL Definition

[propget]
HRESULT LDAPPort([out, retval] VARIANT *pVal /* VT_I4 */);
[propput]
HRESULT LDAPPort([in] unsigned long newVal);

Type

LONG


Interface ITMAdmin DSAccount Property

DSAccount Property

This property specifies the account name used to authenticate to the LDAP service.

IDL Definition

[propget]
HRESULT DSAccount([out, retval] VARIANT *pVal /* VT_BSTR */);
[propput]
HRESULT DSAccount([in] BSTR newVal);

Type

BSTR


Interface ITMAdmin DSPassword Property

DSPassword Property

This property specifies the password to use when authenticating with the LDAP service.

IDL Definition

[propget]
HRESULT DSPassword([out, retval] VARIANT *pVal /* VT_BSTR */);
[propput]
HRESULT DSPassword([in] BSTR newVal);

Type

BSTR


Interface ITMAdmin SMTPServer Property

SMTPServer Property

This property specifies the DNS name of the server hosting the SMTP service to use.

IDL Definition

[propget]
HRESULT SMTPServer([out, retval] VARIANT *pVal /* VT_BSTR */);
[propput]
HRESULT SMTPServer([in] BSTR newVal);

Type

BSTR


Interface ITMAdmin POP3Server Property

POP3Server Property

This property specifies the DNS name of the server hosting the POP3 service to use.

IDL Definition

[propget]
HRESULT POP3Server([out, retval]  VARIANT *pVal   /* VT_BSTR */ );
[propput]
HRESULT POP3Server( [in] BSTR  newVal );

Type

BSTR


Interface ITMAdmin POP3Account Property

POP3Account Property

This property specifies the account name to present when authenticating with the POP3 service.

IDL Definition

[propget]
HRESULT POP3Account( [out, retval]  VARIANT  *pVal  /* VT_BSTR */ );
[propput]
HRESULT POP3Account( [in]  BSTR  newVal );

Type

BSTR


Interface ITMAdmin POP3Password

POP3Password Property

This property specifies the password to present when authenticating with the POP3 service.

IDL Definition

[propget]
HRESULT POP3Password( [out, retval]  VARIANT  *pVal /* VT_BSTR */ );
[propput]
HRESULT POP3Password( [in]  BSTR  newVal );

Type

BSTR


Interface ITMAdmin NDRThreshold Property

NDRThreshold Property

This property specifies the number of failed deliveries can occur before the mailer stops attempting delivery. (NDR is an acronym for Non-Delivered-Response )

IDL Definition

[propget]
HRESULT NDRThreshold([out, retval] VARIANT *pVal /*VT_I4*/);
[propput]
HRESULT NDRThreshold([in] long newVal);

Type

LONG

Default

3


Interface ITMAdmin NDRSubjectKeywords Property

NDRSubjectKeywords Property

This property is a comma-separated list of words used to identify subject lines in mail items that were undeliverable.

IDL Definition

[propget]
HRESULT NDRSubjectKeywords( [out, retval]  VARIANT  *pVal  /*VT_BSTR*/ );
[propput]
HRESULT NDRSubjectKeywords( [in]  BSTR  newVal);

Type

BSTR

Default

"Undeliverable, nondeliverable, Nondelivery, Unable, Cannot, Return"


Interface ITMAdmin NDRRecipientKeywords Property

NDRRecipientKeywords Property

This property is a comma-separated list of words used when identifying the recipient line in mail items that were undeliverable.

IDL Definition

[propget]
HRESULT NDRRecipientKeywords( [out, retval]  VARIANT  *pVal /*VT_BSTR*/);
[propput]
HRESULT NDRRecipientKeywords( [in]  BSTR  newVal );

Type

BSTR

Default

" To, Delivery-To"


Interface ITMAdmin UnSubKeywords Property

UnSubKeywords Property

This property is a comma-separated list of words used to identify "unsubscribe" directives from users in the body of mail messages.

IDL Definition

[propget]
HRESULT UnSubKeywords([out, retval] VARIANT *pVal /*VT_BSTR*/);
[propput]
HRESULT UnSubKeywords([in] BSTR newVal);

Type

BSTR

Default

" Cancel, UnSubscribe"


Interface ITMAdmin LogPath Property

LogPath Property

This property specifies the filesystem path to the directory that the instance will write the log file for mailings.

IDL Definition

[propget]
HRESULT LogPath([out, retval] VARIANT *pVal /*VT_BSTR*/);
[propput]
HRESULT LogPath([in] BSTR newVal);

Type

BSTR


Interface ITMAdmin LogType Property

LogType Property

This property specifies the type of log to generate for mailings.

IDL Definition

[propget]
HRESULT LogType([out, retval] VARIANT *pVal /*VT_I4*/);
[propput]
HRESULT LogType([in] long newVal);

Type

LONG

Values

The statement below lists the typedef enum statement defining the possible values.

typedef enum tagLOGTYPE {
DAILY_LOG = 0,
WEEKLY_LOG = 1,
MONTHLY_LOG = 2,
SIZE_LIMITED = 3
} LOGTYPE;


Interface ITMAdmin LogFileName Property

LogFileName Property

This property specifies the log file name for this instance's mailings log.

IDL Definition

[propget, id(28), helpstring("property LogFileName")]
HRESULT LogFileName([out, retval] VARIANT *pVal /*VT_BSTR*/);


Interface ITMAdmin LogAutoNew Property

LogAutoNew Property

This property specifies whether new log files should automatically be created when the current one has reached a certain size. 0 = False, 1 = True

IDL Definition

[propget]
HRESULT LogAutoNew([out, retval] VARIANT *pVal /*VT_I4: */);
[propput]
HRESULT LogAutoNew([in] BOOL newVal);

Type

BOOL

Values

1=TRUE, 0=FALSE


Interface ITMAdmin LogSize Property

LogSize Property

This property specifies the maximum size, in megabytes, the mailings log file can reach before another file is started. This property is used only if the LogType property is set to SIZE_LIMITED.

IDL Definition

[propget]
HRESULT LogSize([out, retval] VARIANT *pVal /*VT_I4*/);
[propput]
HRESULT LogSize([in] long newVal);

Type

LONG


Interface ITMAdmin LogNDR Property

LogNDR Property

This property specifies whether to log undeliverable mailing attempts.

IDL Definition

[propget]
HRESULT LogNDR([out, retval] VARIANT *pVal /*VT_I4 */);
[propput]
HRESULT LogNDR([in] BOOL newVal);

Type

BOOL

Values

1=TRUE,0=FALSE


Interface ITMAdmin LogUnSub Property

LogUnSub Property

This property specifies whether to log unsubscribe messages received.

IDL Definition

[propget]
HRESULT LogUnSub([out, retval] VARIANT *pVal /*VT_I4: 1=TRUE,0=FALSE*/);
[propput]
HRESULT LogUnSub([in] BOOL newVal);

Type

BOOL

Values

1=TRUE,0=FALSE


Interface ITMAdmin AutoDeleteNDR Property

AutoDeleteNDR Property

This property specifies whether to delete non-deliverable returned messages after they are processed.

IDL Definition

[propget]
HRESULT AutoDeleteNDR([out, retval] VARIANT *pVal /* VT_I4 :  */);
[propput]
HRESULT AutoDeleteNDR([in] BOOL newVal);

Type

BOOL

Values

1=TRUE,0=FALSE


Interface ITMAdmin AutoDeleteUnSub Property

AutoDeleteUnSub Property

This property specifies whether to delete "unsubscribe" messages after they are processed.

IDL Definition

[propget]
HRESULT AutoDeleteUnSub([out, retval] VARIANT *pVal /* VT_I4: */);
[propput
HRESULT AutoDeleteUnSub([in] BOOL newVal);

Type

BOOL

Values

1=TRUE,0=FALSE


Interface ITMAdmin RestOfDayMessageRate Property

RestOfDayMessageRate Property

This property specifies the message delivery rate. The rate is expressed as the number of messages delivered per second. (e.g. 2 = 2 messages per second)

This property is global, and is thus set for all server instances.

IDL Definition

 [propget]
HRESULT RestOfDayMessageRate([out, retval] VARIANT *pvVal);
[propput]
HRESULT RestOfDayMessageRate([in] long newVal);

Type

LONG


CoClass UserObjects (Membership.UserObjects.1)

Class UserObjects

COM Class Identification

The following values identify this COM class. These values are set in the registry with the Site Server 3.0 product installation.

COM Class Logical Name

UserObjects

Programmatic Identifier

Membership.UserObjects.1

CLSID

77BD6B36-B1B5-11D0-BBD6-00C04FB615E5

Type Information

Type Library location

"c:\microsoft site server\bin\p&m\auo.dll"

IDL file

AUO.idl (comes with this SDK)

Type Library name

AUO 1.0 Type Library

Class Overview

This class defines a Component Object Model (COM) object that programmers and scripters can use to easily store and retrieve information about users.

AUO Providers

An object of this class relies on a set of configuration entries referred to as Active User Objects (AUO) providers to define the specific access details to information about users. When configuring the AUO, administrators supply an instance-unique AUO alias to identify the specific AUO provider configuration. Programmers and scripters may then access the targeted information using this alias.

Each AUO provider configuration is comprised of information used to bind to a specific COM object that implements the Active Directory Service Interfaces (ADSI). It is specifically through these COM objects that all management and transport of data occurs. In the simplest case, the AUO is simply a set of "helper" COM objects that assist programmers in gaining access to a particular ADSI implemented COM object with a minimum of fuss. Further, the ADSI interfaces define only general information about the expected behavior of ADSI implemented COM objects, allowing developers to implement the details in any fashion they so desire. The AUO system makes no assumptions about the actual implementations used COM objects that implement the ADSI interfaces. The AUO objects, specifically UserObjects and SchemaObjects, are strictly clients of the bound ADSI COM objects, or fetch and return interfaces on ADSI objects.

The Default Provider

The one provider definition that has special status is the default AUO provider. Programmers or scripts need not specify this provider in programs or scripts directly. Instead, they may interact with the UserObjects or SchemaObjects objects as if they were the corresponding ADSI object. However, if an interface on the actual ADSI object is required by an application, it can always be requested by the IUserObjects::GetObjectEx (or IADsContainer::GetObject implemented by the UserObjects object) method with the empty string "". This provider configuration normally points to user data in the appropriate Membership Directory service and works in conjunction with the Membership Server attribute or property cache to provide high-speed access and synchronization. The IADs and IADsContainer interface implemented by the UserObjects coclass provides this service only for the ADSI object specified by the configuration of the default AUO provider.

The Active Directory Service Interfaces (ADSI)

The UserObjects coclass relies on other COM objects that implement the Active Directory Service COM Interfaces (ADSI) for all connectivity to data stores. (I.e. directory services, databases, etc) As its name suggests, an instance of the UserObjects coclass acts as a collection of ADSI COM objects that implement ADSI interfaces and provide connectivity services. However, it also simultaneously masquerades as the ADSI object defined by the default AUO provider and the current user. All invocations made on the UserObject IADs interface are delegated to the actual ADSI COM object. If the Membership system is configured to have the AUO check the Membership service property cache, the Get/GetEx methods implemented on the UserObjects object first check there for a requested attribute. If this feature is disabled, the call goes directly to the ADSI object in a standard COM "delegation" fashion. If the user's ADSI object also is an ADSI container object, the IADsContainer interface implemented on the UserObjects coclass will delegate these calls as well.

Constructing the ADs Paths to the Objects

Example

A hypothetical example may help make these ideas concrete. Assume there are two directory service "containers" that store data about users. Assume the Suffix value is set to "1" for each AUO provider that defines the paths to user information in these databases. The ADsPathPrefix and Name of the corresponding AUO provider entries could be

Alias | ADsPathPrefix
"" | "LDAP://ldapsvr1:389/o=company1/ou=accounting"
"Secure" | "LDAP://ldapsvr1:443/o=company1/ou=401ks"

Note that the default AUO alias is specified by the "" alias. (I.e. the empty string)

Next assume a registered user with username "JohnS" (i.e. has REMOTE_USER="JohnS") requests an ASP page that uses the UserObjects object to personalize his 401k page. When the script programmer instructs the UserObjects object to fetch some properties from a directory, it binds the appropriate ADSI object by combining the two sets of information. Take the following ASP script example:

Hello <%= UserObjects.Get "givenName" %>, your current 401k balance is
<%= UserObjects.GetObjectEx("Secure").Get("Balance") %>.

In the first call, the UserObjects object constructs the complete ADs path from the ADsPathPrefix from default provider and the value of REMOTE_USER as follows:

ADsPath 1

"LDAP://ldasvr1:389/o=company1/ou=accounting" + "/cn=JohnS"

When the script parser hits the line

UserObjects.Get "givenName"

the script invokes the Get method on the class UserObjects object's IADs interface. In this case, the Get method in the UserObjects object requests the "givenName" attribute from the Membership virtual server cache first. If not found there, it then binds the ADSI object shown above in ADsPath 1 and passes on the Get invocation to the actual ADSI object IADs interface. In either case, the attribute value is returned or an error is raised.

In the second call, the UserObjects object constructs the complete using the AUO entry with the alias of "Secure" and the current username as follows:

ADsPath 2

"LDAP://ldapsvr1:443/o=company/ou=401k" + "/cn=JohnS"

In this case, we must explicitly ask for this ADSI object via the GetObjectEx method using the alias "Secure." This method simply returns the IDispatch interface to the ADSI object bound by the above ADs Path 2.

ADSI Security Issues

ADSI implements a set of security features to restrict access to information by unauthorized accounts stored in directory services. Essentially, how one goes about binding to an ADSI object determines what type of credentials are presented to the underlying directory service. A complete discussion of ADSI security features is beyond the scope of this reference. For a complete discussion of ADSI related security issues, see the ADSI 2.0 SDK documentation found in the Platform SDK under Network and Distributed Services.

The UserObjects class implements the following checklist when determining which credentials to present when binding to ADSI objects. The list is in order of precedence.

First and foremost,

  • If the AUO provider has the BindAsUsername value currently set, the UserObjects object binds ADSI objects using these values. The BindAsUsername and BindAsPassword values can be set for the AUO entry permanently with an instance of the AuoConfig class or with the IUserObjects::BindAs method at runtime.

  • That not being the case,

  • If the programmer uses the SetUserName method to change the username within the UserObjects object at runtime, it subsequently binds to all ADSI objects anonymously. (i.e. no credentials are presented when binding) Note that this only applies if the initial condition was not met. If the BindAsUsername value is set for the provider, then these values are used to bind irrespective of whether SetUserName has been called or not. This allows programmers and scripters to use the "auto user-create" feature of the AUO within a secured directory service.

  • Otherwise, the UserObjects object uses the current username and password as credentials to bind to ADSI objects.

When ADSI Objects are Bound

The actual ADSI objects are not bound until a method is explicitly invoked on either the IADs or IADsContainer interfaces of a UserObjects object. This is often referred to a "lazy" binding. It is best to think of it as "bound when requested by a method."

Creating Instances of this Class

Normally, a web site programmer would have a built-in ASP Server-class object create the instance of the Membership.UserObjects class: (VBScript example)

<% Set UserObject = Server.CreateObject(“Membership.UserObjects”)

However, this class is a bona fide COM object, and programmers can create instances in any context using the normal COM library methods.


CoClass UserObjects Interface IDispatch

Interface IDispatch

A Note about IDispatch

When programmers request the storage and retrieval of properties using the IADs interface method through the IDispatch interface on an instance of the UserObjects class or an ADSI object, they can use a special syntax. Normally, properties and methods defined for an object must be implemented before compile time. That is, if an object has a public property called "Name" then the corresponding methods to get and put the value of this property are implemented as part of the coding of the object before it is compiled. The ADSI objects, (and the UserObjects object), however, support the notion of dynamic properties through the IDispatch interface. What this means is that programmers can request properties in the object that can change dynamically at runtime. A programmer can bypass using the "Get/GetEx" and "Set/SetEx" methods, which are static, and simply refer to the desired property as if it belonged to the object. For VBScript script programmers, this presents a much less cumbersome syntax, since all method and property calls act via the IDispatch interface.

Example:

Static sytax (clear)

UserObjects.Get("givenName")

Dynamic property syntax (may be confusing, but is easy)

UserObjects.givenName

Both of these calls would return the same property from the directory service.

CAUTION When using the dynamic property syntax, one must be careful to avoid name collisions with bona fide properties of the object. These "real" properties of the object always take precedence over data fetched from a directory service. For example, any directory service properties with the names "GUID," "Parent," or "Name" would conflict since these names are used to store information about the object itself, and must be returned when requested. In such cases, one must use the "Get" and "Set" methods for these properties.


CoClass UserObjects Interface IADs

Interface IADs

The UserObjects class implements the IADs interface in a slightly difference way than a bona file ADSI object. The properties and methods below can be used to access the user's ADSI object as defined by the default AUO entry only. It therefore can be said that to a client application, the UserObjects object contains the IADs interface on the user's ADSI object as it is defined for the default AUO entry. However, using the interface on the UserObjects object has some extra advantages:

  1. If configured to do so, the various "Get/GetEx" methods first check the Membership server instance cache for the properties before forwarding the call to the actual ADSI object. This can increase performance tremendously.

  2. The IADs interface exposed on the UserObjects class can be used immediately to interact with the ADSI object defined for the user in the default AUO entry. No extra call to GetObject or GetObjectEx is required.

Properties

Property | Description
Name | Gets the object’s relative name as it appears in the underlying directory service.
Class | Gets the object's schema class name.
GUID | Gets the object's globally unique identifier.
ADsPath | Gets the object's ADsPath. This path uniquely identifies the object from all others.
Parent | Gets the ADsPath to the object that contains this object. (its parent object)
Schema | Gets the ADsPath to the object that defines the schema for this object.

Methods

Method | Description
GetInfo | Loads or reloads the data from the directory service into the ADSI object. This method is implicitly called if a call to Get is encountered before Getinfo.
GetInfoEx | Loads or reloads specific properties from the directory service database into the ADSI object.
SetInfo | Commits the data in the ADSI object to the directory service database.
Get | Gets the value or values of the property specified by name. The method will first check the Membership Server instance property cache if configured to do so.
GetEx | Gets the value of the property specified by name. The method will check the Membership Server instance cache is configured to do so.
Put | Sets the value for the property specified
PutEx | Sets the value for the property specified

Remarks

The properties stored in the ADSI object can be accessed through IDispatch interfaces on ADSI objects using a special syntax. This syntax is also referred to as "direct syntax." In this case, one can refer to the property names as if they were real properties of the ADSI object.

<%
Set IUserObjects = Server.CreateObject("Membership.UserObjects
name = IUserObjects.GivenName
%>

The other way to access this property would be through the Get method as shown below.

<%
    Set IUserObjects = Server.CreateObject("Membership.UserObjects")
    name = IUserObjects.Get "givenName"
 %>

Note that objects of class UserObjects as well as ADSI objects support this syntax.


CoClass UserObjects Interface IADsContainer

Interface IADsContainer

The IADsContainer interface implementation for the UserObjects class allows a programmer to access the various ADSI objects for the current user. This implementation differs from those on bona fide ADSI objects in that they deal with the objects defined by the AUO entries for the current Membership server instance. For example, if the AUO entries for Membership server instance 3 are the default, "container1" and "container2", the Count property would return 3 and the enumeration would return interfaces on the corresponding user ADSI objects defined by these entries. It could be said that the UserObjects object is a container of the user's ADSI objects as defined by the AUO entries for the server instance. It aggregates the IDispatch interfaces on these objects. Hence the name UserObjects.

Properties

Property | Description
Count | Gets the number of ADSI objects defined by the AUO entries for this Membership virtual server instance. (e.g. if there are 3 AUO entries, this method returns "3")
_NewEnum | Gets an interface on an enumerator object that can be used to enumerate the ADSI objects defined by the AUO entries for this Membership virtual server instance.
Filters | Not implemented by this class
Hints | Not implemented by this class

Methods

Method | Description
GetObject | Gets an interface on a named ADSI object. In this case, the names can refer to a defined AUO entry name. If the name is not defined as an AUO entry, the method will attempt to invoke this method on the ADSI object defined by the default AUO entry as if it were a "container" ADSI object.
Create | Not implemented by this class
Delete | Not implemented by this class
CopyHere | Not implemented by this class
MoveHere | Not implemented by this class


Interface IUserObjects BindAs Method

BindAs Method

This method sets the credentials used when binding to the ADSI object defined by the AUO entry specified.

IDL Definition

HRESULT BindAs(
BSTR bszEntryName,
BSTR bszUserName,
BSTR bszPassword
);

Parameters

bszEntryName

The name of the AUO entry to change binding credentials on.

bszUserName

The distinguished name to use when binding.

bszPassword

The password to use when binding.

Return Value

A standard HRESULT value.

Remarks

The Init method must be called before BindAs. This loads the entries defined for a particular Membership virtual server instance.

The distinguished name (DN) is the full path to the user as it appears in the underlying directory service. (e.g. in an LDAP service: /o=company/ou=admingroup/cn=John")

This method can only be invoked prior to the binding of any ADSI objects. Once an ADSI object has been bound by the object, the binding credentials cannot be changed, and any further invocations of the BindAs method will fail.

This method only changes the binding credentials for the lifetime of the class UserObjects object. To permanently change binding credentials for an AUO entry, see

Example

<% Set UserObjects = Server.CreateObject(“Membership.UserObjects”)
   UserObjects.BindAs(“o=company/ou=public/cn=publicuser”,”password”)
%>

See Also

Class AuoConfig


Interface IUserObjects Interface GetObjectAsUser Method

GetObjectAsUser Method

This method attempts to bind a specified ADSI object, and if successful, returns the IDispatch address of the object. The authentication procedure is the same as normally used by the class UserObjects object when binding ADSI objects.

IDL Definition

HRESULT GetObjectAsUser(
[in]         BSTR        bszADsPath,
[out,retval] IDispatch** ppObject
);

Parameters

bszADsPath

The ADSI path to an object.

ppObject

Upon return, the IDispatch interface to the ADSI object.

Return Value

a standard HRESULT value

Remarks

This method differs from IADsContainer GetObject or IUserObjects GetObjectEx in that it returns any accessible ADSI object, rather than an object located in one of the containers defined by the AUO entries.

Example

VBScript in an ASP page

<% Set IUserObjects = Server.CreateObject(“Membership.UserObjects”)
   Set IContainer =    IUserObjects.GetObjectAsUser(“LDAP://someserver/ou=groups/o=company”)
   For Each IItem in IContainer
     Response.write “Item’s Name: “ & IItem.Name & “<br>”
     Response.write “Item’s ADsPath: “ & IItem.AdsPath & “<br>”
   Next


Interface IUserObjects GetObjectEx Method

GetObjectEx Method

This method returns the IDispatch interface to the user's ADSI object as defined by the specified AUO entry name passed as an argument.

IDL Definition

HRESULT GetObjectEx(
[in]         BSTR         bszEntryName,
[out,retval] IDispatch**  ppEntry
);

Parameters

bszEntryName

The name of the AUO entry. (the AUO alias)

ppEntry

Upon return, the IDispatch interface to the ADSI object.

Return Value

a standard HRESULT value

Remarks

Since each Membership virtual server instance has its own set of AUO entries defined, the Init method must be called before GetObjectEx.

GetObjectEx is marked in its IDL definition as [id(DISPID_VALUE)]. This means that this method is the default method for the object. If no method is specifies when IDispatch::Invoke is called, the object defaults to invoking GetObjectEx. This is nice for languages such as VBscript as a shorthand to avoid extra typing:

UserObject("this") is the same as UserObjects.GetObjectEx("this"). That is, they invoke the same method using "this" as an argument.

Example

VBScript in an ASP Page

<%
 Set IUserObjects = Server.CreateObject("Membership.UserObjects")
 Set IadsiObj = IUserObjects("AUOAlias")
 Response.write "Hello " & IadsObj.givenName
%>

In this example, the givenName user propert is fetched from the user ADSI object using the configuration information for the AUO entry named "AUOAlias". Note also that one need not explicitly type out GetObjectEx as it is the default method for the dispinterface for IUserObjects.


Interface IUserObjects Init Method

Init Method

The Init method is used to initialize the object with a username and an Internet Information Server virtual server instance identifier.

IDL Definition

HRESULT Init(
BSTR bszIISVirtId,
BSTR bszUserName
);

Parameters

bszIISVirtId

An Internet Information Server virtual server instance identifier

bszUserName

The user name (from REMOTE_USER variable)

Return Value

a standard HRESULT value

Remarks

The bszIISVirtId is used to map to the corresponding Membership virtual server instance, and hence a set of AUO entries.

The bszUserName is used to complete the ADs path to the user's directory information when ADSI objects are requested of the UserObjects object.

The Init method is invoked automatically within in the OnStartPage method which is always invoked on the object when the Server dispinterface method CreateObject is used to create the instance. The IIS virtual server instance identifier (INSTANCE_ID) and the current username (REMOTE_USER) are fetched from the Request object to be sent as arguments.

In a non-ASP environment, one must explicitly call the Init method.

Example

VBScript in an ASP page

<% Set IUserObjects = CreateObject("Membership.UserObjects")

'  Note here that the Server dispinterface (object) was not used to create the object
'  In this case, the OnStartPage method was not called, so we must do so

Username = Request.ServerVariables("REMOTE_USER")
IISVirtId = Request.ServerVariables("INSTANCE_ID")
call IUserObjects.Init(IISVirtId,Username)

See Also

OnStartPage Method


Interface IUserObjects OnStartPage Method

OnStartPage Method

The OnStartPage method is an implementation of the standard server-side method invoked by the ASP scripting context on any COM objects created using the built-in ASP Server dispinterface CreateObject method. In this case, the OnStartPage method invokes the IUserObject::Init method on the UserObjects object, passing the virtual server instance identifier and the username found in the REMOTE_USER variable sent with the request.


Interface IUserObjects SetUserName Method

SetUserName Method

The SetUserName method sets the username in the object.

IDL Definition

HRESULT SetUserName(  BSTR  bszUserName ) ;

Parameters

bszUserName

The new username.

Return Value

a standard HRESULT value

Remarks

SetUserName may be called at any time before any ADSI objects have been bound by the UserObjects object. Once an ADSI object has been bound, the SetUserName can no longer be used.

Example

VBscript in an ASP page

<% Set IUserObjects = Server.CreateObject("Membership.UserObjects")
IUserObjects.SetUserName "KellyC"
Response.write “User Object ADs Path: “ & IUserObjects.AdsPath
Response.Write “Given Name property:  “ & IUserObjects.Get(“givenName”)

In the case above, the ADSI user object with relative name “cn=KellyC” in the default AUO entry would be used, not the one sent with the HTTP request. The output would be, depending on the default AUO entry ADsPathPrefix and the properties stored in the user object:

User Object ADs Path: LDAP://someserver/o=so,ecompnay/ou=members/cn=KellyC
Given Name property:  Kelly


CoClass VerifUsr

Class VerifUsr

The VerifUsr COM class is used in an ASP environment to issue appropriate Membership server related cookies to a user. Objects of this class should be used in the following situations:

  • For issuance of appropriate cookies during the creation or migration of users from anonymous cookie accounts to user accounts.

  • When the Membership server is configured to perform authentication service and the web site is configured to accept "forms authentication." In this case, an instance of this class must be used to perform the verification of the username and password.

  • For issuance of timestamp cookies to force a reload of a user's properties from the directory service into the Membership user property cache.

  • Hashing and storage of a user's certificate. (if desired)

Objects of this class will only work correctly if in an ASP scripting environment.

COM Class Identification

Programmatic Identifier

Membership.VerifUsr.1

CLSID

C4F9C9CC-C33E-11D0-B8A0-00C04FB616C7

COM Class Name

verifusr

Type Information

The complete Interface Definition Language (IDL) definition of this class is contained in the file <sdk_install_root>\include\verifusr.idl

The type library for this class is available as a resource in the verifusr.dll dynamic link library (DLL). The default location of this DLL is c:\microsoft site server\bin\p&m\verifusr.dll.

Interfaces

The verifusr COM class exposes the single dual custom COM interface Iverifusr. Thus, the methods and properties are accessible through the COM interface, or through the dispinterface Iverifusr. (IDispatch)

It should be noted here that instance of the Verifusr class require the ASP scripting context interfaces and thus the ASP environment. Because of this, script languages used within ASP pages will be the primary clients for objects of this class.


Interface IVerifUsr OnStartPage Method

OnStartPage Method

The OnStartPage method is invoked as a call-back method by the ASP scripting context when an instance of the VerifUsr class is created via the intrinsic Server object method CreateObject. One need not explicitly call this method.

The method gathers the necessary interfaces internally to prepare for additional method invocations.

Example

VBScript in an ASP page

Set IVerifUsr = Server.CreateObject("Membership.Verifusr.1")

Here the OnStartPage method is invoked automatically by the ASP scripting context.


Interface IVerifUsr OnEndPage Method

OnEndPage Method

The OnEndPage method is invoked as a call-back method by the ASP scripting context when an instance of the VerifUsr class is created via the intrinsic Server object method CreateObject. One need not explicitly call this method. It performs any memory de-allocations and interface releases required.


Interface IVerifUsr VerifyCredentials Method

VerifyCredentials Method

This method verifies that the passed arguments bszUsername and bszPassword are correct by contacting the appropriate Membership virtual server instance. If they are correct, an appropriate cookie is issued to the user, and the passed URL argument is returned. If the username and password are not valid, no cookie is issued, and the URL returned points to a predefined registration page.

IDL Definition

HRESULT VerifyCredentials(
BSTR bszUserName,
BSTR bszPassword,
BSTR bszURL,
[out, retval] BSTR * pbstrUrlToRedirect
);

Parameters

bszUserName

The username to check along with a password

bszPassword

The password to check along with a username

bszURL

The URL to send the user if the presented credentials are valid.

pbstrUrlToRedirect

On return, the URL to redirect the client. This value is dependent on whether the client's presented credentials were valid or not. If the credentials are valid, the bszURL value is returned. Otherwise, a predefined error/registration URL is returned.

Return Values

A standard HRESULT value

Remarks

This method should be used in ASP pages for IIS server instances mapped to Authentication server instances that have "Membership" authentication set, and is most useful when "Forms Authentication" is being used. One then uses this method to perform the verification of credentials. Once the user has successfully provided authentic credentials to the VerifyCredentials method, the necessary cookies are sent in the response that then allow the user to access content.

In any case, a user must have the necessary cookies issued to proceed to content without being sent back to the login page.

Example

VBScript in an ASP page

Assume ”forms authentication" is being used for this IIS server. Further assume the items Username and Password are collected through an HTML form that has it's ACTION attribute set to an ASP script with the following code included. A "success" target URL is set up in the form if login is successful, usually as a "hidden" variable in the form.

<%
Name  = Request("UserName")
Password = Request("Password")
URL = Request("SuccessURL")
Set IVerifUsr = Server.CreateObject("Membership.VerifUsr.1")
If IVerifUser.
returnedURL = oVerifUsr.VerifyCredentials(Name,Password,URL)
Response.Redirect returnedURL
%>


Interface IVerifUsr IssueCookieToOldUser Method

IssueCookieToOldUser Method

This method issues the necessary cookies to a new registered user account that has been migrated from a previous anonymous cookie account. The GUID value for the new registered account will be the same as for the old cookies account.

IDL Definition

HRESULT IssueCookieToOldUser(BSTR bszUserName);

Parameters

bszUserName

The new username to issue the old cookie to

Return Values

a standard HRESULT value

Remarks

When migrating users, make sure to actually move the account information to its new location before invoking IssueCookieToOldUser. The GUID value will be fetched for the user using the new account information.

Example

This example migrates an anonymous cookies user to the members container using the new username.

VBscript in an ASP Page

<% Set oUserObject = Server.CreateObject("membership.userobjects.1")

   UserName = "JohnS"
    if Request.Cookies("SITESERVER")("GUID") <> "" Then
      '
      ' Get the parent object
      Set ParentUserObject =  oUserObject.GetObjectAsUser(oUserObject.Parent)
      '
      ' Get the grandparent object
      Set TargetContainer = oUserObject.GetObjectAsUser(ParentUserObject.Parent)
      '
      'Move the object to the target container
      TargetContainer.MoveHere oUserObject.ADsPath, "cn=" & UserName
      '
      ' create cookie object
      Set NewCookie = Server.CreateObject("Membership.verifusr")
      '
      ' Issue cookie to the old user
      NewCookie.IssueCookieToOldUser(cstr(UserName))
   End if
%>


Interface IVerifUsr IssueCookiesToNewUser Method

IssueCookiesToNewUser Method

This method is used to issue the necessary cookies to a new registered user account that did not previously have a corresponding anonymous cookie account.

IDL Definition

HRESULT IssueCookiesToNewUser(
BSTR bszUserName,
[out, retval] BSTR* pbstrNewGUIDValue
);

Parameters

bszUserName

The name of the new user.

pbstrNewGUIDValue

On return, the BSTR variable contains the user's new GUID value.

Return Values

A standard HRESULT value

Remarks

This method is used to set a new user's Membership cookies during the construction of a new user account as well as generate a GUID value for the account. If the user already has a GUID value associated, use the IssueOldCookiesToNewUser method.

One must explicitly update the new account's directory properties with the new GUID value as this is a required property.

Example

<%
  NewUserName = "FredJ"
  ID = "o=company/ou=members/cn=administrator"
  Password = "password"

  Set IUserObjects = Server.CreateObject("Membership.UserObjects.1")
  '  assume this AUO is going to be used to create a new user
  ' with username "FredJ"

  ' set the new username in the AUO
  IUserObjects.SetUserName(cstr(NewUserName))

  ' use these binding credentials to access the DS
  IUserObjects.BinsAs "", ID,Password

  '  Now work with cookies
  Set IVerifUsr = Server.CreateObject("Membership.VerifUsr.1")
  '  Check to see if the user already has a GUID
  If Request("MEMUSER") <> "" Then
    ' No username and likely no GUID;  Issue Cookies and Get a new GUID
    GUIDValue = IVerifUsr.IssueCookiesToNewUser(Username)

    '  ADSI object loaded and the value put
    '  the required GUID value in the object
    IUserObjects.Put "GUID", cstr(GUIDValue)

   Else
    GUIDValue = IUserObjects.Get("GUID")
    IVerifUsr.IssueOldCookiesToNewUser Username, GUIDValue
   End If

    ' the info in the ADSI object committed to DS
    IUserObjects.SetInfo
%>


Interface IVerifUsr HashCert Method

HashCert

This method generates and returns the Secure Hashing Algorithm (SHA) hash of the subject name and issuer name for a user's certificate.

IDL Definition

HRESULT HashCert(
BSTR bszSubjectName,
BSTR bszIssuerName,
[out, retval] BSTR* pbstrCertHash
);

Parameters

bszSubjectName

The subject in the certificate

bszIssuerName

The certificate issuer name

pbstrCertHash

On return, the hash of the certificate.

Return Values

a standard HRESULT value

Example

<%

Set gMemUserObject = Server.CreateObject("Membership.UserObjects")
If Request("REMOTE_USER") = "" Then
      ScriptError("Not Authenticated")
End if
set x = Server.CreateObject("Membership.verifusr.1")
y = x.HashCert(Request.ClientCertificate("SUBJECT"),Request.ClientCertificate("ISSUER"))
gMemUserObject.Put "userCertificateHash", y
gMemUserObject.setinfo
%>


Interface IVerifUsr IssueRecentChangesCookie Method

IssueRecentChangesCookie Method

This method issues an updated timestamp cookie to the user that will notify the Membership virtual server instance on the next request that the user's directory data should be refreshed from the directory service.

IDL Definition

HRESULT IssueRecentChangesCookie(BSTR bszUserName);

Parameters

bszUserName

The username of the user. This name should be the name of the user as it appears in the REMOTE_USER server variable. For example, if the relative DN of a user is "cn=JohnS", the username passed to this method should be "JohnS".

Return Values

a standard HRESULT value

Remarks

This method should be invoked whenever a user's properties have been updated in the Membership directory service. It issues or updates the "MemRightsChanged" timestamp cookie using the ASP Response object. This cookie is therefore sent to the client along with the rest of the response. When the user makes their next request, the timestamp notifies the Membership virtual server instance that the user's properties should be refreshed from the directory store.

This method is invoked by the UserObjects object automatically when a Put/PutEx method is invoked on its IADs interface. In this case, no explicit call is necessary.

Example

<%
      Set IUserObjects = Server.CreateObject("Membership.UserObjects")
      call IUserObjects.GetObject("","").Put "something","somevalue"

      ' note that here we got the dispinterface on the ADSI object
      ' directly using the GetObject method.  We must invoke
      ' IssueRecentChangesCookie explicitly.

      Set IVerif = Server.CreateObject("Membership.VerifUsr.1")

      '  change a property in the directory (code ommited)
      IVerif.IssueRecentChangesCookie(Request("Remote_User"))
%>


Interface IVerifUsr VerifyPassword Method

VerifyPassword Method

This method checks the username and password against the directory information and returns TRUE if they are valid. It returns FALSE if they are incorrect.

IDL Definition

HRESULT VerifyPassword(
BSTR bszUserName,
BSTR bszPassword,
[out, retval] LONG* plPasswordVerified
);

Parameters

bszUserName

The username

bszPassword

The password

plPasswordVerified

On return, the LONG variable holds the result of the verification. The value returned will be either TRUE (1) or FALSE (0). TRUE means that the password was correct.

Return Values

a standard HRESULT value

Example

ASP and VBScript

<% Set IVerifUsr = Server.CreateObject("Membership.VerifUsr")
     ' assume Username and Password are defined and need to be checked
      If IVerifUsr.VerifyPassword(Username,Password) Then
      Response.Write "password is correct"
      Else
      Response.Write "password incorrect"
      End If
%>


Interface IVerifUsr IssueOldCookiesToNewUser Method

IssueOldCookiesToNewUser Method

This method issues the Membership cookies to a specified new user. It is used when creating a new user that had a previously set anonymous GUID value.

IDL Definition

HRESULT IssueOldCookiesToNewUser(
BSTR bszUserName,
BSTR bstrUserGUID
);

Parameters

bszUserName

The new username to issue the cookies under

bszUserGUID

The previous GUID value for the user

Return Values

a standard HRESULT value

Remarks

This method should only be used when creating a new user account for a user that already has a GUID value stored with the Membership directory service.

Example

NewUserName = "FredJ"
  ID = "o=company/ou=members/cn=administrator"
  Password = "password"

  Set IUserObjects = Server.CreateObject("Membership.UserObjects.1")
  '  assume this AUO is going to be used to create a new user
  ' with username "FredJ"

  ' set the new username in the AUO
  IUserObjects.SetUserName(cstr(NewUserName))

  ' use these binding credentials to access the DS
  IUserObjects.BinsAs "", ID,Password

  '  Now work with cookies
  Set IVerifUsr = Server.CreateObject("Membership.VerifUsr.1")
  '  Check to see if the user already has a GUID
  If Request("MEMUSER") <> "" Then
    ' No GUID;  Issue Cookies and Get a new GUID
    GUIDValue = IVerifUsr.IssueCookiesToNewUser(Username)

    '  ADSI object loaded and the value put to the object
    IUserObjects.Put "GUID", cstr(GUIDValue)

  Else
    GUIDValue = IUserObjects.Get("GUID")
    IVerifUsr.IssueOldCookiesToNewUser Username, GUIDValue
  End If
    '  Now the new user with DN cn=FredJ exists in the default
    ' AUO provider and the necessary cookies will be sent with
    ' the response from this page

  IUserObjects.SetInfo

%>


Interface IVerifUsr IssueCookie Method

IssueCookie Method

This method issues a cookie to the page response, inserting the correct Domain portion that the Siteserver system requires.

IDL Definition

HRESULT IssueCookie(BSTR bszCookieName,  BSTR bszCookieValue);

Parameters

bszCookieName

The name of the cookie

bszCookieValue

The associated value of the cookie

Return Values

a standard HRESULT value

Remarks

This method can be used to simply "reset" a user's cookies that somehow have been lost or are not present.

Example

<%
   ' The response.buffer line MUST be the first code
   ' and/or HTML line on the page
  Response.Buffer = TRUE
  Set UserObjects = Server.CreateObject("Membership.UserObjects")
  Set vusr = Server.CreateObject("Membership.verifusr")
  vusr.IssueCookie "SITESERVER", "GUID=" & UserObjects.Get("GUID")
  vusr.IssueCookie "MEMUSER", UserObjects.Get("cn")
%>


Interface IVerifUsr CancelCookie Method

CancelCookie Method

The method will cancel a previously assigned cookie from the server's response.

IDL Defintion

HRESULT CancelCookie(BSTR bszCookieName);

Parameters

bszCookieName

The name the cookie was set under

Return Values

A standard HRESULT value

Example

<% Set IVerifUsr = Server.CreateObject("Membership.Verifusr.1")
      IVerifUsr.IssueCookie "mycookie", "myvalue"
       … ' for some reason, we need to revoke it
      IVerifUsr.CancelCookie "mycookie"
%>


Search Programmer's Guide

The Microsoft® Site Server Search SDK contains COM objects that can be programmed to automate the catalog building process for conducting searches. You can fully administer all the components of a Search system and also invoke catalog building whenever document content changes.

In addition to developing applications with user interfaces, developers can provide administrators with Windows® Scripting Host (WSH) scripts for performing quick configurations and for gathering statistical information.

The Search SDK does not provide objects for initiating search requests or for managing search results. See the main Microsoft Site Server documentation for information about using the Query and Utility objects, SQL queries, and how to use ADO objects for data processing the search results.

Search System Overview

Programmers are encouraged to read about Search in the Microsoft Site Server product documentation to get a thorough understanding of the technology; however, here is a brief overview of the Search system components.

A Search host is a Microsoft® Windows NT® Server on which Search is installed. A Search system comprises one or more hosts that work together to create, maintain, and store your catalogs.

Hosts are divided into the following functions:

  • Catalog Build Server. Contains catalog definitions, which are the user-defined settings for a catalog. Based on these settings, this server gathers information and builds catalogs.

  • Search Server. Stores completed catalogs for searching.

A host can function as both a catalog build server and a search server.

In the Microsoft Management Console under Search, these two servers are represented as icons under each host in the system.

Propagating Catalogs

After a catalog build server has built a catalog from a catalog definition, it propagates the completed catalog to the selected search servers. A catalog can be propagated to as many as 32 search servers, where site visitors can search the completed catalog.

Although you can use just one host for both building and searching catalogs, propagating catalogs to other hosts can be useful.

  • You can dedicate one server to building catalogs, and dedicate multiple servers to searching catalogs. Because building a catalog can consume system resources, site visitors can search catalogs quicker on dedicated search servers.

  • If your site experiences a high volume of use, multiple search servers can distribute the load with a round-robin approach.

  • By using multiple hosts, you can increase the reliability of your system; for example, if one host goes down, other hosts will continue to function.

Terminology

The Search SDK naming conventions are slightly different than what is used is the Search product documentation and administrative tools. The following table shows the relationship between the two.

Site Server Product Names | SDK Component Names
Catalog Build Server | Build Server
Search Server | Search Server
Catalog Definition | Build Catalog
Catalog | Search Catalog


COM Class Architecture

Two COM classes provide developers with access to a comprehensive set of collections, properties, and methods to fully administer a Search system, except for programming end-user search requests. Use the SearchAdmin class to define, manage definitions, build catalogs from the catalog definitions and propagate them to the Search hosts in the system. Use the CGatherNotify class to notify Search that content has changed and should be re-indexed.

SearchAdmin

The SearchAdmin class contains two sets of interfaces serving the core functions of a Search system:

  • Creating catalogs and administering builds

    The BuildServer property obtains a Catalog Build Server object from which a collection of catalog definitions can be obtained, using the IBuildServer, IBuildCatalogs and IBuildCatalog interfaces.

  • Managing catalogs and administering search requests

    The SearchServer property obtains the Search Server object from which a collection of catalogs can be obtained, using the ISearchServer, ISearchCatalogs and ISearchCatalog interfaces.

CGatherNotify

The GatherNotify class supplies methods for notifying Search when the documents of a catalog have changed and should be re-indexed.

For more information about this object, visit http://www.microsoft.com/msdn/sdk/siteserver.htm in late April 1998 for an updated version of this SDK and for late breaking information.


Using the Search Objects

This section provides an overview of programming with the Search objects. The following table lists the topics in this section and the interfaces from which the relevant objects are obtained.

Topic | Interface
Configuring the Catalog Build Server | IBuildServer
Managing Definitions and Building Catalogs | IBuildCatalogs , IBuildCatalog
Configuring the Search Server | ISearchServer
Managing Catalogs and Search Requests | ISearchCatalogs , ISearchCatalog

If you create catalog defintions and catalogs by using Microsoft® Management Console MMC, Web Admin, or on the command line, they are included in the collection of catalog definitions and catalogs.

Using the Type Libraries

To get acquainted with Search objects, properties, and methods, programmers can peruse the Search type libraries by using the Microsoft Visual Basic® Object Browser or the Microsoft Visual C++® OLE/COM Object Viewer. The following type libraries are provided.

  • Site Server Search Administration 1.0 Type Library

  • Site Server Gathering Service Type Library

  • Site Server Gatherer Type Library

  • Site Server Indexer Type Library

For more information about the type libraries and the interfaces they describe, see Interface Type Information in the Search Programmer’s Reference Appendix.


Configuring the Catalog Build Server

The Catalog Build Server, obtained by the BuildServer property, serves two purposes:

Obtains a catalog definition collection for adding, removing, and configuring catalog definitions. This collection is obtained by the BuildCatalogs property.

  1. Provides the following configuration options, such as:
    • Specifes crawl settings such as sites that have hit frequency restrictions, the user agent used for crawling, timeout values, the default content access account name for crawling other hosts, and the email address to log while crawling.

    • Specifies default settings for the access account and other administrative settings.

    • Specifies locations for catalog defintions, logs, and temporary files.

    • Saves and load catalog definitions and server configurations.

    • Sets the server’s performance level.

    • Specifies proxy server addresses and settings.


Managing Definitions and Building Catalogs

To manage catalog definitions, you obtain a collection to which you can add, remove, and modify individual definitions.

You can perform the following configurations and actions on a catalog definition object:

  • Specify the schema used for the catalog definition and load the schema from a file.

  • Configure the catalog project type, crawl or notification. Crawl types are when crawling is invoked manually or from a scheduling application. Crawling for Notification types is automatically invoked when content changes, and you specify the text identifier that the GatherNotify.Init method uses to trigger the re-indexing of documents.

  • Specify crawl settings, such as file extensions, the pages to crawl, the sites to avoid, and also log the progress and activity of a crawl. You can also map from where a file is searched to where it is displayed.

    For a notification type, you can

  • Build a catalog from a catalog definition.

  • Obtain information about current and previous builds.

  • Configure and manage the building process, such as starting, stopping, and pausing the build.

  • Propagate catalogs to the participating Search hosts in the system.


Configuring the Search Server

After the catalogs are built, you can control which catalogs are used for searches and specify settings for the Search Server.

The Search Server, obtained by the SearchServer property, serves two purposes:

  1. Obtains a catalog collection for adding, removing, and configuring catalogs. This collection is obtained by the SearchCatalogs property.

  2. Provides the following configuration options, such as:
    • Gets the location of catalogs on the Search Server.

    • Sets the default catalog used for a search.

    • Sets the performance level of host resources dedicated to searching.


Managing Catalogs and Search Requests

To manage catalogs, you obtain a collection of them to which you can add, remove, and modify individual catalogs.

You can perform the following configurations and actions on a Search catalog object:

  • Get the name of the server that built the catalog.

  • Enable or disable searching on a catalog.

  • Update a catalog.

  • Set the maximum number of result rows for a query.

  • Get catalog properties.

  • Set the timeout value for a query to finish.

  • Determine the status of a catalog.


Interface Overview

Each Search object implements an interface and this section briefly describes each Search interface, including how to create or access an instance of each object. Except for the CGatherNotify COM class, you must first create an instance of the SearchAdmin COM class to create or access other Search objects.

The following table briefly describes the Search interfaces.

Interface | Description
IBuildCatalog | Manages a catalog definition.
IBuildCatalogs | Manages catalog definitions (collection of IBuildCatalog objects).
IBuildServer | Manages catalog definitions (through the IBuildCatalogs interface) and catalog build server properties.
ICatalogProperties | The properties of a catalog.
ICatalogSearchServerList | Manages information about Search hosts (collection of IIndexDs objects) to which a catalog (ISearchCatalog object) is propagated.
IColumn | Information about documents that Search indexes or retrieves while crawling.
IColumns | Manages schema columns (collection of IColumn objects) of information about documents that Search indexes or retrieves while crawling.
IExtension | Specifies a file extension that Search crawls or avoids when building a catalog.
IExtensions | Manages file extensions (collection of IExtension objects) that Search crawls or avoids when building a catalog.
IGatherLog | Manages a catalog build server log containing the names of the documents that Search successfully or unsuccessfully crawled, or avoided, while building a catalog.
IGatherLogs | Manages catalog build server logs (collection of IGatherLog objects) containing the names of the documents that Search successfully or unsuccessfully crawled, or avoided, while building a catalog.
IGatherNotify | Used to notify Search that content has changed and that a catalog should be updated.
IIndexDs | Manages information about a Search host where Search propagates a catalog.
IMapping | Specifies how documents are accessed when crawling (the crawler access location) and how documents are displayed to site visitors when searching (the display location).
IMappings | Manages access-display mappings (collection of IMapping objects) that specify how documents are accessed when crawling (the crawler access location) and how documents are displayed to site visitors when searching (the display location).
IProtocol | The properties of a protocol that Search crawls or avoids when crawling.
IProtocols | Manages protocols (collection of IProtocol objects) that Search crawls or avoids when crawling.
ISearchAdmin | Provides properties to access other Search interface objects on a specified host.
ISearchCatalog | Manages a searchable catalog.
ISearchCatalogs | Manages catalogs (collection of ISearchCatalog objects) that can be searched.
ISearchSchema | Manages the properties (through the IColumns interface) and noise words (through the IStoplists interface) used to control what information is stored in a catalog.
ISearchServer | Manages catalogs (through the ISearchCatalogs interface) and search server properties.
IServer | How frequently Search is allowed to access a site.
IServers | Manages site hit frequency rules (collection of IServer objects) that specify how frequently Search is allowed to access a site.
ISitePath | Manages a path that Search crawls or avoids on a site.
ISitePaths | Manages site path rules (collection of ISitePath objects) that tell Search whether to crawl or avoid certain paths.
ISiteRestriction | Manages site that Search crawls or avoids, that may be configured with a content access account, and where Search crawls or avoids certain paths.
ISiteRestrictions | Manages site rules (collection of ISiteRestriction objects) that tell Search whether to crawl or avoid certain sites.
IStartPage | Manages a location where Search starts crawling a site.
IStartPages | Manages start addresses (collection of IStartPage objects) where Search starts crawling.
IStoplist | Manages a file containing noise words that Search ignores when building a catalog.
IStoplists | Manages noise word files (collection of IStoplist objects) containing words that Search ignores when building a catalog.


IBuildCatalog Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs

This interface manages a catalog definition. You create a new IBuildCatalog object by calling the IBuildCatalogs.Add method. You access a specific IBuildCatalog object by calling the IBuildCatalogs.Item property. You can access all of the IBuildCatalog objects by iterating through the IBuildCatalogs collection in a for each loop.

You don't create or access an interface object, you create or access an object. Please make these changes globally.


IBuildCatalogs Interface

Hierarchy

ISearchAdmin:IBuildServer

The BuildCatalogs object is a collection of BuildCatalog objects. The BuildCatalog objects manage a catalog definition.

You access an IBuildCatalogs interface object by calling the IBuildServer.BuildCatalogs property.


IBuildServer Interface

Hierarchy

ISearchAdmin

This interface manages catalog definitions (through the IBuildCatalogs interface) and catalog build server properties.

You access an IBuildServer interface object by calling the ISearchAdmin.BuildServer property.


ICatalogProperties Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog ISearchAdmin:ISearchServer:ISearchCatalogs:ISearchCatalog

This interface specifies the properties of a catalog.

You access ICatalogProperties interface objects by calling any of the following:

Property | Description
IBuildCatalog.CurrentBuildProperties | For information on the current build.
IBuildCatalog.PreviousBuildProperties | For information on the previous build.
ISearchCatalog.Properties | Properties of a catalog.


ICatalogSearchServerList Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog

This interface manages information about Search hosts (collection of IIndexDs interface objects) to which a catalog (ISearchCatalog interface) is propagated.

You access an ICatalogSearchServerList interface object by calling the IBuildCatalog.SearchServers property.


IColumn Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog:ISearchSchema:IColumns

This interface specifies information about documents that Search indexes or retrieves while crawling.

You create an IColumn interface object by calling the IColumns.Add method. You access a specific IColumn interface object by calling the IColumns.Item property. You can access all of the IColumn interface objects by iterating through the IColumns collection in a for each loop.


IColumns Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog:ISearchSchema

This interface manages schema columns (collection of IColumn interface objects) of information about the documents that Search indexes or retrieves while building a catalog.

You access an IColumns interface object by calling the ISearchSchema.Columns property.


IExtension Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog:IExtensions

This interface specifies a file extension that Search crawls or avoids when building a catalog.

You create an IExtension interface object by calling the IExtensions.Add method. You access a specific IExtension interface object by calling the IExtensions.Item property. You can access all of the IExtension interface objects by iterating through the IExtensions collection in a for each loop.


IExtensions Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog

This interface manages file extensions (collection of IExtension interface objects) that Search crawls or avoids when building a catalog.

You access an IExtensions interface object by calling the IBuildCatalog.Extensions property.


IGatherLog Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog:IGatherLogs

This interface is a catalog build server log containing the names of the documents that Search successfully or unsuccessfully crawled, or avoided, while building a catalog.

You access a specific IGatherLog interface object by calling the IGatherLogs.Item property. You can access all of the IGatherLog interface objects by iterating through the IGatherLogs collection in a for each loop.


IGatherLogs Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog

This interface manages catalog build server logs (collection of IGatherLog interface objects) containing the names of the documents that Search successfully or unsuccessfully crawled, or avoided, while building a catalog.

You access an IGatherLogs interface object by calling the IBuildCatalog.Logs property.


IGatherNotify Interface

Hierarchy

CGatherNotify

This interface is used to notify Search that content has changed and that a catalog should be updated.

To use the IGatherNotify interface, you create an instance of the CGatherNotify COM class by calling CreateObject, as follows:

Set objGatherNotify = CreateObject("GatherSvc.GatherNotify")


IIndexDs Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog:ICatalogSearchServerList

This interface manages information about a Search host to which Search propagates a catalog.

You create a new IIndexDs interface object by calling the ICatalogSearchServerList.Add method. You access a specific IIndexDs interface object by calling the ICatalogSearchServerList.Item property. You can access all of the IIndexDs interface objects by iterating through the ICatalogSearchServerList collection in a for each loop.


IMapping Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog:IMappings

This interface specifies how documents are accessed when crawling (the crawler access location) and how documents are displayed to site visitors when searching (the display location).

You create an IMapping interface object by calling the IMappings.Add method. You access a specific IMapping interface object by calling the IMappings.Item property. You can access all of the IMapping interface objects by iterating through the IMappings collection in a for each loop.


IMappings Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog

This interface manages access-display mappings (collection of IMapping interface objects) that specify how documents are accessed when crawling (the crawler access location) and how documents are displayed to site visitors when searching (the display location).

You access an IMappings interface object by calling the IBuildCatalog.Mappings property.


IProtocol Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog:IProtocols

This interface contains the properties of a protocol that Search crawls or avoids when crawling.

You access a specific IProtocol interface object by calling the IProtocols.Item property. You can access all of the IProtocol interface objects by iterating through the IProtocols collection in a for each loop.


IProtocols Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog

This interface manages protocols (collection of IProtocol interface objects) that Search crawls or avoids when crawling.

You access an IProtocols interface object by calling the IBuildCatalog.Protocols property.


ISearchAdmin Interface

Hierarchy

SearchAdmin

This object provides properties to access the other Search interface objects on a specific host.

Use the ISearchAdmin interface to specify a Search host for administration or default to the local host and then access the other Search interfaces. You can access the IBuildServer or ISearchServer interface objects by using the ISearchAdmin properties.

You create an instance of the SearchAdmin COM class by calling CreateObject, as follows:

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")


ISearchCatalog Interface

Hierarchy

ISearchAdmin:ISearchServer:ISearchCatalogs

This interface manages a searchable catalog.

Normally, catalogs are created on a particular host when the host is specified as a Search host in the catalog definition. For disconnected propagation you can create an ISearchCatalog interface object by calling the ISearchCatalogs.Add method. You access a specific ISearchCatalog interface object by calling the ISearchCatalogs.Item property. You can access all of the ISearchCatalog interface objects by iterating through the ISearchCatalogs collection in a for each loop.


ISearchCatalogs Interface

Hierarchy

ISearchAdmin:ISearchServer

This interface manages catalogs (collection of ISearchCatalog interface objects) that can be searched.

You access an ISearchCatalogs interface object by calling the ISearchServer.SearchCatalogs property.


ISearchSchema Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog

This interface manages the properties (IColumns interface) and noise words (IStoplists interface) used to control what information is stored in a catalog.

You access an ISearchSchema interface object by calling the IBuildCatalog.Schema property.


ISearchServer Interface

Hierarchy

ISearchAdmin

This interface manages catalogs (through the ISearchCatalogs interface) and search server properties.

You access an ISearchServer interface object by calling the ISearchAdmin.SearchServer property.


IServer Interface

Hierarchy

ISearchAdmin:IBuildServer:IServers

This interface specifies how frequently Search is allowed to access a site.

You create an IServer interface object by calling the IServers.Add method. You access a specific IServer interface object by calling the IServers.Item property. You can access all of the IServer interface objects by iterating through the IServers collection in a for each loop.


IServers Interface

Hierarchy

ISearchAdmin:IBuildServer

This interface manages site hit frequencies rules (collection of IServer interface objects) that specify how frequently Search is allowed to access a site.

You access an IServers interface object by calling the IBuildServer.Sites property.


ISitePath Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog:ISiteRestrictions:ISiteRestriction:ISitePaths

This interface manages a path that Search crawls or avoids on a site.

You create an ISitePath interface object by calling the ISitePaths.Add method. You access a specific ISitePath interface object by calling the ISitePaths.Item property. You can access all of the ISitePath interface objects by iterating through the ISitePaths collection in a for each loop.


ISitePaths Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog:ISiteRestrictions:ISiteRestriction

This interface manages site path rules (collection of ISitePath interface objects) that tell Search whether to crawl or avoid certain paths.

You access an ISitePaths interface object by calling the ISiteRestriction.Paths property.


ISiteRestriction Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog:ISiteRestrictions

This interface specifies a site where Search crawls or avoids certain paths.

You create an ISiteRestriction interface object by calling the ISiteRestrictions.Add method. You access a specific ISiteRestriction interface object by calling the ISiteRestrictions.Item property. Since ISiteRestrictions is a collection, you can access all of the ISiteRestriction interface objects by iterating through the collection in a for each loop.


ISiteRestrictions Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog

This interface manages site rules (collection of ISiteRestriction interface objects) that tell Search whether to crawl or avoid certain sites.

You access an ISiteRestrictions interface object by calling the IBuildCatalog.Sites property.


IStartPage Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog:IStartPages

This interface manages a location where Search starts crawling a site.

You create an IStartPage interface object by calling the IStartPages.Add method. You access a specific IStartPage interface object by calling the IStartPages.Item property. You can access all of the IStartPage interface objects by iterating through the IStartPages collection in a for each loop.


IStartPages Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog

This interface manages start addresses (collection of IStartPage interface objects) where Search starts crawling.

You access an IStartPages interface object by calling the IBuildCatalog.StartPages property.


IStoplist Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog:ISearchSchema:IStoplists

This interface manages a file containing noise words that Search ignores when building a catalog.

You create an IStoplist interface object by calling the IStoplists.Add method. You access a specific IStoplist interface object by calling the IStoplists.Item property. You can access all of the IStoplist interface objects by iterating through the IStoplists collection in a for each loop.


IStoplists Interface

Hierarchy

ISearchAdmin:IBuildServer:IBuildCatalogs:IBuildCatalog:ISearchSchema

This interface manages noise word files (collection of IStoplist interface objects) containing words that Search ignores when building a catalog.

You access an IStoplists interface object by calling the ISearchSchema.Stoplists property.


Search Programmer's Reference

This section provides a detailed description of the COM objects that comprise the Search section of the Microsoft Site Server SDK. It describes the interfaces that are provided, including their properties and methods. The examples are written in VBScript and can be used with the Windows Scripting Host (WSH).


Adapting WSH Examples for ASP

Although the interface reference examples are written for the Windows Scripting Host (WSH), you can easily adapt them for Active Server Pages (ASP). The first step is to wrap the VBScript code in the ASP delimiters (<% and %>), as in the following example:

WSH File ASP File

Option Explicit
On Error Resume Next
Dim objSearchAdmin
Set objSearchAdmin = _
CreateObject("Search.SearchAdmin.1")
...
'Release objSearchAdmin object
Set objSearchAdmin = Nothing

<%
Option Explicit
On Error Resume Next
Dim objSearchAdmin
Set objSearchAdmin = _
CreateObject("Search.SearchAdmin.1")
...
'Release objSearchAdmin object
Set objSearchAdmin = Nothing
%>

Also, to produce output, you must change the Wscript.Echo methods to Response.Write methods.

Note Since ASP files default to the VBScript programming language, you need not supply a language qualifier to your VBScript ASP pages. If you use a different language, such as JScript, you must amend the first line of the previous ASP example to the following:

<% SCRIPT LANGUAGE="JScript"

ASP files offer some additional functionality over WSH files. For example, you can create an include file in which can place commonly-used code, such as the following defined constants, which specify the error codes you receive if Search cannot create the object or the object does not exist:

Const E_CREATEOBJECT  = 429   ' cannot create object
Const E_NOTEXIST      = 424   ' object doesn't exist

You can then include this file in an ASP file with a line of code similar to the following, where SearchInclude.inc is the name of the include file (it can be any legal file name and need not have the .inc file extension):

<!--#include file = "SearchInclude.inc"-->


Error Handling

You can use code like the following to display errors:

If (Err.Number <> 0) Then
    Wscript.Echo "Error #:     " & Err.Number
    Wscript.Echo "Description: " & Err.Description
End If


Search Interfaces

The following table briefly describes the Search interfaces.

Interface | Description
IBuildCatalog | Manages a catalog definition.
IBuildCatalogs | Manages catalog definitions (collection of IBuildCatalog objects).
IBuildServer | Manages catalog definitions (through the IBuildCatalogs interface) and catalog build server properties.
ICatalogProperties | The properties of a catalog.
ICatalogSearchServerList | Manages information about Search hosts (collection of IIndexDs objects) to which a catalog (ISearchCatalogobject) is propagated.
IColumn | Information about documents that Search indexes or retrieves while crawling.
IColumns | Manages schema columns (collection of IColumn objects) of information about documents that Search indexes or retrieves while crawling.
IExtension | Specifies a file extension that Search crawls or avoids when building a catalog.
IExtensions | Manages file extensions (collection of IExtension objects) that Search crawls or avoids when building a catalog.
IGatherLog | Manages a catalog build server log containing the names of the documents that Search successfully or unsuccessfully crawled, or avoided, while building a catalog.
IGatherLogs | Manages catalog build server logs (collection of IGatherLog objects) containing the names of the documents that Search successfully or unsuccessfully crawled, or avoided, while building a catalog.
IGatherNotify | Used to notify Search that content has changed and that a catalog should be updated.
IIndexDs | Manages information about a Search host where Search propagates a catalog.
IMapping | Specifies how documents are accessed when crawling (the crawler access location) and how documents are displayed to site visitors when searching (the display location).
IMappings | Manages access-display mappings (collection of IMapping objects) that specify how documents are accessed when crawling (the crawler access location) and how documents are displayed to site visitors when searching (the display location).
IProtocol | The properties of a protocol that Search crawls or avoids when crawling.
IProtocols | Manages protocols (collection of IProtocol objects) that Search crawls or avoids when crawling.
ISearchAdmin | Provides properties to access other Search interface objects on a specified host.
ISearchCatalog | Manages a searchable catalog.
ISearchCatalogs | Manages catalogs (collection of ISearchCatalog objects) that can be searched.
ISearchSchema | Manages the properties (through the IColumns interface) and noise words (through the IStoplists interface) used to control what information is stored in a catalog.
ISearchServer | Manages catalogs (through the ISearchCatalogs interface) and search server properties.
IServer | How frequently Search is allowed to access a site.
IServers | Manages site hit frequency rules (collection of IServer objects) that specify how frequently Search is allowed to access a site.
ISitePath | Manages a path that Search crawls or avoids on a site.
ISitePaths | Manages site path rules (collection of ISitePath objects) that tell Search whether to crawl or avoid certain paths.
ISiteRestriction | Manages site that Search crawls or avoids, that may be configured with a content access account, and where Search crawls or avoids certain paths.
ISiteRestrictions | Manages site rules (collection of ISiteRestriction objects) that tell Search whether to crawl or avoid certain sites.
IStartPage | Manages a location where Search starts crawling a site.
IStartPages | Manages start addresses (collection of IStartPage objects) where Search starts crawling.
IStoplist | Manages a file containing noise words that Search ignores when building a catalog.
IStoplists | Manages noise word files (collection of IStoplist objects) containing words that Search ignores when building a catalog.

While every Site Server Search user has read-only access to search server and catalog properties, you must have Site Server Administrator privileges to access catalog build server and catalog definition properties and to modify search server and catalog properties.


IBuildCatalog Interface

This interface manages a catalog definition.

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs

The following table briefly describes this interface's methods and properties.

Method | Description
AbortProp | Aborts the propagation of a build catalog.
ForceProp | Forces a propagation of the build catalog.
PauseBuild | Pauses a build.
ResumeBuild | Resumes a build.
StartBuild | Starts a build.
StartIncrementalBuild | Start an incremental build.
StopBuild | Stops a build.
Property | Description
AutoPropLimit | The number of documents to crawl before propagating.
AutoPropLimitEnabled | Whether Search uses the AutoPropLimit property.
BuildServer | The catalog build server (IBuildServer interface) that manages catalog definitions.
CurrentBuildProperties | Information about the current build (as an ICatalogProperties interface).
CurrentPages | List of documents being crawled.
Extensions | A list of filename extensions (IExtensions interface) to crawl or avoid.
FollowComplexUrls | Whether to allow wildcards in the names of Web links to crawl.
IsBuilding | Whether Search is building a catalog.
IsLocalFileSchema | Whether the local schema file is used as the schema.
LogExcluded | Whether to log the names of documents excluded from crawling.
Logs | A list of gatherer logs (IGatherLogs interface) that contain the names of the documents that Search successfully or unsuccessfully crawled, or ignored, while building a catalog.
LogSuccess | Whether to log the names of documents successfully crawled.
Mappings | The list of mappings (IMappings interface) that specify from where a file is searched (the crawler access location) to where a file is displayed to site visitors (the display location).
Name | The name of the catalog definition.
NotificationSource | The source string that identifies a gather Search catalog.
PreviousBuildProperties | Information about the previous build (as an ICatalogProperties interface).
ProjectType | The type of project.
Protocols | The protocols (IProtocols interface) that Search uses when crawling.
Schema | Document properties (ISearchSchema interface) that Search indexes or retrieves when building a catalog.
SearchServers | The list of search server names (collection of ISearchServer interfaces) to which the catalog is propagated.
Sites | The sites (ISiteRestrictions interface) that Search crawls or avoids.
StartPages | The locations (IStartPages interface) where the crawl starts.
Status | The status of the catalog.
StatusCode | The status code of the catalog.


Creating an IBuildCatalog Object

You create a new IBuildCatalog object by calling the IBuildCatalogs.Add method, as in the following example, where KMSampleCatalog1 is the name of the catalog:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs    = objSearchServer.BuildCatalogs
Set objCatalog     = objCatalogs.Add("KMSampleCatalog1", _
    "C:\Catalogs)

...

'Release objects
Set objCatalog     = Nothing
Set objCatalogs    = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


Accessing IBuildCatalog Objects

You can access a specific IBuildCatalog object by calling the IBuildCatalogs.Item method. Since IBuildCatalogs is a collection, you can access all IBuildCatalog objects using a for each loop, as in the following example, where objCatalog is the name you give the IBuildCatalog object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs    = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  ...
Next

'Release objects
Set objCatalog     = Nothing
Set objCatalogs    = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


AbortProp Method

This method aborts the propagatation of a build catalog.

Syntax

IBuildCatalog.AbortProp

Example

The following example begins a forced propagation of a catalog specified by the KMSampleCatalog1 catalog definition, presenting an abort button.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog
Dim Prompt, Buttons, Title, Response

Prompt = "Click OK to kill the forced propagation"
Buttons = vbOKOnly
Title = "Kill Forced Propagation?"

Err.Clear

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs    = objBuildServer.BuildCatalogs
Set objCatalog     = objCatalogs.Item("KMSampleCatalog1")

'Start forced propagation
objCatalog.ForceProp

'Present message box so user can cancel forced propagation operation
Response = MsgBox(Prompt, Buttons, Title)

If Response = vbOK Then
  objCatalog.AbortProp
End If

'Display its status
Wscript.Echo "Status: " & objCatalog.Status

'Release objects
Set objCatalog      = Nothing
Set objCatalogs     = Nothing
Set objBuildServer  = Nothing
Set objSearchAdmin  = Nothing

See Also

ForceProp


ForceProp Method

This method forces a propagation of the build catalog.

Syntax

IBuildCatalog.ForceProp

Example

The following example forces the propagation of all the catalogs on the local host.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  objCatalog.ForceProp
Next

'Release objects
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

AbortProp


PauseBuild Method

This method pauses a build.

Syntax

IBuildCatalog.PauseBuild

Example

The following example pauses the build of a catalog specifed by the KMSampleCatalog2 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")

objCatalog.PauseBuild

'Release objects
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

ResumeBuild, StartBuild, StopBuild


ResumeBuild Method

This method resumes a build.

Syntax

IBuildCatalog.ResumeBuild

Example

The following example starts building the catalog specified by the KMSampleCatalog1 catalog definition, then displays a message box asking the user whether they would like to pause the build. If the user pauses the build, another message box appears asking the user whether they would like to resume the build.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog
Dim Prompt, Buttons, Title, Response

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")

Prompt = "Build started." & Chr(13)
  & "Would you like to pause the build?"
Buttons = vbYesNo
Title = objCatalog.Name

objCatalog.StartBuild

Response = MsgBox(Prompt, Buttons, Title)

If Response = vbYes Then
  objCatalog.PauseBuild

   Prompt = "Build paused." & Chr(13)
    & "Would you like to resume the build?" & Chr(13)
    & "(No cancels the build)."
   Response = MsgBox(Prompt, Buttons, Title)

   If Response = vbYes Then
     objCatalog.ResumeBuild
   Else
     objCatalog.StopBuild
   End If
End If

'Release objects
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

PauseBuild , StartBuild, StopBuild


StartBuild Method

This method starts a build.

Syntax

IBuildCatalog.StartBuild

Example

The following example starts building the catalog specified by the KMSampleCatalog1 catalog definition, then displays a message box asking the user whether they would like to stop the build.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog
Dim Prompt, Buttons, Title, Response

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")

Prompt = "Build started." & Chr(13)
  & "Would you like to stop the build?"
Buttons = vbYesNo
Title = objCatalog.Name

objCatalog.StartBuild

Response = MsgBox(Prompt, Buttons, Title)

If Response = vbYes Then
  objCatalog.StopBuild
End If

'Release objects
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

PauseBuild , ResumeBuild, StopBuild


StartIncrementalBuild Method

This method starts an incremental build.

Syntax

IBuildCatalog.StartIncrementalBuild

Example

The following example starts an incremental build of search catalog specified by the KMSampleCatalog2 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")

objCatalog.StartIncrementalBuild

'Release objects
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

PauseBuild , ResumeBuild, StartBuild, StopBuild


StopBuild Method

This method stops a build.

Syntax

IBuildCatalog.StopBuild

Example

The following example starts building the catalog specified by the KMSampleCatalog1 catalog definition, then displays a message box asking the user whether they would like to stop the build.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog
Dim Prompt, Buttons, Title, Response

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")

Prompt = "Build started." & Chr(13)
  & "Would you like to stop the build?"
Buttons = vbYesNo
Title = objCatalog.Name

objCatalog.StartBuild

Response = MsgBox(Prompt, Buttons, Title)

If Response = vbYes Then
  objCatalog.StopBuild
End If

'Release objects
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

PauseBuild , ResumeBuild, StartBuild


AutoPropLimit Property

This property specifies the number of documents to crawl before propagating.

Syntax

IBuildCatalog.AutoPropLimit [=NumberOfDocuments]

Settings

NumberOfDocuments

The number of documents to cache before automatically propagating the catalog.

Remarks

Search ignores this property if the AutoPropLimitEnabled property is False.

Example

The following example sets the KMSampleCatalog1 catalog definition's AutoPropLimitEnabled property to True and AutoPropLimit property to 10000 documents.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")

objCatalog.AutoPropLimitEnabled = True
objCatalog.AutoPropLimit        = 10000

'Release objects
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

AutoPropLimitEnabled


AutoPropLimitEnabled Property

This property specifies whether Search uses the AutoPropLimit property.

Syntax

IBuildCatalog.AutoPropLimitEnabled [=Enabled]

Settings

Enabled

If True, the AutoPropLimit property is enabled.

Example

The following example sets every catalog's AutoPropLimitEnabled property to False (disables the AutoPropLimit property).

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  objCatalog.AutoPropLimitEnabled = False
Next

'Release objects
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

AutoPropLimit


BuildServer Property

This read-only property specifies the catalog build server (IBuildServer interface).

Syntax

IBuildCatalog.BuildServer

Example

The following example retrieves the catalog build server for a catalog definition and verifies its accuracy.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objBldSvr

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")

Set objBldSvr = objCatalog.BuildServer

If objBuildServer is objBldSvr Then
  Wscript.Echo "Identical IBuildServer interfaces"
Else
  Wscript.Echo "Error! The IBuildServer interfaces differ!"
End If

'Release objects
Set objCatalogs = Nothing
Set objBldSvr   = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

IBuildServer, SearchServers


CurrentBuildProperties Property

This read-only property specifies information about the current build (as an ICatalogProperties interface).

Syntax

IBuildCatalog.CurrentBuildProperties

Example

The following example displays information about the current build for the KMSampleCatalog1 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objCurBldProps

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")

Set objCurBldProps = objCatalog.CurrentBuildProperties

'Show the properties
Wscript.echo "objCatalog " & objCatalog.Name & " properties:"
Wscript.echo "  Build date:    " & objCurBldProps.BuildDate
Wscript.echo "  # docs:      " & objCurBldProps.NumberOfDocuments
Wscript.echo "  Size of index:   " & objCurBldProps.IndexSize _
  & " (MBytes)"
Wscript.echo "  Size of property store " _
  & objCurBldProps.PropertyStoreSize & " (MBytes)"
Wscript.echo "  # unique keys:   " _
  & objCurBldProps.UniqueKeyCount
Wscript.echo "  Crawl number:    " & objCurBldProps.PropSeqNum
Wscript.Echo ""

'Release objects
Set objCurBldProperties = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

PreviousBuildProperties


CurrentPages Property

This read-only property lists the documents being crawled.

Syntax

IBuildCatalog.CurrentPages

Example

The following example displays the documents being crawled while building the KMSampleCatalog2 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, Doc, i

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")

Doc = objCatalog.CurrentPages

Wscript.Echo "objCatalog " & objCatalog.Name _
  & "is searching the following documents:"

For i = Lbound(Doc) to Ubound(Doc)
  Wscript.Echo Doc(i)
Next

'Release objects
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Extensions, Mappings


Extensions Property

This read-only property specifies the list of filename extensions (collection of IExtensions interfaces) to crawl or avoid.

Syntax

IBuildCatalog.Extensions

Example

The following example displays the extensions that the KMSampleCatalog2 catalog definition specifies.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objExts

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")

Wscript.Echo objCatalog.Name & " crawls the following extensions:"

For Each objExts in objCatalog.Extensions
  Wscript.Echo objExts.Extension
Next

'Release objects
Set objExts        = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Protocols, IExtensions interface


FollowComplexUrls Property

This property specifies whether to allow wildcards in the names of Web links to crawl.

Syntax

IBuildCatalog.FollowComplexUrls [=Follow]

Settings

Follow

If True, Search allows the question mark (?) in filenames; if false, Search does not allow the question mark (?) in filenames.

Example

The following example allows wildcards in the names of Web links to crawl.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  objCatalog.FollowComplexUrls = True
Next

'Release objects
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Sites, StartPages


IsBuilding Property

This read-only property specifies whether Search is building a catalog.

Syntax

IBuildCatalog.IsBuilding

Example

The following example displays whether Search is building any catalogs.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  If objCatalog.IsBuilding Then
    Wscript.Echo objCatalog.Name & " is building."
  Else
    Wscript.Echo objCatalog.Name & " is not building."
  End If
Next

'Release objects
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Status, StatusCode


IsLocalFileSchema Property

This property specifies whether the local schema file is used as the schema.

Syntax

IBuildCatalog.IsLocalFileSchema [=UseLocal]

Settings

UseLocal

If True, Search uses the local file as the schema; if False, Search does not use the local file as the schema.

Remarks

Local schema files only affect the individual catalog.

Example

The following example causes the KMSampleCatalog1 catalog definition to use the local schema file.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog = objCatalogs("KMSampleCatalog1")

objCatalog.IsLocalFileSchema = True

'Release objects
objCatalog = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Schema


LogExcluded Property

This property specifies whether to log the names of documents excluded from crawling.

Syntax

IBuildCatalog.LogExcluded [=Exclude]

Parameters

Exclude

If True, the names of excluded files are logged; if False, the names of the excluded files are not logged.

Example

The following example logs the files that are excluded during the building of the KMSampleCatalog2 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")

objCatalog.LogExcluded = True

'Release objects
objCatalog = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Logs, LogSuccess


Logs Property

This read-only property specifies a list of gatherer logs (IGatherLogs interface) that contain the names of the documents that Search successfully or unsuccessfully crawled, or ignored, while building a catalog.

Syntax

IBuildCatalog.Logs

Example

The following example displays the name of the current the log file for every catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, Logs, CurrentLog

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  Set Logs = objCatalog.Logs
   Set CurrentLog = Logs.CurrentLog
  Wscript.Echo "The current log file For the " & objCatalog.Name
    & " catalog is " & CurrentLog.Name
Next

'Release objects
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

LogExcluded, LogSuccess


LogSuccess Property

This property specifies whether to log the names of documents successfully crawled.

Syntax

IBuildCatalog.LogSuccess [=Success]

Settings

Success

If True, Search logs the names of files that are successfully searched; if False, Search does not log the names of files that are successfully searched.

Example

The following example logs the files that were successfully crawled during the building of the catalog specifiec by the KMSampleCatalog2 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")

objCatalog.LogSuccess = True

'Release objects
objCatalog = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

LogExcluded, Logs


Mappings Property

This read-only property specifies the list of mappings (IMappings interface) that specify from where a file is searched (the crawler access location) to where a file is displayed to site visitors (the display location).

Syntax

IBuildCatalog.Mappings

Example

The following example displays the mappings for all of the catalog definitions.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objMappings, objMapping

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  Set objMappings = objCatalog.objMappings
  Wscript.Echo "objCatalog " & objCatalog.Name

  If objMappings.Count = 0 Then
    Wscript.Echo "has no mappings."
  Else
    For Each objMapping in objMappings
      Wscript.Echo "maps " & objMapping.From & " to " _
        & objMapping.To
    Next
    Wscript.Echo ""
  End If
Next

'Release objects
Set objMapping  = Nothing
Set objMappings = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Extensions, IMappings Interface


Name Property

This read-only property specifies the name of the catalog definition.

Syntax

IBuildCatalog.Name

Example

The following example displays the names of all of the catalog definitions.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  Wscript.Echo "objCatalog " & objCatalog.Name
Next

'Release objects
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Status, StatusCode


NotificationSource Property

This property specifies the source string that identifies a gather Search catalog.

Syntax

IBuildCatalog.NotificationSource [=Source]

Settings

Source

The source string that identifies a gather Search catalog.

Remarks

This property is ignored if the ProjectType property is Crawl. The notification string with which you call the IGatherNotify.Init method must match this property.

Example

The following example sets the notification source for the KMSampleCatalog1 catalog definition to NotificationTest.

Option Explicit
On Error Resume Next

Const Notification = 0

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog = objCatalogs("KMSampleCatalog1")

objCatalog.ProjectType = Notification
objCatalog.NotificationSource = "NotificationTest"

'Release objects
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

IGatherNotify, ProjectType


PreviousBuildProperties Property

This read-only property specifies information about the previous build (as an ICatalogProperties interface).

Syntax

IBuildCatalog.ICatalogProperties

Example

The following example displays the previous build properties for the KMSampleCatalog1 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objPrevBldProps

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog = objCatalogs("KMSampleCatalog1")
Set objPrevBldProps = objCatalog.PreviousBuildProperties

'Show the properties
Wscript.echo "objCatalog " & objCatalog.Name & " properties:"
Wscript.echo "  Build date:    " & objPrevBldProps.BuildDate
Wscript.echo "  # docs:      " & objPrevBldProps.NumberOfDocuments
Wscript.echo "  Size of index:   " & objPrevBldProps.IndexSize _
  & " (MBytes)"
Wscript.echo "  Size of property store " _
  & objPrevBldProps.PropertyStoreSize & " (MBytes)"
Wscript.echo "  # unique keys:   " & objPrevBldProps.UniqueKeyCount
Wscript.echo "  Crawl number:    " & Prop objPrevBldProps erty.PropSeqNum
Wscript.Echo ""

'Release objects
Set objPrevBldProps = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

CurrentBuildProperties


ProjectType Property

This property specifies the type of project definition.

Syntax

IBuildCatalog.ProjectType

Remarks

If ProjectType is Crawl, the catalog definition is for a crawl; if ProjectType is Notification, the catalog definition is for a notification and you must also set the NotificationSource property.

Example

The following example displays the project type for all catalog definitions.

Option Explicit
On Error Resume Next

Const Crawl = 1
Const Notification = 0

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  Select Case objCatalog.ProjectType
    Case Crawl
    Wscript.Echo "The project type For " & objCatalog.Name _
      & " is Crawl"
    Case Notification
    Wscript.Echo "The project type For " & objCatalog.Name _
      & " is Notification"
  End Select
Next

'Release objects
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

IGatherNotify, NotificationSource


Protocols Property

This read-only property specifies the protocols (an IProtocols interface) that Search uses when crawling.

Syntax

IBuildCatalog.Protocols

Remarks

The types of protocols are:

File

Search crawls use FILE protocol.

HTTP

Search crawls use HTTP protocol.

Exch

Search crawls use Exchange folders.

Example

The following example displays which protocols are searched for all catalog definitions.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, Protocols, Protocol

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  Set Protocols = objCatalog.Protocols
  Wscript.Echo objCatalog.Name & " searches the following protocols:"

  For Each Protocol in Protocols
    If Protocol.Included Then Wscript.Echo Protocol.Urlname
  Next

Next

'Release objects
Set Protocol  = Nothing
Set Protocols = Nothing
Set objCatalogs  = Nothing
Set objBuildServer  = Nothing
Set objSearchAdmin  = Nothing

See Also

Extensions, IProtocols interface


Schema Property

This read-only property specifies document properties (ISearchSchema interface) that Search indexes or retrieves when building a catalog.

Syntax

IBuildCatalog.Schema

Example

The following example displays the categories that Search retrieves for the KMSampleCatalog2 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, Schema, Columns, Column

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set Schema   = objCatalog.Schema

Wscript.Echo "objCatalog " & objCatalog.Name & " retrieves these categories:"

For Each Column in Schema.Columns
  If IColumn.Retrieve Then Wscript.Echo "  " & IColumn.Name
Next

'Release objects
Set Column   = Nothing
Set Schema   = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

ISearchSchema interface


SearchServers Property

This read-only property specifies the list of search server names (collection of ICatalogSearchServerList interfaces) to which the catalog is propagated.

Syntax

IBuildCatalog.SearchServers

Example

The following example displays the search servers for all catalogs.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, Server

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  Wscript.Echo objCatalog.Name & " is propagated to search servers:"

  For Each Server in objCatalog.SearchServers
    Wscript.Echo "  " & Server.Name
  Next
Next

'Release objects
Set Server   = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

BuildServer, ICatalogSearchServerList interface


Sites Property

This read-only property specifies the sites (ISiteRestrictions interface) that Search crawls or avoids.

Syntax

IBuildCatalog.Sites

Example

The following example displays the sites for all catalog definitions.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  Set objSites = objCatalog.Sites

  If objSites.Count = 0 Then
     Wscript.Echo objCatalog.Name & " does not include/exclude any sites."
   Else
    Wscript.Echo objCatalog.Name & " includes/excludes the following sites:"

    For Each objSite in objSites
    If Restriction.Included Then
           Wscript.Echo "  " & objSite.Name & " is included."
         Else
           Wscript.Echo "  " & objSite.Name & " is excluded."
         End If
    Next

    Wscript.Echo ""
   End If
Next

'Release objects
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

StartPages, ISiteRestrictions interface


StartPages Property

This read-only property specifies the locations (IStartPages interface) where the crawl starts.

Syntax

IBuildCatalog.StartPages

Example

The following example displays the start locations for all catalog definitions.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, StartPages, StartPage

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  StartPages = objCatalog.StartPages
  If StartPages.Count = 0 Then
    Wscript.Echo objCatalog.Name & " has no start pages."
  Else
    For Each StartPage in StartPages
    Wscript.Echo StartPage.Url
    Next
  End If
Next

'Release objects
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See also

Sites


Status Property

This read-only property specifies the status of the catalog.

Syntax

IBuildCatalog.Status

Example

The following example displays the status of all catalogs.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  Wscript.Echo "Status For " & objCatalog.Name & ": " _
    & objCatalog.Status
Next

'Release objects
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

StatusCode


StatusCode Property

This read-only property specifies the status code of the catalog.

Syntax

IBuildCatalog.StatusCode

Remarks

The following status codes are defined:

0

Idle

1

Crawling

2

Paused

3

Throtted

4

Initializing

5

Shut down

6

Crawling incrementally

32

(Index) Crawling

64

Compiling the catalog

128

Propagating the catalog

320

Paused (disk full)

640

Retrying propagation

1024

Flushing

Example

The following example displays the status code of all catalogs.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  Wscript.Echo "Status code For " & objCatalog.Name & ": " _
    & objCatalog.StatusCode
Next

'Release objects
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Status


IBuildCatalogs Interface

This interface manages a list of catalog definitions (collection of IBuildCatalogSR_IBuildCatalog_Interface interfaces).

Hierarchy

ISearchAdmin.IBuildServer

The following table briefly describes this interface's methods and properties.

Method | Description
Add | Adds a catalog definition.
Remove | Removes a catalog definition.
Property | Description
Count | The number of catalog definitions.
Item | Accesses a catalog definition.


Accessing an IBuildCatalogs Object

You access an IBuildCatalogs object by calling the IBuildServer.BuildCatalogs property, as in the following example, where objCatalogs is the name you give to the IBuildCatalogs object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

...

'Release objects
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


Add Method

This method adds a catalog definition (IBuildCatalog interface).

Syntax

IBuildCatalogs.Add(Catalog, Path)

Parameters

Catalog

The catalog definition to add.

Path

The full path to the catalog definition to add.

Example

The following example adds the catalog definition KMSampleCatalog3 from C:\Catalogs.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

objCatalogs.Add("KMSampleCatalog3", "C:\objCatalogs")

'Release objects
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Item


Remove Method

This method removes a catalog definition (IBuildCatalog interface).

Syntax

IBuildCatalogs.Remove(Catalog)

Parameters

Catalog

The catalog definition to remove.

Example

The following example removes the catalog definition KMSampleCatalog2.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

objCatalogs.Remove("KMSampleCatalog1")

'Release objects
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Item


Item Property

This read-only property accesses a catalog definition (IBuildCatalog interface) by name.

Syntax

IBuildCatalogs[.Item(Catalog)]

Parameters

Catalog

The catalog to access.

Remarks

Since IBuildCatalogs is a collection, you need only include Item to access an IBuildCatalog object by name (see the following Example).

Example

The following example accesses the catalog definition KMSampleCatalog1 and then displays its name.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")

Wscript.Echo "Accessed catalog " & objCatalog.Name

'Release objects
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Remove


Count Property

This read-only property specifies the number of catalog definitions (IBuildCatalog interfaces).

Syntax

IBuildCatalogs.Count

Example

The following example displays the number of catalog definitions.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

Wscript.Echo "There are " & objCatalogs.Count _
  & " catalog definitions."

'Release objects
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Item, Remove


IBuildServer Interface

This interface manages catalog definitions (through the IBuildCatalogs interface) and catalog build server properties.

Hierarchy

ISearchAdmin

The following table briefly describes this interface's methods and properties.

Method | Description
ExportCatalog | Saves a catalog definition.
ImportCatalog | Restores a catalog definition.
LoadConfiguration | Restores a catalog build server configuration.
SaveConfiguration | Stores a catalog build server configuration.
SetDefaultAccount | Specifies the default content access account information for a Domain\User.
SetDefaultPluginAccount | Specifies the default plugin account information for administrative access.
SetProxySettings | Specifies the proxy configuration.
Property | Description
BuildCatalogs | The IBuildCatalogs interface on the host.
ConnectTimeout | How long to wait, in seconds, for a connection when accessing a site.
DataTimeout | How long to wait, in seconds, for data to arrive when accessing a site.
DefaultAccountName | The content access name to use when crawling documents on other hosts and sites over the network.
DefaultCatalogsLocation | The location in the file system where the catalog definitions are stored.
DefaultLogsLocation | The location in the file system where the catalog build server log files are stored.
DefaultPluginAccountName | The administrative access account name.
EmailAddress | The email address to which Search logs when crawling sites.
PerformanceLevel | The amount of system resources applied to building catalogs.
ProxyAddress | The name of the proxy server through which Search operates.
ProxyBypassAddressesList | The addresses for which the proxy server is bypassed.
ProxyBypassForLocalAddresses | Whether the proxy server is bypassed for local (intranet) addresses.
ProxyPortNumber | The port on the proxy server to which Search connects.
ProxyUsageSetting | The proxy server configuration.
SearchAdmin | The parent SearchAdmin object.
Sites | The list of sites (IServers interface) with access frequency restrictions.
TempPath | The directory where Search stores temporary files.
UserAgent | The user agent used when crawling.


Accessing an IBuildServer Object

You access an IBuildServer object by calling the SearchAdmin.BuildServer property, as in the following example, where objBuildServer is the name you give to the IBuildServer object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

...

'Release objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


ExportCatalog Method

This method saves a catalog definition.

Syntax

IBuildServer.ExportCatalog(Name, Path)

Parameters

Name

The name of the catalog definition to export.

Path

The full path where the exported catalog definition is saved.

Remarks

By default the Search export operation in both MMC and WebAdmin export catalog definition configuration files with a SBP file extension. Microsoft recommends that you save your catalog definition configuration files with a SBP file extension.

Example

The following example saves the catalog definition to the file MyCatalog.sbp in the directory C:\Backup.

This doesn't seem to work as advertised. See my email dated 12/30/97.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

objBuildServer.ExportCatalog "MyCatalog", "C:\Backup\MyCatalog.sbp"

'Release objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

ImportCatalog


ImportCatalog Method

This method restores a catalog definition.

Syntax

IBuildServer.ImportCatalog(Name, Path)

Parameters

Name

The name of the catalog definition to import.

Path

The full pathname to where the imported catalog definition is stored.

Remarks

By default, the Search import operation in both MMC and WebAdmin import catalog definition configuration files with a SBP file extension.

Example

The following example imports the catalog MyCatalog.sbp from the directory C:\Backup.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

objBuildServer.ImportCatalog "MyCatalog", "C:\Backup\MyCatalog.sbp"

...

'Release objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

ExportCatalog


LoadConfiguration Method

This method restores a catalog build server configuration.

Syntax

IBuildServer.LoadConfiguration(Path)

Parameters

Path

The full pathname to the file containing the build server configuration information.

Remarks

By default, the Search save catalog build server configuration operations in both MMC and WebAdmin loads catalog build server configuration files with a SBC file extension.

Example

The following example loads the catalog build server configuration file C:\Backup\LocalHost.sbc.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

objBuildServer.LoadConfiguration("C:\Backup\LocalHost.sbc")

'Release objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

SaveConfiguration


SaveConfiguration Method

This method stores a catalog build server configuration.

Syntax

IBuildServer.SaveConfiguration(Path)

Parameters

Path

The full path to the file containing the configuration information.

Remarks

By default the Search save configuration operation in both MMC and WebAdmin export catalog files with a SBC file extension. Microsoft recommends that you save your catalog build server configuration files with a SBC file extension.

Example

The following example saves the configuration to the file C:\Backup\LocalHost.sbc.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

objBuildServer.SaveConfiguration("C:\Backup\LocalHost.sbc")

'Release objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

LoadConfiguration


SetDefaultAccount Method

This method specifies the default content access account information for a Domain\User.

Syntax

IBuildServer.SetDefaultAccount(Account, Password)

Parameters

Account

The Domain\Username for the account.

Password

The password for the account.

Example

The following example sets the default account to Test\SSAdmin with the password "PikePlace007".

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

objBuildServer.SetDefaultAccount("Test\SSAdmin", "PikePlace007")

'Release objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

DefaultAccountName


SetDefaultPluginAccount Method

This method specifies the default plugin (indexer) account information for administrative access.

Syntax

IBuildServer.SetDefaultPluginAccount(Account, Password)

Parameters

Account

The Domain\Username for the account.

Password

The password for the account.

Example

The following example sets the administrative access to Search1\Admin with the password "SSSearch1".

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

objBuildServer.SetDefaultPluginAccount("Search1\Admin", "SSSearch1")

'Release objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

DefaultPluginAccountName


SetProxySettings Method

This method specifies the proxy configuration.

Syntax

IBuildServer.SetProxySettings(Usage, Address, Port, BypassLocal, BypassAddresses)

Parameters

Usage

The proxy server configuration:

0

Use the default system proxy server.

1

Do not use a proxy server.

2

Use the proxy server specified by the ProxyAddress property.

Address

The address of the proxy server through which Search operates.

Port

The port on the proxy server to which Search connects. By default this is 80.

BypassLocal

Whether the proxy server is bypassed for local addresses.

0

Use the proxy server for local addresses.

1

Bypass the proxy server for local addresses.

BypassAddresses

The addresses for which the proxy server is bypassed. If more than one address, the addresses must be separated by semicolons (;). See the Example.

Example

The following example specifies that Search uses the proxy server MyProxy on port 80, bypassing the proxy server for local addresses, and bypassing the proxy server for addresses MySite and MyOtherSite.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

objBuildServer.SetProxySettings(2, "MyProxy", 80, 1, _
  "MySite; MyOtherSite")

'Release objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

ProxyAddress, ProxyBypassAddressesList, ProxyBypassForLocalAddresses, ProxyPortNumber, ProxyUsageSetting


BuildCatalogs Property

This read-only property specifies the IBuildCatalogs object on the host.

Syntax

IBuildServer.BuildCatalogs

Example

The following example accesses the IBuildCatalogs object, listing the names of the catalog definitions.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog

Set objSearchAdmin   = CreateObject("Search.SearchAdmin.1")
Set objBuildServer   = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  Wscript.Echo "Catalog definition: " & objCatalog.Name
Next

'Release objects
Set objCatalogs = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing

See Also

IBuildCatalog interface, IBuildCatalogs interface


ConnectTimeout Property

This property specifies how long, in seconds, to wait for a connection when accessing a site.

Syntax

IBuildServer.ConnectTimeout

Remarks

The default duration is 20 seconds.

Example

The following example displays the current connection timeout duration, in seconds.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

Wscript.Echo "The current connection timeout is " _
  & objBuildServer.ConnectTimeout & " seconds."

'Release Objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

DataTimeout


DataTimeout Property

This property specifies how long, in seconds, to wait for data to arrive when accessing a site.

Syntax

IBuildServer.DataTimeout

Remarks

The default duration is 20 seconds.

Example

The following example displays the current data timeout duration, in seconds.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

Wscript.Echo "The current data timeout is " _
  & objBuildServer.DataTimeout & " seconds."

'Release Objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

ConnectTimeout


DefaultAccountName Property

This read-only property specifies the content access name to use when crawling documents on other hosts and sites over the network.

Syntax

IBuildServer.DefaultAccountName

Remarks

This user account must have read access to the hosts and sites on the network.

Example

The following example displays the default content access name.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

Wscript.Echo "The default account name is: " & _
  objBuildServer.DefaultAccountName

...

'Release Objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

EmailAddress


DefaultCatalogsLocation Property

This property specifies the location in the file system where the catalog definitions are stored.

Syntax

IBuildServer.DefaultCatalogsLocation [=Directory]

Parameters

Directory

The directory where the catalog definitions are stored.

Remarks

If Directory does not exist, Search creates it.

Example

The following example changes the default catalog definitions location to the Misc directory under the current catalog location directory.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

objBuildServer.DefaultCatalogsLocation = _
  objBuildServer.DefaultCatalogsLocation & "\Misc"

'Release Objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

BuildCatalogs, DefaultLogsLocation


DefaultLogsLocation Property

This property specifies the location in the file system where the catalog build server log files are stored.

Syntax

IBuildServer.DefaultLogsLocation

Remarks

If you specify a directory that does not exist, Search creates it.

Example

The following example sets the default catalog build server log file location to D:\Catalogs\Logs.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

objBuildServer.DefaultLogsLocation = "D:\Catalogs\Logs"

'Release objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

DefaultCatalogsLocation


DefaultPluginAccountName Property

This read-only property specifies the administrative access account name.

Syntax

IBuildServer.DefaultPluginAccountName

Example

The following example displays the administrative access account name.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

Wscript.Echo "The administrative access account name is " _
  & objBuildServer.DefaultPluginAccountName

'Release Objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

SetDefaultPluginAccount


EmailAddress Property

This property specifies the email address to which Search logs when crawling sites.

Syntax

IBuildServer.EmailAddress

Remarks

The address should be in the form user@host.

Example

The following example displays the email address.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

Wscript.Echo "The email address is: " & objBuildServer.EmailAccount

'Release Objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

UserAgent


PerformanceLevel Property

This property specifies the amount of system resources applied to building catalogs.

Syntax

IBuildServer.PerformanceLevel

Remarks

PerformanceLevel has a range of from 1, which runs Search in the background, to 5, which dedicates all of the host machine's resources to Search.

Example

The following example displays the level of performance.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, PerfLevel

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

PerfLevel = objBuildServer.PerformanceLevel

Select Case PerfLevel
  Case 1
    Wscript.Echo "Search runs in the background"
  Case 2
    Wscript.Echo "Search runs at a low priority"
  Case 3
    Wscript.Echo "Search runs at a medium priority"
  Case 4
    Wscript.Echo "Search runs at a high priority"
  Case 5
    Wscript.Echo "Host resources are dedicated to Search"
End Select

'Release Objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

ConnectTimeout, DataTimeout


ProxyAddress Property

This read-only property specifies the name of the proxy server through which Search operates.

Syntax

IBuildServer.ProxyAddress

Remarks

This property is empty if you specify either the "Do not connect using a proxy server" or "Use the system default proxy server" setting in MMC. This property is set by the second argument to the SetProxySettings method.

Example

The following example displays the proxy server address used by Search.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, ProxyAdd

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

ProxyAdd = objBuildServer.ProxyAddress

If ProxyAdd = "" Then
  Wscript.Echo "Proxy addressing is not used."
Else
  Wscript.Echo "The Search proxy address is: " & ProxyAdd
End If

'Release Objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

SetProxySettings


ProxyBypassAddressesList Property

This read-only property specifies the addresses for which the proxy server is bypassed.

Syntax

IBuildServer.ProxyBypassAddresses

Remarks

This property is set by the fifth argument to the SetProxySettings method.

Example

The following example displays the addresses for which the proxy server is bypassed.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, ProxyAdd, ProxyBypass

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

ProxyAdd = objBuildServer.ProxyAddress

If ProxyAdd = "" Then
  Wscript.Echo "Proxy addressing is not used."
Else
  ProxyBypass = objBuildServer.ProxyBypassAddressesList
  If ProxyBypass <> "" Then
    Wscript.Echo "The proxy server is bypassed For addresses:
    Wscript.Echo  ProxyBypass
  End If
End If

...

'Release Objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

SetProxySettings


ProxyBypassForLocalAddresses Property

This read-only property specifies whether the proxy server is bypassed for local (intranet) addresses.

Syntax

IBuildServer.ProxyBypassForLocalAddresses

Remarks

ProxyBypassForLocalAddresses has one of the following values:

0

The proxy server is used for local addresses.

1

The proxy server is bypassed for local addresses.

This property is set by the fourth argument to the SetProxySettings method.

Example

The following example displays whether the proxy server is bypassed for local addresses.

Option Explicit
On Error Resume Next

Const ByPassLocal = 1

Dim objSearchAdmin, objBuildServer, ProxyAdd, ProxyBypassLocal

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

ProxyAdd = objBuildServer.ProxyAddress

If ProxyAdd = "" Then
  Wscript.Echo "Proxy addressing is not used."
Else
  ProxyBypassLocal = objBuildServer.ProxyBypassForLocalAddresses
  If ProxyBypassLocal = ByPassLocal Then
    Wscript.Echo "The proxy server is bypassed For local addresses."
  Else
    Wscript.Echo "The proxy server is used For local addresses."
  End If
End If

'Release Objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

SetProxySettings


ProxyPortNumber Property

This read-only property specifies the port on the proxy server to which Search connects.

Syntax

IBuildServer.ProxyPortNumber

Remarks

By default, Search connects to port 80 on the proxy server, as expected.

This property is set by the third argument to the SetProxySettings method.

Example

The following example displays the port on the proxy server to which Search connects.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, ProxyAdd

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

ProxyAdd = objBuildServer.ProxyAddress

If ProxyAdd = "" Then
  Wscript.Echo "Proxy addressing is not used."
Else
  Wscript.Echo "The proxy port number is: " & objBuildServer.ProxyPortNumber
End If

'Release Objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

SetProxySettings


ProxyUsageSetting Property

This read-only property specifies the proxy server configuration.

Syntax

IBuildServer.ProxyUsageSetting

Remarks

ProxyUsageSetting can have one of the following values:

0

Uses the default system proxy server.

1

Does not use a proxy server.

2

Uses the proxy server specified by the ProxyAddress property.

This property is set by the first argument to the SetProxySettings method.

Example

The following example displays the proxy usage setting.

Option Explicit
On Error Resume Next

Const UseSystemDefaultProxyServer = 0
Const DontUseProxyServer          = 1
Const UseSpecifiedProxyServer     = 2

Dim objSearchAdmin, objBuildServer, ProxySetting

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

ProxySetting = objBuildServer.ProxyUsageSetting

If ProxySetting = DontUseProxyServer Then
  Wscript.Echo "Search does not use a proxy server"
End If

If ProxySetting = UseSystemDefaultProxyServer Then
  Wscript.Echo "Search is using the default system proxy server"
End If

If ProxySetting = UseSpecifiedProxyServer Then
  Wscript.Echo "Search is using the proxy server " &
    objBuildServer.ProxyAddress & "
    on port " & objBuildServer.ProxyPortNumber
End If

'Release Objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

SetProxySettings


SearchAdmin Property

This read-only property specifies the parent ISearchAdmin object.

Syntax

IBuildServer.SearchAdmin

Remarks

This property is a convenient way to get to the parent interface of the current IBuildServer object.

Example

The following example displays the host name of the associated ISearchAdmin object.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objBuildServerParent

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

Set objBuildServerParent = objBuildServer.SearchAdmin

If objBuildServerParent is objSearchAdmin Then
  Wscript.Echo "Identical ISearchAdmin interfaces"
Else
  Wscript.Echo "Error! The ISearchAdmin interfaces differ!"
End If

'Release Objects
Set objBuildServerParent = Nothing
Set objBuildServer       = Nothing
Set objSearchAdmin       = Nothing

See Also

ISearchAdmin


Sites Property

This read-only property specifies a list of sites (IServers interface) with access frequency restrictions.

Syntax

IBuildServer.Sites

Example

The following example displays the names of the sites with access frequency restrictions.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, ServersObj, Site, Hit

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set ServersObj = objBuildServer.Sites

Wscript.Echo "The following sites have timing restrictions: "

For Each Site in ServersObj
  Wscript.Echo Site.Name
  Hit = Site.HitInterval

  If Hit = -1 Then
    Wscript.Echo "(Request docs simultaneously)"
  elseif Hit < 0 Then
    Wscript.Echo "(Request at most " & -Hit
    & " docs simultaneously)"
  Else
    Wscript.Echo "(Wait " & Hit & " seconds between requests)"
  End If
Next

'Release objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

IServers Interface


TempPath Property

This property specifies the directory where Search stores temporary files.

Syntax

IBuildServer.TempPath [=Directory]

Parameters

Directory

The full pathname to the directory where Search stores temporary files.

Example

The following example specifies that Search stores temporary files in C:\Temp.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

objBuildServer.TempPath = "C:\Temp"

...

'Release Objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

DefaultCatalogsLocation, DefaultLogsLocation


UserAgent Property

This property specifies the user agent used when crawling.

Syntax

IBuildServer.UserAgent [=Agent]

Parameters

Agent

The user agent.

Example

The following example displays the value of the user agent.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

Wscript.Echo "The user agent is: " & objBuildServer.UserAgent

'Release Objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

EmailAddress


ICatalogProperties Interface

This interface specifies the properties of a catalog.

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog ISearchAdmin.ISearchServer.ISearchCatalogs.ISearchCatalog

The following table briefly describes this interface's properties (all are read-only).

Property | Description
BuildDate | The date and time when the catalog was built.
IndexSize | The size, in megabytes, of the catalog.
NumberOfDocuments | The number of documents in the catalog.
PropertyStoreSize | The size, in megabytes, of the property store.
PropSeqNum | The crawl number.
UniqueKeyCount | The number of unique keys in the catalog.


Accessing ICatalogProperties Objects

You access ICatalogProperties objects by calling the IBuildCatalog.CurrentBuildProperties property for information on the current build, the IBuildCatalog.PreviousBuildProperties property for information on the previous build or the ISearchCatalog.Properties property for information on a searchable catalog. The following example displays all of the catalog properties for the KMSampleCatalog1 catalog definition:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, Property

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set Property = objCatalog.PreviousBuildProperties

'Show the properties
Wscript.echo "objCatalog " & objCatalog.Name & " properties:"
Wscript.echo "  Build date:    " & Property.BuildDate
Wscript.echo "  # docs:      " & Property.NumberOfDocuments
Wscript.echo "  Size of index:   " & Property.IndexSize _
  & " (MBytes)"
Wscript.echo "  Size of property store " _
  & Property.PropertyStoreSize & " (MBytes)"
Wscript.echo "  # unique keys:   " & Property.UniqueKeyCount
Wscript.echo "  Crawl number:    " & Property.PropSeqNum
Wscript.Echo ""

'Release objects
Set Property = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


BuildDate Property

This read-only property specifies the date and time when the catalog was built.

Syntax

ICatalogProperties.BuildDate

Remarks

BuildDate is 0 (zero) if no build has been done.

Example

See Accessing ICatalogProperties Objects.

See Also

IndexSize


IndexSize Property

This read-only property specifies the size, in megabytes, of the catalog.

Syntax

ICatalogProperties.IndexSize

Example

See Accessing ICatalogProperties Objects.

See Also

BuildDate


NumberOfDocuments Property

This read-only property specifies the number of documents in the catalog.

Syntax

ICatalogProperties.NumberOfDocuments

Example

See Accessing ICatalogProperties Objects.

See Also

IndexSize


PropertyStoreSize Property

This read-only property specifies the size, in megabytes, of the property store.

Syntax

ICatalogProperties.PropertyStoreSize

Example

See Accessing ICatalogProperties Objects.

See Also

NumberOfDocuments


PropSeqNum Property

This read-only property specifies the crawl number.

Syntax

ICatalogProperties.PropSeqNum

Remarks

The sequence number starts at 0 (zero).

Example

See Accessing ICatalogProperties Objects.

See Also

PropertyStoreSize


UniqueKeyCount Property

This read-only property specifies the number of unique keys in the catalog.

Syntax

ICatalogProperties.UniqueKeyCount

Example

See Accessing ICatalogProperties Objects.

See Also

PropSeqNum


ICatalogSearchServerList Interface

This interface is a list of search servers (collection of IIndexDs objects) to which a catalog (IBuildCatalog) is propagated.

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog

The following table briefly describes this interface's methods and property.

Method | Description
Add | Adds a search server to the list of search servers to which a catalog definition is propagated.
Remove | Removes a search server from the list of search servers to which a catalog definition is propagated.
Property | Description
Count | The number of search servers to which a catalog definition is propagated.
Item | Accesses a search server to which a catalog definition is propagated.


Accessing an ICatalogSearchServerList Object

You access an ICatalogSearchServerList object by calling the IBuildCatalog.SearchServers property, as in the following example, where objServers is the name you give to the ICatalogSearchServerList object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objServers

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objServers  = objCatalog.SearchServers

...

'Release objects
Set objServers  = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


Add Method

This method adds a search server to the list of search servers to which a catalog is propagated.

Syntax

ICatalogSearchServerList.Add(Server)

Parameters

Server

The server that is added to the list.

Example

The following example adds the server KnowledgeServer1 to the list of servers to which the KMSampleCatalog1 catalog definition is propagated.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objServers

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objServers  = objCatalog.SearchServers

objServers.Add("KnowledgeServer1")

'Release objects
Set objServers  = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

IIndexDs interface, Remove


Remove Method

This method removes a search server from the list of search servers to which a catalog definition is propagated.

Syntax

ICatalogSearchServerList.Remove(Server)

Parameters

Server

The server that is removed from the list.

Example

The following example removes the server KnowledgeServer1 from the list of servers to which the KMSampleCatalog1 catalog definition is propagated.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objServers

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objServers  = objCatalog.SearchServers

objServers.Remove("KnowledgeServer1")

'Release objects
Set objServers  = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Add, IIndexDs interface


Count Property

This read-only property specifies the number of search servers to which a catalog definition is propagated.

Syntax

ICatalogSearchServerList.Count

Example

The following example displays the number of search server to which all catalog definitions are propagated.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objServers

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  Set objServers = objCatalog.SearchServers
  Wscript.Echo objCatalog.Name & " is propated to " & objServers.Count
    & " servers."
Next

'Release objects
Set objServers  = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Item


Item Property

This read-only property accesses a search server (IIndexDs object) to which a catalog definition is propagated.

Syntax

ICatalogSearchServerList[.Item(Server)]

Parameters

Server

The server that is accessed.

Remarks

Since ICatalogSearchServerList is a collection, you need only include Item to access an IIndexDs object by name (see the following Example).

Example

The following example lists all of the servers to which the KMSampleCatalog2 catalog definition is propated.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objServers

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")

For Each objServers in objCatalog.SearchServers
  Wscript.Echo objServers.Name
Next

'Release objects
Set objServers  = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Count, IIndexDs interface


IColumn Interface

This interface specifies information about documents that Search indexes or retrieves while crawling.

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog.ISearchSchema.IColumns

The following table briefly describes this interface's properties.

Note Changes to these properties do not take effect until you call the ISearchSchema.Save method.

Property | Description
Description | A textual description of the column.
Index | Whether Search indexes the information in this column.
Length | Reserved (set to 0).
Name | The name of the column.
PropGuid | The property set GUID that together with PropPid, uniquely identifies this column for indexing, searching, and retrieving.
PropPid | The property ID that together with PropGuid, uniquely identifies this column
Retrieve | Whether Search retrieves the information in this column.
Type | The data type of the column.


Creating an IColumn Object

You create an IColumn object by calling the IColumns.Add method, as in the following example, where objColumn is the name you give to the IColumn object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSchema, objColumns, objColumn
Dim Name, Description, Type, PropGuid, PropPid, Index, Retrieve, Length

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objSchema   = objCatalog.Schema
Set objColumns  = objSchema.Columns

Name        = " HitCount"
Description = "The number of hits (words matching query) in file"
Type        = "I4"
PropGuid    = "49691c90-7e17-101a-a91c-08002b2ecda9"
PropPid     = "4"
Index       = False
Retrieve    = True
Length      = 0

Set objColumn = objColumns.Add Name, Description, Type, PropGuid, _
  PropPid, Index, Retrieve, Length

...

'Release objects
Set objColumn   = Nothing
Set objColumns  = Nothing
Set objSchema   = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


Accessing IColumn Objects

You can access a specific IColumn object by calling the IColumns.Item property. Since IColumns is a collection, you can access all IColumn objects using a for each loop, as in the following example, where objColumn is the name you give to the IColumn object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSchema, objColumns, objColumn

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objSchema   = objCatalog.objSchema
Set objColumns  = objSchema.objColumns

Wscript.Echo "The schema For " & objCatalog.Name & " has these columns:"

For Each objColumn in objColumns
  Wscript.Echo "  Name:         " & objColumn.Name
  Wscript.Echo "  Description:  " & objColumn.Description
  Wscript.Echo "  PropGuid:     " & objColumn.PropGuid
  Wscript.Echo "  PropPid:      " & objColumn.PropPid

  If objColumn.Retrieve Then
    Wscript.Echo "  Retrieved:    Yes"
  Else
    Wscript.Echo "  Retrieved:    No"
  End If

  If objColumn.Index Then
    Wscript.Echo "  Indexed:      Yes"
  Else
    Wscript.Echo "  Indexed:      No"
  End If

  Wscript.Echo "   Type:        " & objColumn.Type
  Wscript.Echo "   Length:      " & objColumn.Length
  Wscript.Echo ""

Next

'Release objects
Set objColumn   = Nothing
Set objColumns  = Nothing
Set objSchema   = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


Description Property

This property specifies a textual description of the column.

Syntax

IColumn.Description

Remarks

The description is an aid to identifying the column. There is no restriction on the size of this property.

Example

See Creating an IColumn Object.

See Also

Name


Index Property

This property specifies whether Search indexes the information in this column.

Syntax

IColumn.Index

Remarks

If Index is True, Search indexes the information in this column. If Index is False, Search does not index the information in this column.

If the filter for a particular document type does not emit this column as an indexable value, setting Index to True has no effect, and Search will not report an error when indexing documents of that type.

Example

See Creating an IColumn Object.

See Also

Retrieve


Length Property

This property is reserved.

Syntax

IColumn.Length

Remarks

Length is reserved and should always be set to zero.

See Also

Type


Name Property

This property specifies the name of the column.

Syntax

IColumn.Name

Remarks

The Name property is a text string that must begin with a lower-case letter (i.e., a-z) and can contain only other lower-case letters (a-z), integers (0-9), and underscore characters (_). Name cannot include spaces and must be unique in the Search schema.

Although the value for Name can contain lower- and upper-case characters, Search does not consider case when determining uniqueness. For example, the Name value MyTestMachine is not unique if the Name value MYTESTMACHINE already exists in the schema.

The Name property has no functional significance, although it must be unique and properly formed. Search identifies the column based on the entry in the DefineColumns.txt file that has a PropGuid and PropPid which matches this column's PropGuid and PropPid properties. Alternatively, you can use a DefineColumn call made in a Search script.

For column attributes such as HTML Meta tags where the PropPid is based on the meta name attribute, the Name property is not the same as PropPid. For such tags, PropPid can be an arbitrary string that can even contain spaces. When creating a column entry for such a column, Microsoft recommends that you choose a value for the Name property that suggests the PropPid, but contains only the allowed characters.

Search does not validate the Name property until you call the ISearchSchema.Save method.

Example

See Creating an IColumn Object.

See Also

Description


PropGuid Property

This property specifies the property set GUID and, with the PropPid property, uniquely identifies this column for indexing, search and retrieve purposes.

Syntax

IColumn.PropGuid

Remarks

The value of PropGuid is a Microsoft GUID string, such as:

   49691c90-7e17-101a-a91c-08002b2ecda9

In order for indexing and search to function for this column, the PropGuid and PropPid properties must match properties emitted by filters for the expected document types.

The combination of the PropGuid and PropPid properties must be unique in the Search schema (the comparison is not case-sensitive). Search does not check that the pair of values is unique until you call the ISearchSchema.Save method.

Example

See Creating an IColumn Object.

See Also

PropPid


PropPid Property

This property specifies the property ID and, with the PropGuid property, uniquely identifies this column for indexing, search and retrieve purposes.

Syntax

IColumn.PropPid

Remarks

The PropPid property must be a text string specifying the property ID value. The string may be either a string representation of a decimal number, or an arbitrary string of at least one character to a maximum of 128 characters.

The first character of the text string value determines whether Search interprets the value as a numeric or string value. If the first character is an integer (e.g., 0-9), then all the remaining characters must also be integers. Search converts the value to the type PRSPEC_PROPID. If the first character not an integer, Search converts the value to the type PRSPEC_LPWSTR.

The combination of the PropGuid and PropPid properties must be unique in the Search schema (the comparison is not case-sensitive). Search does not check that the pair of values is unique until you call the ISearchSchema.Save method.

Example

See Creating an IColumn Object.

See Also

PropGuid


Retrieve Property

This property specifies whether Search retrieves the information in this column.

Syntax

IColumn.Retrieve

Remarks

If Retrieve is True, Search retrieves the information in this column; If Retrieve is False, Search does not retrieve the information in this column.

If the filter for a particular document type does not emit this column as a retrievable value, setting Retrieve to True has no effect. In addition, Search will not report an error when indexing documents of that type. Many properties emitted by the HTML indexing filter, including all URL link properties, are emitted only as indexable values.

Example

See Creating an IColumn Object.

See Also

Index


Type Property

This property specifies the data type of the column.

Syntax

IColumn.Type

Remarks

The Type property can be an empty string, or one of the values in the following table..

Type | VBScript VarType
BOOL | vbBoolean
FILETIME | vbDate
I4 | vbLong
LPSTR | vbString
LPWSTR | vbString

Type is optional. You need not set it to function correctly with any value type returned by a filter. If you don't know the type of a property emitted by the indexing filter, or if the filter or filters for a property do not always emit the same value type, don't set Type. If Type is specified, it must match the value emitted by the filter, otherwise the value is discarded and not indexed.

Example

See Creating an IColumn Object.

See Also

Length


IColumns Interface

This interface is a list of columns (collection of IColumn objects) of information about documents that Search indexes or retrieves while crawling.

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog.ISearchSchema

The following table briefly describes this interface's methods and properties.

Note Changes made by these methods do not take effect until you call the ISearchSchema.Save method.

Method | Description
Add | Adds a column to the collection.
Clear | Clears the schema columns.
Remove | Removes a column.
Property | Description
Count | The number of columns.
Item | Accesses a column by name.


Accessing an IColumns Object

You access an IColumns object by calling the ISearchSchema.Columns property, as in the following example, where objColumns is the name you give to the IColumns object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSchema, objColumns

Set objSearchAdmin   = CreateObject("Search.SearchAdmin.1")
Set objBuildServer   = objSearchAdmin.BuildServer
Set objCatalogs   = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objSchema   = objCatalog.objSchema

Set objColumns  = objSchema.objColumns
...

'Release objects
Set objColumns    = Nothing
Set objSchema     = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing


Add Method

This method adds a column to the list of columns (IColumn interfaces).

Syntax

IColumns.Add(Name, Description, Type, PropGuid, PropPid, Index, Retrieve, Length)

Parameters

Name

The name of the column. Sets the Name property of the resulting column to this value.

Description

A textual description of the column. Sets the Description property of the resulting column to this value.

Type

The data type of the column. Sets the Type property of the resulting column to this value.

Type | VBScript VarType
BOOL | vbBoolean
FILETIME | vbDate
I4 | vbLong
LPSTR | vbString
LPWSTR | vbString

PropGuid

The property set GUID. Sets the PropGuid property of the resulting column to this value.

PropGuid and PropPid uniquely identify a column for indexing, searching, and retrieving.

PropPid

The property ID. Sets the PropPid property of the resulting column to this value.

Index

If True, Search indexes the information in this column.

Retrieve

If True, Search retrieves the information in this column; if False, Search does not retrieve the information in this column. Sets the Retrieve property of the resulting column to this value.

Length

Length is reserved and should always be set to zero.

Remarks

Search does not validate the values of this method's parameters until you call the ISearchSchema.Save method.

You should check the Err.Number property after both the Add and the ISearchSchema.Save methods to ensure that the column was added successfully.

Example

The following example adds the HitCount column to the schema for the KMSampleCatalog1 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSchema, objColumns, objColumn
Dim Name, Description, Type, PropGuid, PropPid, Index, Retrieve, Length

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objSchema   = objCatalog.objSchema
Set objColumns  = objSchema.objColumns

Name        = " HitCount"
Description = "The number of hits (words matching query) in file"
Type        = "I4"
PropGuid    = "49691c90-7e17-101a-a91c-08002b2ecda9"
PropPid     = "4"
Index       = False
Retrieve    = True
Length      = 0

Set objColumn = objColumns.Add Name, Description, Type, PropGuid, PropPid,
  Index, Retrieve, Length

...

'Release objects
Set objColumn   = Nothing
Set objColumns  = Nothing
Set objSchema   = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Clear, Count, IColumn interface, Remove


Clear Method

This method clears the schema columns.

Syntax

IColumns.Clear

Remarks

This method is not permanent unless you subsequently call the ISearchSchema.Save method.

Example

The following example clears all schema columns.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSchema, objColumns

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objSchema   = objCatalog.objSchema
Set objColumns  = objSchema.objColumns

objColumns.Clear

'Release objects
Set objColumns  = Nothing
Set objSchema   = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Count, Remove


Remove Method

This method removes a column (IColumn interface) from the schema.

Syntax

IColumns.Remove(Column)

Parameters

Column

A text string specifying the name of the column to remove from the schema.

Example

The following example removes the VBScript column from the schema.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSchema, objColumns

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objSchema   = objCatalog.objSchema
Set objColumns  = objSchema.objColumns

objColumns.Remove("VBScript")

'Release objects
Set objColumns  = Nothing
Set objSchema   = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Add, Count


Count Property

This read-only property specifies the number of columns (IColumn interfaces) in the schema.

Syntax

IColumns.Count

Example

The following example displays the number of columns in the schema for the KMSampleCatalog1 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSchema, objColumns

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objSchema   = objCatalog.objSchema
Set objColumns  = objSchema.objColumns

Wscript.Echo objCatalog.Name & " has " & objColumns.Count & " columns."

'Release objects
Set objColumns  = Nothing
Set objSchema   = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Add, Remove


Item Property

This read-only property accesses a column (IColumn interface) by its Name property.

Syntax

IColumns[.Item(Column)]

Parameters

Column

An optional text string specifying the column to access.

Remarks

Since IColumns is a collection, you need only include Item to access an IColumn object by name (see the following Example).

Example

The following example displays the name of the columns for the KMSampleCatalog1 catalog definition's schema.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSchema, objColumns, objColumn

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objSchema   = objCatalog.objSchema
Set objColumns  = objSchema.objColumns

Wscript.Echo objCatalog.Name & " has the following schema columns:"

For Each objColumn in objColumns
  Wscript.Echo "  " & objColumn.Name
Next

'Release objects
Set objColumn   = Nothing
Set objColumns  = Nothing
Set objSchema   = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

IColumn, Count


IExtension Interface

This interface is a filename extension that Search crawls or avoids when building a catalog.

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog.IExtensions

The following table briefly describes this interface's property.

Property | Description
Extension | The filename extension to include or exclude.


Creating an IExtension Object

You create an IExtension objects by calling the IExtensions.Add method, as in the following example, where objExtension is the name you give to the IExtension object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objExtensions, objExtension

Set objSearchAdmin   = CreateObject("Search.SearchAdmin.1")
Set objBuildServer   = objSearchAdmin.BuildServer
Set objCatalogs   = objBuildServer.BuildCatalogs
Set objCatalog    = objCatalogs("KMSampleCatalog1")
Set objExtensions = objCatalog.objExtensions

Set objExtension = objExtensions.Add("TMP")

...

'Release objects
Set objExtension  = Nothing
Set objExtensions = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing


Extension Property

This read-only property specifies an extension that Search includes or excludes when building a catalog.

Syntax

IExtension.Extension

Example

See Creating an IExtension Object.


IExtensions Interface

This interface is a list of filename extensions (collection of IExtension objects) that Search crawls or avoids when building a catalog.

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog

The following table briefly describes this interface's methods and properties.

Method | Description
Add | Adds an extension to the list.
Remove | Removes an extension from the list.
Property | Description
Count | The number of extensions in the list.
IncludedExtension | Whether the list is of included or excluded filename extension.
Item | Accesses a log in the list of extensions.


Accessing an IExtensions Object

Accessing an IExtensions Objects

You access an IExtensions object by calling the IBuildCatalog.Extensions property, as in the following example, where objExtensions is the name you give to the IExtensions object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objExtensions

Set objSearchAdmin   = CreateObject("Search.SearchAdmin.1")
Set objBuildServer   = objSearchAdmin.BuildServer
Set objCatalogs   = objBuildServer.BuildCatalogs
Set objCatalog    = objCatalogs("KMSampleCatalog2")
Set objExtensions = objCatalog.objExtensions("KMSampleCatalog1")

...

'Release objects
Set objExtensions = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing


Add Method

This method adds an extension to the list.

Syntax

IExtensions.Add(Extension)

Parameters

Extension

The filename extension to add to the list of extensions to crawl or avoid.

Example

The following example adds the TMP extension to the list of filename extensions to avoid for the KMSampleCatalog1 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objExtensions, objExtension

Set objSearchAdmin   = CreateObject("Search.SearchAdmin.1")
Set objBuildServer   = objSearchAdmin.BuildServer
Set objCatalogs   = objBuildServer.BuildCatalogs
Set objCatalog    = objCatalogs("KMSampleCatalog2")
Set objExtensions = objCatalog.objExtensions("KMSampleCatalog1")

objExtension = objExtensions.Add("TMP")
objExtension.IncludedExtension = False

'Release objects
Set objExtension  = Nothing
Set objExtensions = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing

See Also

Remove


Remove Method

This method removes an extension from the list.

Syntax

IExtensions.Remove(Extension)

Parameters

Extension

The type of filename extension to remove from the list to include or ignore.

Example

The following example removes the TMP extension to the list of filename extensions to include or exclude for the KMSampleCatalog1 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objExtensions

Set objSearchAdmin   = CreateObject("Search.SearchAdmin.1")
Set objBuildServer   = objSearchAdmin.BuildServer
Set objCatalogs   = objBuildServer.BuildCatalogs
Set objCatalog    = objCatalogs("KMSampleCatalog2")
Set objExtensions = objCatalog.objExtensions("KMSampleCatalog1")

objExtensions.Remove("TMP")

'Release objects
Set objExtensions = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing

See Also

Add


Count Property

This read-only property specifies the number of extensions in the list.

Syntax

IExtensions.Count

Example

The following example displays the number of extensions in the list for the KMSampleCatalog1 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objExtensions, ExIncludes

Set objSearchAdmin   = CreateObject("Search.SearchAdmin.1")
Set objBuildServer   = objSearchAdmin.BuildServer
Set objCatalogs   = objBuildServer.BuildCatalogs
Set objCatalog    = objCatalogs("KMSampleCatalog2")
Set objExtensions = objCatalog.objExtensions("KMSampleCatalog1")

If objExtensions.IncludedExtension Then
  ExIncludes = " includes"
Else
  ExIncludes = " excludes"
End If

Wscript.Echo objCatalog.Name & ExIncludes & objExtensions.Count
  & " filename extensions."

'Release objects
Set objExtensions = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing

See Also

Add, Remove


IncludedExtension Property

This property specifies whether the list of extensions are included or are excluded by Search when it builds a catalog.

Syntax

IExtensions.IncludedExtension

Remarks

If True, the list is of filename extensions to include; if False, the list is of filename extensions to exclude.

Example

The following example displays the extensions for all catalogs, and whether they are included or excluded by Search.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog
Dim objExtensions, objExtension, ExInclude

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
    Set objExtensions = objCatalog.objExtensions

    If objExtensions.IncludedExtension Then
        ExIncludes = " includes"
    Else
        ExIncludes = " excludes"
    End If

    Wscript.Echo objCatalog.Name & ExIncludes & " these extensions:"

    For Each objExtension in objExtensions
        Wscript.Echo "  " & objExtension.objExtension
    Next
Next

'Release objects
Set objExtension  = Nothing
Set objExtensions = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing

See Also

Add, Remove


Item Property

This read-only property accesses an extension (IExtension interface).

Syntax

IExtensions[.Item(Extension)]

Parameters

Extension

The extension to access.

Remarks

Since IExtensions is a collection, you need only include Item to access an IExtension object by name (see the following Example).

Example

The following example displays whether the PDF extension is included for all catalog definitions.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog
Dim objExtensions, objExtension, Ext, ExInclude

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
    Set objExtensions = objCatalog.objExtensions
    Set Ext = objExtensions.Item("PDF")

    If IsEmpty(Ext) = False Then
        If Ext.IncludedExtension Then
            Wscript.Echo objCatalog.Name & " includes the PDF extension."
        Else
            Wscript.Echo objCatalog.Name & " excludes the PDF extension."
        End If
    End If

Next

'Release objects
Set Ext        = Nothing
Set objExtension  = Nothing
Set objExtensions = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing

See Also

Count


IGatherLog Interface

This interface is a catalog build server log containing the names of the documents that Search successfully or unsuccessfully crawled, or avoided, while building a catalog.

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog.IGatherLogs

The following table briefly describes this interface's properties.

Property | Description
Created | The date when the log was created.
Name | The name of the log.
Path | The full path to the log.
Size | The size, in bytes, of the log.


Accessing an IGatherLog Object

You access a specific IGatherLog object by calling the IGatherLogs.Item property. Since IGatherLogs is a collection, you can access all IGatherLog objects using a for each loop, as in the following example, where objLog is the name you give to the IGatherLog object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objLogs, objLog

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objLogs     = objCatalog.objLogs

For Each objLog in objLogs
  ...
Next

'Release objects
Set objLog      = Nothing
Set objLogs     = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


Created Property

This read-only property specifies the date when the log was created.

Syntax

IGatherLog.Created

Example

The following example displays the date when the current log was created.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objLogs, objLog

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objBuildServer  = objSearchAdmin.BuildServer
Set objCatalogs  = objBuildServer.BuildCatalogs
Set objCatalog   = objCatalogs("KMSampleCatalog2")
Set objLogs      = objCatalog.objLogs
Set objLog       = objLogs.CurrentLog

Wscript.Echo "The current log, " & objLog.Name & " was created at " _
  & objLog.Created

'Release objects
Set objLog      = Nothing
Set objLogs     = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Name, Path, Size


Name Property

This read-only property specifies the name of the log.

Syntax

IGatherLog.Name

Example

The following example displays the name of the current gatherer log.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objLogs, objLog

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objBuildServer  = objSearchAdmin.BuildServer
Set objCatalogs  = objBuildServer.BuildCatalogs
Set objCatalog   = objCatalogs("KMSampleCatalog2")
Set objLogs      = objCatalog.objLogs
Set objLog       = objLogs.CurrentLog

Wscript.Echo "The current gatherer log is " & objLog.Name

'Release objects
Set objLog      = Nothing
Set objLogs     = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Created, Path, Size


Path Property

This read-only property specifies the path to the log.

Syntax

IGatherLog.Path

Example

The following example displays the path to the current log.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objLogs, objLog

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objBuildServer  = objSearchAdmin.BuildServer
Set objCatalogs  = objBuildServer.BuildCatalogs
Set objCatalog   = objCatalogs("KMSampleCatalog2")
Set objLogs      = objCatalog.objLogs
Set objLog       = objLogs.CurrentLog

Wscript.Echo "The current gatherer log is located at " & objLog.Path

'Release objects
Set objLog      = Nothing
Set objLogs     = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Created, Name, Size


Size Property

This read-only property specifies the size, in bytes, of the log.

Syntax

IGatherLog.Size

Example

The following example displays the size of the current gatherer log.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objLogs, objLog

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objBuildServer  = objSearchAdmin.BuildServer
Set objCatalogs  = objBuildServer.BuildCatalogs
Set objCatalog   = objCatalogs("KMSampleCatalog2")
Set objLogs      = objCatalog.objLogs
Set objLog       = objLogs.CurrentLog

Wscript.Echo "The current gatherer log is " & objLog.Size & " bytes."

'Release objects
Set objLog      = Nothing
Set objLogs     = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Created, Name, Path


IGatherLogs Interface

This interface is a list of catalog build server logs (collection of IGatherLog objects) containing the names of the documents that Search successfully or unsuccessfully crawled, or avoided, while building a catalog.

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog

The following table briefly describes this interface's properties.

Property | Description
Count | The number of logs in the list.
CurrentLog | The log that Search is using to save the document names.
Item | Accesses a log in the list of logs.
MaxLogs | The maximum number of logs that Search retains for this catalog.


Accessing IGatherLogs Objects

You access an IGatherLogs object by calling IBuildCatalog.Logs method, as in the following example, where objLogs is the name you give to the IGatherLogs object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objLogs

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objLogs     = objCatalog.objLogs

...

'Release objects
Set objLogs     = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


Count Property

This read-only property specifies the number of logs in the list.

Syntax

IGatherLogs.Count

Example

The following example displays the number of logs for the KMSampleCatalog2 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objLogs

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objBuildServer  = objSearchAdmin.BuildServer
Set objCatalogs  = objBuildServer.BuildCatalogs
Set objCatalog   = objCatalogs("KMSampleCatalog2")
Set objLogs      = objCatalog.objLogs

Wscript.Echo objCatalog.Name & " has " & objLogs.Count & " gatherer logs."

'Release objects
Set objLogs     = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

IGatherLog interface, Item


CurrentLog Property

This read-only property specifies the log that Search is using to save the document names.

Syntax

IGatherLogs.CurrentLog

Example

The following example displays the name of the current gatherer log for the KMSampleCatalog2 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objLogs, objLog

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objBuildServer  = objSearchAdmin.BuildServer
Set objCatalogs  = objBuildServer.BuildCatalogs
Set objCatalog   = objCatalogs("KMSampleCatalog2")
Set objLogs      = objCatalog.objLogs
Set objLog       = objLogs.CurrentLog

Wscript.Echo objLog & " is the current gatherer log For " objCatalog.Name

'Release objects
Set objLog      = Nothing
Set objLogs     = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


Item Property

This read-only property accesses a log in the list of gather logs.

Syntax

IGatherLogs[.Item(Log)]

Settings

Log

The gatherer log.

Remarks

Since IGatherLogs is a collection, you need only include Item to access an IGatherLogs object by name (see the following Example).

Example

The following example displays the name of all of the gatherer logs for the KMSampleCatalog1 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objLogs, objLog

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objBuildServer  = objSearchAdmin.BuildServer
Set objCatalogs  = objBuildServer.BuildCatalogs
Set objCatalog   = objCatalogs("KMSampleCatalog1")
Set objLogs      = objCatalog.objLogs

Wscript.Echo objCatalog.Name & " has the following gatherer logs:"

For Each objLog in objLogs
  Wscript.Echo "  " & objLog.name
Next

'Release objects
Set objLog      = Nothing
Set objLogs     = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Count, CurrentLog, IGatherLog


MaxLogs Property

This property specifies the maximum number of gather logs that Search retains for this catalog.

Syntax

IGatherLogs.MaxLogs

Example

The following example displays the maximum number of gatherer logs that Search retains for the KMSampleCatalog1 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objLogs

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objBuildServer  = objSearchAdmin.BuildServer
Set objCatalogs  = objBuildServer.BuildCatalogs
Set objCatalog   = objCatalogs("KMSampleCatalog1")
Set objLogs      = objCatalog.objLogs

Wscript.Echo objCatalog.Name & " retains " & objLogs.MaxLogs & " logs."

'Release objects
Set objLogs     = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Count, CurrentLog, Item


IGatherNotify Interface

This interface establishes a notification search.

ProgID:

GatherSvc.GatherNotify

The following table briefly describes this interface's methods.

Method | Description
Init | Specifies a source identifier.
OnDataChange | Informs Search of a document change.


Accessing an IGatherNotify Object

Creating an IGatherNotify Object

You create an IGatherNotify object by calling CreateObject, as in the following example, where objGatherNotify is the name you give to the IGatherNotify object:

Option Explicit
On Error Resume Next

Dim objGatherNotify

Set objGatherNotify = CreateObject("GatherSvc.GatherNotify")
objGatherNotify.Init("NotificationTest")

objGatherNotify.OnDataChange GTHR_CA_ADD, "C:\UpdateList.htm"
objGatherNotify.OnDataChange GTHR_CA_DELETE, "C:\OldList.htm"
objGatherNotify.OnDataChange GTHR_CA_MODIFY, "C:\ChangeList.htm"

'Release objGatherNotify object
Set objGatherNotify = Nothing


Init Method

This method specifies a source identifier.

Syntax

IGatherNotify.Init(Source)

Parameters

Source

The source identifier string.

Remarks

The source identifier must be the same as the IBuildCatalog.NotificationSource property, which specifies the notification source string in the associated catalog definition.

Example

See Accessing an IGatherNotify Object.

See Also

OnDataChange , IBuildCatalog.ProjectType


OnDataChange Method

This method informs Search of a document change.

Syntax

IGatherNotify.OnDataChange Advise, PhyAddress[, LogAddress]

Parameters

Advise

The change in the document.

GTHR_CA_ADD

Add the document to the list of documents to index.

GTHR_CA_DELETE

Delete the document from the list of documents to index.

GTHR_CA_MODIFY

Update the entries for the document.

PhyAddress

The address where the file is located.

LogAddress

The address where the file is displayed to site visitors.

Remarks

You must call the Init method before you can call this method.

Example

See Accessing an IGatherNotify Object.

See Also

Init , IBuildCatalog.NotificationSource , IBuildCatalog.ProjectType


IIndexDs Interface

This interface specifies a Search host to which Search propagates a catalog.

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog.ICatalogSearchServerList

The following table briefly describes this interface's properties.

Property | Description
Name | The name of the Search host where the catalog is propagated.
PropDestination | The full path to the directory where the catalog is propated.


Creating an IIndexDs Object

You create a new IIndexDs object by calling the ICatalogSearchServerList.Add method, as in the following example, where objServer is the name you give to the IIndexDs object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objServers, objServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objServers  = objCatalog.SearchServers

Set objServer = objServers.Add("KnowledgeServer1")

...

'Release objects
Set objServer   = Nothing
Set objServers  = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


Accessing IIndexDs Objects

You can access a specific IIndexDs object by calling the ICatalogSearchServerLIst.Item property. Since ICatalogSearchServerList is a collection, you can access all IIndexDs objects using a for each loop, as in the following example, where objServer is the name you give to the IIndexDs object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objServers, objServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objServers  = objCatalog.SearchServers

Wscript.Echo objCatalog.Name & " is propagated to:"

For Each objServer in objServers
  Wscript.Echo objServer.Name & " in directory " & objServer.PropDestination
Next

'Release objects
Set objServer   = Nothing
Set objServers  = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


Name Property

This read-only property specifies the name of the Search host where the catalog is propagated.

Syntax

IIndexDs.Name

Example

See Accessing an IIndexDs Object.

See Also

PropDestination


PropDestination Property

This property specifies the full path to the directory where the catalog is propated.

Syntax

IIndexDs.PropDestination

Example

See Accessing an IIndexDs Object.

See Also

Name


IMapping Interface

This interface specifies from where a file is searched (the crawler access location) to where a file is displayed to site visitors (the display location).

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog.IMappings

The following table briefly describes this interface's properties.

Property | Description
From | The crawler access location in the file system where the file is located.
To | The display location where the file is displayed to site visitors.


Creating an IMapping Object

You create an IMapping object by calling the IMappings.Add method, as in the following example, where objMapping is the name you give to the IMapping object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objMappings, objMapping

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objMappings = objCatalog.objMappings

Set objMapping = objMappings.Add "C:\InetPub\wwwroot",
  "http://www.microsoft.com"

'Release objects
Set objMapping  = Nothing
Set objMappings = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


Accessing IMapping Objects

You access an IMapping object by calling the IMappings.Item property. Since IMappings is a collection, you can access all IMapping objects using a for each loop, as in the following example, where objMapping is the name you give to the IMapping object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objMappings, objMapping

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  Set objMappings = objCatalog.objMappings
  Wscript.Echo "objCatalog " & objCatalog.Name & " maps the following:"

  For Each objMapping in objMappings
    Wscript.Echo "  " & objMapping.From & " to " & objMapping.To
  Next
Next

'Release objects
Set objMapping  = Nothing
Set objMappings = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


From Property

This read-only property specifies the crawler access location in the file system where the file is located.

Syntax

IMapping.From

Example

See Accessing IMapping Objects.

See Also

To


To Property

This read-only property specifies the display location where the file is displayed to site visitors.

Syntax

IMapping.To

Example

See Accessing IMapping Objects.

See Also

From


IMappings Interface

This interface is a list of mappings (collection of IMapping objects) that specify from where a file is searched (the crawler access location) to where a file is displayed to site visitors (the display location).

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog

A typical mapping is to search a file as a fully qualified path name and display a file as a URL. The following table briefly describes this interface's methods and properties.

Method | Description
Add | Adds a mapping to the list.
Remove | Removes a mapping from the list.
Property | Description
Count | The number of mappings.
Item | Accesses a mapping.


Accessing an IMappings Object

You access an IMappings object by calling the IBuildCatalog.Mappings property, as in the following example, where objMappings is the name you give to the IMappings object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objMappings

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objMappings = objCatalog.objMappings

...

'Release objects
Set objMappings = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


Add Method

This method adds a mapping to the list of mappings.

Syntax

IMappings.Add(From, To)

Parameters

From

The crawler access location in the file system where the file is located.

To

The display location where the file is displayed to site visitors.

Remarks

Example

The following example add the mapping of C:\InetPub\wwwroot to http://www.microsoft.com.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objMappings, objMapping

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objMappings = objCatalog.objMappings

Set objMapping = objMappings.Add "C:\InetPub\wwwroot",
  "http://www.microsoft.com"

'Release objects
Set objMapping  = Nothing
Set objMappings = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Remove


Remove Method

This method removes a mapping from the list of mappings.

Syntax

IMappings.Remove(From)

Parameters

From

The location in the file system where the file is located.

Example

The following example removes the mapping of C:\InetPub\wwwroot from KMSampleCatalog2.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objMappings

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objMappings = objCatalog.objMappings

objMappings.Remove("C:\InetPub\wwwroot")

'Release objects
Set objMappings = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Add


Count Property

This read-only property specifies the number of mappings in the list.

Syntax

IMappings.Count

Example

The following example displays the number of mappings.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objMappings

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objMappings = objCatalog.objMappings

Wscript.Echo "There are " & objMappings.Count & " mappings."

'Release objects
Set objMappings = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Item


Item Property

This read-only property accesses a mapping in the list of mappings.

Syntax

IMappings[.Item(From)]

Settings

From

The crawler access location in the file system where the file is located.

Remarks

Since IMappings is a collection, you need only include Item to access an IMapping object by name (see the following Example).

Example

The following example displays the mappings for the KMSampleCatalog1 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objMappings, objMapping

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objMappings = objCatalog.objMappings

Wscript.Echo "objCatalog " & objCatalog.Name & " maps the following:"

For Each objMapping in objMappings
  Wscript.Echo objMapping.From & " to " & objMapping.To
Next

'Release objects
Set objMapping  = Nothing
Set objMappings = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Count


IProtocol Interface

This interface contains the properties of a protocol that Search uses when crawling.

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog.IProtocols

The following table briefly describes this interface's properties.

Property | Description
Included | Whether Search crawls this protocol building a catalog.
ProgIdHandler | ProgID for the component that handles this protocol.
UrlName | Protocol name.


Accessing an IProtocol Object

You can access a specific IProtocol object by calling the IProtocols.Item method. Since IProtocols is a collection, you can access all IProtocol objects using a for each loop, as in the following example, where objProtocol is the name you give to the IProtocol object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objProtocols, objProtocol

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  Set objProtocols  = objCatalog.objProtocols

  For Each objProtocol in objProtocols
    If objProtocol.Included Then
      Wscript.Echo UrlName & " using ProgID: " & ProgIdHandler
    End If
  Next
Next

'Release objects
Set objProtocol   = Nothing
Set objProtocols  = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing


Included Property

This property specifies whether Search crawls this protocol building a catalog.

Syntax

IProtocol.Included

Remarks

If True, the Search crawls files of this protocol; if False, the Search does not crawl files of this protocol.

Example

See Accessing an IProtocol Object.

See Also

UrlName


ProgIdHandler Property

This read-only property specifies the ProgID for the component that handles this protocol.

Syntax

IProtocol.ProgIdHandler

Example

See Accessing an IProtocol Object.

See Also

UrlName


UrlName Property

This read-only property specifies the name of the protocol.

Syntax

IProtocol.UrlName

Remarks

This property can be Exch, File, or Http.

Example

See Accessing an IProtocol Object.

See Also

Included, ProgIdHandler


IProtocols Interface

This interface is a list of the protocols (collection of IProtocol objects) that Search uses when crawling.

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog

The following table briefly describes this interface's properties.

Property | Description
Count | The number of protocols in the list.
Item | Accesses a protocol.


Accessing an IProtocols Object

You access an IProtocols object by calling the IBuildCatalog.Protocols property, as in the following example, where objProtocols is the name you give to the IProtocols object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objProtocols, objProtocol

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  Set objProtocols = objCatalog.objProtocols
  Wscript.Echo objCatalog.Name & " searches the following protocols:"

  For Each objProtocol in objProtocols
     If objProtocol.Included Then Wscript.Echo objProtocol.Urlname
  Next

Next

'Release objects
Set objProtocols = Nothing
Set objCatalogs  = Nothing
Set objBuildServer  = Nothing
Set objSearchAdmin  = Nothing


Count Property

This read-only property specifies the number of protocols in the list.

Syntax

IProtocols.Count

Example

See Accessing an IProtocols Object.

See Also

Item


Item Property

This read-only property accesses a protocol (IProtocol interface).

Syntax

IProtocols[.Item(IProtocol)]

Settings

IProtocol

The protocol to access, either Exch, File, or Http.

Remarks

Since IProtocols is a collection, you need only include Item to access an IProtocol object by name.

Example

See Accessing an IProtocols Object.

See Also

Count


ISearchAdmin Interface

This interface provides properties to access the other Search interfaces on a specific host.

ProgID:

Search.SearchAdmin.1

interfaceThe following table briefly describes this object's properties.

Property | Description
BuildServer | The IBuildServer interface of the host.
HostName | The name of the host being administered.
SearchServer | The ISearchServer interface of the host.


Accessing an ISearchAdmin Object

Creating an ISearchAdmin Object

You create an ISearchAdmin object by calling CreateObject, as in the following example, where objSearchAdmin is the name you give to the new ISearchAdmin object:

Option Explicit
On Error Resume Next

Dim SearchAdmin

Set SearchAdmin = CreateObject("Search.SearchAdmin.1")

...
'Release ISearchAdmin object
Set SearchAdmin = Nothing


BuildServer Property

This read-only property provides access to the IBuildServer interface of the host.

Syntax

ISearchAdmin.BuildServer

Example

The following example retrieves the IBuildServer object for the current host.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer

...

'Release objects
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

IBuildServer, SearchServer


HostName Property

The HostName property specifies the host being administered.

Syntax

ISearchAdmin.HostName

Example

The following example displays the administrator email address configured on the catalog build server of the Search host SearchHost1.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, Host

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
objSearchAdmin.HostName = "SearchHost1"
Wscript.Echo objSearchAdmin.BuildServer.EmailAddress
...

Set objSearchAdmin = Nothing

See Also

BuildServer, SearchServer


SearchServer Property

This read-only property provides access to the ISearchServer object of the host.

Syntax

ISearchAdmin.SearchServer

Example

The following example retrieves the ISearchServer object for the current host.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer

...

'Release objects
Set objSearchServer = Nothing
Set objSearchAdmin  = Nothing

See Also

BuildServer, ISearchServer


ISearchCatalog Interface

This interface manages a search catalog (a catalog that Search searches).

Hierarchy

ISearchAdmin.ISearchServer.ISearchCatalogs

The following table briefly describes this interface's methods and properties.

Method | Description
Disable | Disable searching on the catalog.
Enable | Enable searching on the catalog.
Update | Update the search catalog.
Property | Description
BuildServerName | The name of the catalog build server (IBuildServer interface).
MaxResultRows | The maximium result rows for queries.
Name | The name of the catalog.
Properties | The catalog properties (ICatalogProperties interface).
QueryTimeout | The duration, in milliseconds, to wait for a query to finish.
SearchServer | The name of the search server (ISearchServer interface).
Status | The status of the catalog.


Creating an ISearchCatalog Object

You create an ISearchCatalog object by calling the ISearchCatalogs.Add method, as in the following example, where KMSampleCatalog1 is the name of the catalog:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer, objCatalogs, objCatalog

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer
Set objCatalogs  = objSearchServer.SearchCatalogs
Set objCatalog   = objCatalogs.Add("KMSampleCatalog1")

...

'Release objects
Set objCatalog   = Nothing
Set objCatalogs  = Nothing
Set objSearchServer = Nothing
Set objSearchAdmin  = Nothing


Accessing ISearchCatalog Objects

You access a specific ISearchCatalog object by calling the ISearchCatalogs.Item property. Since ISearchCatalogs is a collection, you can access all ISearchCatalog objects using a for each loop, as in the following example, where objCatalog is the name you give to the ISearchCatalog object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer, objCatalogs, objCatalog

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer
Set objCatalogs  = objSearchServer.SearchCatalogs

For Each objCatalog in objCatalogs
  ...
Next

'Release objects
Set objCatalog   = Nothing
Set objCatalogs  = Nothing
Set objSearchServer = Nothing
Set objSearchAdmin  = Nothing


Disable Method

The Disable method disables searching on the catalog.

Syntax

ISearchCatalog.Disable

Remarks

If True, Search will not access the catalog when searching; if False, Search can access the catalog when searching.

Example

The following example disables searching on the catalog KMSampleCatalog1.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer, objCatalogs, objCatalog

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer
Set objCatalogs  = objSearchServer.SearchCatalogs
Set objCatalog   = objCatalogs("KMSampleCatalog1")

objCatalog.Disable

'Release objects
Set objCatalog   = Nothing
Set objCatalogs  = Nothing
Set objSearchServer = Nothing
Set objSearchAdmin  = Nothing

See Also

Enable, Update


Enable Method

This method enables searching on the catalog.

Syntax

ISearchCatalog.Enable

Example

The following example enables searching on the KMSampleCatalog1 catalog.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer, objCatalogs, objCatalog

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer
Set objCatalogs  = objSearchServer.SearchCatalogs
Set objCatalog   = objCatalogs("KMSampleCatalog1")

objCatalog.Enable

'Release objects
Set objCatalog   = Nothing
Set objCatalogs  = Nothing
Set objSearchServer = Nothing
Set objSearchAdmin  = Nothing

See Also

Disable, Update


Update Method

This method updates the catalog files.

Syntax

ISearchCatalog.Update

Example

The following example updates catalog files based on the KMSampleCatalog1 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer, objCatalogs, objCatalog

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer
Set objCatalogs  = objSearchServer.SearchCatalogs
Set objCatalog   = objCatalogs("KMSampleCatalog1")

objCatalog.Update

'Release objects
Set objCatalog   = Nothing
Set objCatalogs  = Nothing
Set objSearchServer = Nothing
Set objSearchAdmin  = Nothing

See Also

Disable, Enable


BuildServerName Property

This read-only property specifies the name of the catalog build server (IBuildServer interface).

Syntax

ISearchCatalog.BuildServerName

Example

The following example displays the name of the catalog build server.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer, objCatalogs, objCatalog

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer
Set objCatalogs  = objSearchServer.SearchCatalogs
Set objCatalog   = objCatalogs("KMSampleCatalog1")

Wscript.Echo "The build server is " & objCatalog.BuildServerName

'Release objects
Set objCatalog   = Nothing
Set objCatalogs  = Nothing
Set objSearchServer = Nothing
Set objSearchAdmin  = Nothing

See Also

ISearchServer


MaxResultRows Property

This property specifies the maximium result rows for queries.

Syntax

ISearchCatalog.MaxResultRows

Remarks

MaxResultRows is the maximum number of rows to access during a query.

Example

The following example displays the maximum number of rows that are accessed during a query.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer, objCatalogs, objCatalog

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer
Set objCatalogs  = objSearchServer.SearchCatalogs
Set objCatalog   = objCatalogs("KMSampleCatalog1")

Wscript.Echo "Searching a maximum of " & MaxResultRows & " rows."

'Release objects
Set objCatalog   = Nothing
Set objCatalogs  = Nothing
Set objSearchServer = Nothing
Set objSearchAdmin  = Nothing

See Also

QueryTimeout


Name Property

This read-only property specifies the name of the catalog.

Syntax

ISearchCatalog.Name

Example

The following example displays the name of the catalogs.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer, objCatalogs, objCatalog

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer
Set objCatalogs  = objSearchServer.SearchCatalogs

For Each objCatalog in objCatalogs
  Wscript.echo "objCatalog: " & objCatalog.Name
Next

'Release objects
Set objCatalogs  = Nothing
Set objSearchServer = Nothing
Set objSearchAdmin  = Nothing

See Also

Status


Properties Property

This read-only property specifes the catalog build properties (ICatalogProperties interface).

Syntax

ISearchCatalog.Properties

Remarks

See ICatalogProperties for a description of the catalog build properties.

Example

The following example displays the properties for all catalogs.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer, objCatalogs, objCatalog, Property

Err.Clear

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer
Set objCatalogs  = objSearchServer.SearchCatalogs

For Each objCatalog in objCatalogs
  Wscript.echo "objCatalog " & objCatalog.Name & " properties:"
  Set Property = objCatalog.Properties
  Wscript.echo "  Build date:             " & Property.BuildDate
  Wscript.echo "  # docs:                 " & Property.NumberOfDocuments
  Wscript.echo "  Size of index:          " & Property.IndexSize
    & " (MBytes)"
  Wscript.echo "  Size of property store: "
    & Property.PropertyStoreSize & " (MBytes)"
  Wscript.echo "  # unique keys:          " & Property.UniqueKeyCount
  Wscript.echo "  Crawl number:           " & Property.PropSeqNum
     Wscript.Echo ""
Next

'Release objects
Set objCatalog    = Nothing
Set objSearchServer  = Nothing
Set objSearchAdmin   = Nothing

See Also

Name


QueryTimeout Property

The QueryTimeout property specifies the duration, in milliseconds, to wait for a query to finish.

Syntax

ISearchCatalog.QueryTimeout

Remarks

The default value is 10000 milliseconds (10 seconds).

Example

The following example sets the timeout duration to 20 seconds for the KMSampleCatalog1 catalog.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer, objCatalogs, objCatalog

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer
Set objCatalogs  = objSearchServer.SearchCatalogs
Set objCatalog   = objCatalogs("KMSampleCatalog1")

objCatalog.QueryTimeout = 20000

'Release objects
Set objCatalog   = Nothing
Set objCatalogs  = Nothing
Set objSearchServer = Nothing
Set objSearchAdmin  = Nothing

See Also

Status


SearchServer Property

This read-only property specifies the name of the search server (ISearchServer interface).

Syntax

ISearchCatalog.SearchServer

Example

The following example displays the name of the search server for the KMSampleCatalog1 catalog.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer, objCatalogs, objCatalog

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer
Set objCatalogs  = objSearchServer.SearchCatalogs
Set objCatalog   = objCatalogs("KMSampleCatalog1")

Wscript.echo "The search server is " & objCatalog.SearchServer

'Release objects
Set objCatalog   = Nothing
Set objCatalogs  = Nothing
Set objSearchServer = Nothing
Set objSearchAdmin  = Nothing

See Also

BuildServerName


Status Property

This read-only property specifies the status of the catalog.

Syntax

ISearchCatalog.Status

Example

The following example displays the status of the KMSampleCatalog1 catalog.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer, objCatalogs, objCatalog

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer
Set objCatalogs  = objSearchServer.SearchCatalogs
Set objCatalog   = objCatalogs("KMSampleCatalog1")

Wscript.echo "The status of catalog " & objCatalog.Name & " is "
  & objCatalog.Status

'Release objects
Set objCatalog   = Nothing
Set objCatalogs  = Nothing
Set objSearchServer = Nothing
Set objSearchAdmin  = Nothing

See Also

QueryTimeout


ISearchCatalogs Interface

This interface is a list of search catalogs (collection of ISearchCatalog objects) that Search searches.

Hierarchy

ISearchAdmin.ISearchServer

The following table briefly describes this interface's methods and properties.

Method | Description
Add | Adds a catalog.
Remove | Removes a catalog.
Property | Description
Count | The number of catalogs.
Item | Accesses a catalog.


Accessing an ISearchCatalogs Object

You access an ISearchCatalogs object by calling the ISearchServer.SearchCatalogs property, as in the following example, where objCatalogs is the name you give to the ISearchCatalogs object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer, objCatalogs

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer
Set objCatalogs  = objSearchServer.SearchCatalogs

...

'Release objects
Set objCatalogs  = Nothing
Set objSearchServer = Nothing
Set objSearchAdmin  = Nothing


Add Method

This method adds a catalog (ISearchCatalog object).

Syntax

ISearchCatalogs.Add(Catalog)

Parameters

Catalog

The catalog to add.

Example

The following example adds the catalog KMSampleCatalog3.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer, objCatalogs, objCatalog

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer
Set objCatalogs  = objSearchServer.SearchCatalogs

Set objCatalog = objCatalogs.Add("KMSampleCatalog3")

...

'Release objects
Set objCatalog   = Nothing
Set objCatalogs  = Nothing
Set objSearchServer = Nothing
Set objSearchAdmin  = Nothing

See Also

Item


Remove Method

This method removes a catalog (ISearchCatalog object).

Syntax

ISearchCatalogs.Remove(Catalog)

Parameters

Catalog

The catalog to remove.

Example

The following example removes the catalog KMSampleCatalog2.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer, objCatalogs

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer
Set objCatalogs  = objSearchServer.SearchCatalogs

objCatalogs.Remove("KMSampleCatalog1")

'Release objects
Set objCatalogs  = Nothing
Set objSearchServer = Nothing
Set objSearchAdmin  = Nothing

See Also

Add


Count Property

This read-only property specifies the number of catalogs (ISearchCatalog objects).

Syntax

ISearchCatalogs.Count

Example

The following example displays the number of catalogs.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer, objCatalogs

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer
Set objCatalogs  = objSearchServer.SearchCatalogs

Wscript.Echo "There are " & objCatalogs.Count & " catalogs."

'Release objects
Set objCatalogs  = Nothing
Set objSearchServer = Nothing
Set objSearchAdmin  = Nothing

See Also

Item


Item Property

This read-only property accesses a catalog (ISearchCatalog object).

Syntax

ISearchCatalogs[.Item(Catalog)]

Settings

Catalog

The catalog to access.

Remarks

Since ISearchCatalogs is a collection, you need only include Item to access an ISearchCatalog object by name (see the following Example).

Example

The following example accesses the catalog KMSampleCatalog1, and then displays its name, which is KMSampleCatalog1.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer, objCatalogs, objCatalog

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer
Set objCatalogs  = objSearchServer.SearchCatalogs
Set objCatalog   = objCatalogs("KMSampleCatalog1")

Wscript.Echo "Accessed catalog " & objCatalog.Name

'Release objects
Set objCatalog   = Nothing
Set objCatalogs  = Nothing
Set objSearchServer = Nothing
Set objSearchAdmin  = Nothing

See Also

Remove


ISearchSchema Interface

This interface defines the document properties that Search indexes or retrieves when building a catalog.

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog

The following table briefly describes this interface's method and properties.

Method | Description
Save | Saves any changes to the Search schema.
Property | Description
Columns | A collection of columns (IColumns interface) of information about the file.
Stoplists | A collection of files (IStoplists interface) containing words that Search ignores while building a catalog.


Accessing an ISearchSchema Object

You access an ISearchSchema object by calling the IBuildCatalog.Schema property, as in the following example, where objSchema is the name you give to the ISearchSchema object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSchema

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  Set objSchema  = objCatalog.objSchema
  ...
Next

'Release objects
Set objSchema    = Nothing
Set objCatalog   = Nothing
Set objCatalogs  = Nothing
Set objBuildServer  = Nothing
Set objSearchAdmin  = Nothing


Save Method

This method saves any changes to the Search schema.

Syntax

ISearchSchema.Save

Remarks

You must call this method to save any changes you've made to the Search schema. Otherwise, the changes disappear once your program exits.

Save validates some of the changes made to the IColumns and IStoplists interfaces, and can return an error based on an invalid or duplicate value in either interface.

You should check the Err.Number property after each interface method and the Save method to ensure that your changes were successful.

You should only call the Save method once—make all of your changes to the Search schema and then call Save. However, if you must call the Save method more than once, release and reload the schema by calling the BuildCatalog.Schema (see Accessing an ISearchSchema Object).

Example

The following example adds the VBScript document property to the indexed Search schema for the KMSampleCatalog2 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSchema, objColumns, objColumn

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objSchema   = objCatalog.objSchema
Set objColumns  = objSchema.objColumns
Set objColumn   = objColumns("VBScript")

objColumn.Index = True
objSchema.Save

'Release objects
Set objColumn   = Nothing
Set objColumns  = Nothgin
Set objSchema   = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

IColumns, IStoplists


Columns Property

This read-only property specifies a collection of columns (IColumns interface) of information about the file.

Syntax

ISearchSchema.Columns

Remarks

See the Columns and Column interface methods for information on how to add and modify column definitions.

Example

The following example displays the names of the columns (document properties that are indexed or retrieved) for the KMSampleCatalog1 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSchema, objColumns, objColumn

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objBuildServer  = objSearchAdmin.BuildServer
Set objCatalogs  = objBuildServer.BuildCatalogs
Set objCatalog   = objCatalogs("KMSampleCatalog1")
Set objSchema    = objCatalog.objSchema
Set objColumns   = objSchema.objColumns

For Each objColumn in objColumns
  Wscript.Echo "Document property " & objColumn.Name & " is: "
  If objColumn.Index Then
     Wscript.Echo "  indexed."
   Else
     Wscript.Echo "  not indexed."
   End If

   If objColumn.Retrieve Then
     Wscript.Echo "  retrieved."
   Else
     Wscript.Echo "  not retrieved."
   End If
   Wscript.Echo ""
Next

'Release objects
Set objColumn    = Nothing
Set objColumns   = Nothing
Set objSchema    = Nothing
Set objCatalog   = Nothing
Set objCatalogs  = Nothing
Set objBuildServer  = Nothing
Set objSearchAdmin  = Nothing

See Also

IColumns, Stoplists


Stoplists Property

This read-only property specifies a collection of files (IStoplists interfaces) containing words that Search ignores while building a catalog.

Syntax

ISearchSchema.Stoplists

Remarks

If multiple stoplist files are created for different sublanguages of a particular primary language, it is advised that all the files for that primary language be identical, or queries may fail when the query sublanguage does not match the inferred document sublanguage.

Example

The following example displays the stop lists available for all catalogs.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSchema, Stoplists, Stoplist

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  Wscript.Echo "Stop lists available For " & objCatalog.Name & " catalog"
  Set objSchema    = objCatalog.objSchema
  Set Stoplists = objSchema.Stoplists
  Wscript.Echo ""

  For Each Stoplist in Stoplists
    Wscript.Echo "  " & Stoplist.Name
   Next
  Wscript.Echo ""
Next

'Release objects
Set Stoplist  = Nothing
Set Stoplists = Nothing
Set objSchema    = Nothing
Set objCatalog   = Nothing
Set objCatalogs  = Nothing
Set objBuildServer  = Nothing
Set objSearchAdmin  = Nothing

See Also

Columns, IStoplists


ISearchServer Interface

This interface manages search catalogs (through the ISearchCatalogs interface) and catalog search server properties.

Hierarchy

ISearchAdmin

The following table briefly describes this interface's properties.

Property | Description
CatalogsLocation | The location of the Search catalogs.
DefaultCatalog | The default Search catalog.
PerformanceLevel | The amount of host resources used for searching.
SearchAdmin | The parent ISearchAdmin interface.
SearchCatalogs | The ISearchCatalogs interface on the host.


Accessing an ISearchServer Object

You access an ISearchServer object by calling the SearchAdmin.SearchServer property, as in the following example, where objSearchServer is the name you give to the new ISearchServer object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer

...

'Release objects
Set objSearchServer = Nothing
Set objSearchAdmin  = Nothing


CatalogsLocation Property

This property specifies the location of the Search catalogs.

Syntax

ISearchServer.CatalogsLocation

Remarks

The location is the full path to the Search catalogs. If the location does not exist when you set this property, Search creates it.

Example

The following example sets the catalog location to C:\Search\Catalogs.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer

objSearchServer.CatalogsLocation = "C:\Search\objCatalogs"

'Release objects
Set objSearchServer = Nothing
Set objSearchAdmin  = Nothing

See Also

DefaultCatalog, SearchCatalogs


DefaultCatalog Property

This property specifies the default Search catalog.

Syntax

ISearchServer.DefaultCatalog

Example

The following example prompts the user whether they want to change the default catalog to one of the displayed catalog names.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer, objCatalogs, objCatalog
Dim Prompt, Buttons, Title, Response

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer
Set objCatalogs  = objSearchServer.SearchCatalogs

For Each objCatalog in objCatalogs
  Prompt = "Would you like to make " & Chr(13) & objCatalog.Name
    & Chr(13) & "the default catalog?"
  Buttons = vbYesNo + vbDefaultButton2 + vbExclamation + vbSystemModal
  Title = "MsgBox Test"
  Response = MsgBox(Prompt, Buttons, Title)

  If Response = vbYes Then
     objSearchServer.DefaultCatalog = objCatalog.Name
  End If
Next

'Release objects
Set objCatalogs   = Nothing
Set objSearchServer  = Nothing
Set objSearchAdmin   = Nothing

See Also

CatalogsLocation, SearchCatalogs


PerformanceLevel Property

This property specifies the amount of host resources used for searching.

Syntax

ISearchServer.PerformanceLevel

Remarks

PerformanceLevel has a range of from 1, which runs Search in the background, to 5, which dedicates all of the host machine's resources to Search.

Example

The following example displays the level of system resources dedicated to searching a catalog.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer, PerfLevel

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer

PerfLevel = objSearchServer.PerformanceLevel

Select Case PerfLevel
  Case 1
    Wscript.Echo "Search runs in the background"
  Case 2
    Wscript.Echo "Search runs at a low priority"
  Case 3
    Wscript.Echo "Search runs at a medium priority"
  Case 4
    Wscript.Echo "Search runs at a high priority"
  Case 5
    Wscript.Echo "Host resources are dedicated to Search"
End Select

'Release objects
Set objSearchServer = Nothing
Set objSearchAdmin  = Nothing

See Also

SearchCatalogs


SearchAdmin Property

This read-only property specifies the parent ISearchAdmin interface.

Syntax

ISearchServer.SearchAdmin

Remarks

This property is a convenient way to get to the parent interface of the current ISearchServer interface.

Example

The following example displays the host name of the associated SearchAdmin object.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer, SearchObjParent

Set objSearchAdmin        = CreateObject("Search.SearchAdmin.1")
Set objSearchServer       = objSearchAdmin.SearchServer
Set SearchObjParent = objBuildServer.SearchAdmin

Wscript.Echo "The current host is " & SearchObjParent.HostName

'Release objects
Set SearchObjParent = Nothing
Set objSearchServer       = Nothing
Set objSearchAdmin        = Nothing

See Also

SearchCatalogs


SearchCatalogs Property

This read-only property specifies the ISearchCatalogs interface on the host.

Syntax

ISearchServer.SearchCatalogs

Example

The following example displays the names of the catalogs.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objSearchServer, objCatalogs, objCatalog

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objSearchServer = objSearchAdmin.SearchServer
Set objCatalogs  = objSearchServer.SearchCatalogs

For Each objCatalog in objCatalogs
  Wscript.Echo "objCatalog: " & objCatalog.Name
Next

'Release objects
Set objCatalog   = Nothing
Set objCatalogs  = Nothing
Set objSearchServer = Nothing
Set objSearchAdmin  = Nothing

See Also

DefaultCatalog


IServer Interface

This interface specifies how frequently Search is allowed to access a site.

Hierarchy

ISearchAdmin.IBuildServer.IServers

The following table briefly describes this interface's properties.

Property | Description
HitInterval | The maximum frequency that Search accesses a site.
Name | The name of the site.


Creating an IServer Object

You create an IServer object by calling the IServers.Add method, as in the following example, where objServer is the name you give to the IServer object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objServers, objServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objServers  = objCatalog.Sites

Set objServer   = objServers.Add("Microsoft.com")

...

'Release objects
Set objServer   = Nothing
Set objServers  = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


Accessing IServer Objects

You access an IServer object by calling the IServers.Item property. Since IServers is a collection, you can access all IServer objects using a for each loop, as in the following example, where objServer is the name you give to the IServer object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objServers, objServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objServers  = objCatalog.Sites

For Each objServer in objServers
  ...
Next

'Release objects
Set objServer   = Nothing
Set objServers  = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


HitInterval Property

This property specifies the maximum frequency that Search is allowed to access a site.

Syntax

IServer.HitInterval

Example

The following example displays how often Search accesses the site Microsoft.com.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objServers, objServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objServers  = objCatalog.Sites

For Each objServer in objServers
  If objServer.Name = "Microsoft.com" Then
    Wscript.Echo "Search accesses " & objServer.Name & " every "
      & objServer.HitInterval & " seconds."
  End If
Next

'Release objects
Set objServer   = Nothing
Set objServers  = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Name


Name Property

This read-only property contains the name of a site.

Syntax

IServer.Name

Example

The following example displays how often Search is allowed to access the site Microsoft.com.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objServers, objServer

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objServers  = objCatalog.Sites

For Each objServer in objServers
  If objServer.Name = "Microsoft.com" Then
    Wscript.Echo "Search accesses " & objServer.Name & " every "
      & objServer.HitInterval & " seconds."
  End If
Next

'Release objects
Set objServer   = Nothing
Set objServers  = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

HitInterval


IServers Interface

This interface is a list of access frequencies (collection of IServer objects) that specify how frequently Search accesses a site.

Hierarchy

ISearchAdmin.IBuildServer

The following table briefly describes this interface's methods and properties.

Method | Description
Add | Adds an item to the list of how frequently Search accesses a site.
ChangeOrder | Moves a site up or down in the collection.
Remove | Removes a site from the collection.
Property | Description
Count | The number of sites in the list of sites.
Item | Accesses a site in the list of sites.


Accessing an IServers Object

You access an IServers object by calling the IBuildServer.Sites property, as in the following example, where objServers is the name you give to the IServers object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objServers

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objServers  = objBuildServer.Sites

...

'Release objects
Set objServers  = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


Add Method

This method adds an item to the list of how frequently Search accesses a site.

Syntax

IServers.Add(Site)

Parameters

Site

The site that is added to the list of how frequently Search accesses a site.

Example

The following example adds the Microsoft.com site to the list of sites.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objServers, objServer

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objBuildServer  = objSearchAdmin.BuildServer
Set objServers   = objBuildServer.Sites

Set objServer = objServers.Add("Microsoft.com")

...

'Release objects
Set objServer   = Nothing
Set objServers  = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

ChangeOrder, IServer, Remove


ChangeOrder Method

This method moves a site up or down in the list of sites.

Syntax

IServers.ChangeOrder(MoveUp)

Parameters

MoveUp

If True, moves the site up in the list of sites; if False, moves the site down in the list of sites.

Example

The following example moves the site Microsoft.com down in the list of sites.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objServers

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objBuildServer  = objSearchAdmin.BuildServer
Set objServers   = objBuildServer.Sites

objServers.ChangeOrder "Microsoft.com", False

'Release objects
Set objServers  = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Add, IServer, Remove


Remove Method

This method removes a site from the list of sites.

Syntax

IServers.Remove(Site)

Parameters

Site

The site to remove.

Example

The following example removes Microsoft.com from the list of sites.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objServers

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objBuildServer  = objSearchAdmin.BuildServer
Set objServers   = objBuildServer.Sites

objServers.Remove("Microsoft.com")

'Release objects
Set objServers  = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Add, Count


Count Property

This read-only property specifies the number of sites in the list of sites.

Syntax

IServers.Count

Example

The following example displays the number of sites in the list.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objServers

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objBuildServer  = objSearchAdmin.BuildServer
Set objServers   = objBuildServer.Sites

Wscript.Echo "There are " & objServers.Count & " sites in the list."

'Release objects
Set objServers  = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Add, Item, Remove


Item Property

This read-only property accesses a site in the list of sites.

Syntax

IServers[.Item(Site)]

Settings

Site

The site to access.

Remarks

Since IServers is a collection, you need only include Item to access an IServers object by name (see the following Example).

Example

The following example displays the names of the sites in the list.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objServers, objServer

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objBuildServer  = objSearchAdmin.BuildServer
Set objServers   = objBuildServer.Sites

Wscript.Echo "The sites with hit frequency rules are:"

For Each objServer in objServers
  Wscript.Echo "  " & objServer.Name
Next

'Release objects
Set objServer   = Nothing
Set objServers  = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Add, Count, IServer, Remove


ISitePath Interface

This interface is a path that Search crawls or avoids on a site.

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog.ISiteRestrictions.ISiteRestriction.ISitePaths

The following table briefly describes this interface's properties.

Property | Description
Included | Whether the path is crawled.
IncludeSubdirs | Whether the path's subdirectories are crawled.
Path | The path that Search crawls or avoids.


Creating an ISitePath Object

You create an ISitePath object by calling the ISitePaths.Add method, as in the following example, where objPath is the name you give to the ISitePath object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite, objPaths

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objSites    = objCatalog.objSites
Set objSite     = objSites.Item("Microsoft.com")
Set objPaths    = objSite.objPaths

Set Path = objPaths.Add "C:\Tmp", False

...

'Release objects
Set Path     = Nothing
Set objPaths    = Nothing
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


Accessing ISitePath Objects

You can access a specific ISitePath object by calling the ISitePaths.Item property. Since ISitePaths is a collection, you can access all ISitePath objects using a for each loop, as in the following example, where objPath is the name you give to the ISitePath object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite, objPaths, objPath

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objSites    = objCatalog.objSites
Set objSite     = objSites.Item("Microsoft.com")
Set objPaths    = objSite.objPaths

For Each objPath in objPaths
  ...
Next

'Release objects
Set objPath    = Nothing
Set objPaths    = Nothing
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


Included Property

This property specifies whether the path is crawled.

Syntax

ISitePath.Included

Remarks

If True, Search crawls the path; if False, Search avoids the path.

Search can avoid a path but crawl its subdirectories.

Example

The following example displays whether Search crawls or avoids all of the paths for the site Microsoft.com.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite, objPaths, objPath

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objSites    = objCatalog.objSites
Set objSite     = objSites.Item("Microsoft.com")
Set objPaths    = objSite.objPaths

Wscript.Echo "The restricted site " & objSite.Name & " has these paths:"

For Each objPath in objPaths
  If objPath.Included Then
    Wscript.Echo "  " & objPath.objPath & " is crawled."
  Else
    Wscript.Echo "  " & objPath.objPath & " is ignored."
  End If
Next

'Release objects
Set objPath     = Nothing
Set objPaths    = Nothing
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

IncludeSubdirs


IncludeSubdirs Property

This property specifies whether the path's subdirectories are crawled.

Syntax

ISitePath.IncludeSubdirs

Remarks

If True, Search crawls the path's subdirectories; if False, Search avoids the path's subdirectories.

Search can ignore a path but crawl its subdirectories.

Example

The following example displays whether Search crawls or avoids all of the paths and subdirectories for the site Microsoft.com.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite, objPaths, objPath

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objSites    = objCatalog.objSites
Set objSite     = objSites.Item("Microsoft.com")
Set objPaths    = objSite.objPaths

Wscript.Echo "The restricted site " & objSite.Name & " has these paths:"

For Each objPath in objPaths
  If objPath.Included Then
    Wscript.Echo "  " & objPath.objPath & " is crawled"
  Else
    Wscript.Echo "  " & objPath.objPath & " is ignored"
  End If
  If objPath.IncludeSubdirs Then
    Wscript.Echo "  (and its subdirectories are crawled)."
  Else
    Wscript.Echo "  (and its subdirectories are ignored)."
  End If
Next

'Release objects
Set objPath     = Nothing
Set objPaths    = Nothing
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Included


Path Property

This read-only property specifies the path that Search crawls or avoids.

Syntax

ISitePath.Path

Example

The following example displays the paths for the site Microsoft.com.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite, objPaths, objPath

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objSites    = objCatalog.objSites
Set objSite     = objSites.Item("Microsoft.com")
Set objPaths    = objSite.objPaths

Wscript.Echo "The restricted site " & objSite.Name & " has these paths:"

For Each objPath in objPaths
  Wscript.Echo "  " & objPath.objPath
Next

'Release objects
Set objPath     = Nothing
Set objPaths    = Nothing
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


ISitePaths Interface

This interface is a list of path rules (collection of ISitePath objects) that Search crawls or avoids on a site.

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog.ISiteRestrictions.ISiteRestriction

The following table briefly describes this interface's methods and properties.

Method | Description
Add | Adds a path rule to the list of path rules.
ChangeOrder | Moves a path rule up or down in the list of path rules.
Remove | Removes a path rule from the list of path rules.
Property | Description
Count | The number of path rules in the list of path rules.
Item | Accesses a path rule in the list of path rules.


Accessing an ISitePaths Object

You access an ISitePaths object by calling the ISiteRestriction.Paths property, as in the following example, where objPaths is the name you give to the ISitePaths object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite, objPaths

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objSites    = objCatalog.objSites
Set objSite     = objSites.Item("Microsoft.com")
Set objPaths    = objSite.objPaths

...

'Release objects
Set objPaths    = Nothing
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


Add Method

This method adds a path rule to the list of path rules.

Syntax

ISitePaths.Add(Path, Included)

Parameters

Path

The full path on the site that Search crawls or avoids.

Included

If True, Search crawls Path; if False, Search does not crawl Path.

Example

The following example add the path C:\Tmp to the list of paths that Search avoids on the Microsoft.com site.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite, objPaths

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objSites    = objCatalog.objSites
Set objSite     = objSites.Item("Microsoft.com")
Set objPaths    = objSite.objPaths

objPaths.Add "C:\Tmp", False

'Release objects
Set objPaths    = Nothing
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

ISitePath, Remove


ChangeOrder Method

This method moves a path rule up or down in the list of path rules.

Syntax

ISitePaths.ChangeOrder(MoveUp)

Parameters

MoveUp

If True, the path rule is moved up in the list of path rules (crawled or avoided earlier); if False, the path rule is moved down in the list of path rules (crawled or avoided later).

Example

The following example moves the path C:\Tmp up in the list of crawled or avoided path rules for the site Microsoft.com.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite, objPaths

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objSites    = objCatalog.objSites
Set objSite     = objSites.Item("Microsoft.com")
Set objPaths    = objSite.objPaths

objPaths.ChangeOrder "C:\Tmp", True

'Release objects
Set objPaths    = Nothing
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


Remove Method

This method removes a path rule from the list of path rules.

Syntax

ISitePaths.Remove(Path)

Parameters

Path

The full path rule on the site that Search was crawling or avoiding.

Example

The following example removes the path C:\Tmp from the list of path rules that Search ignores on the Microsoft.com site.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite, objPaths

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objSites    = objCatalog.objSites
Set objSite     = objSites.Item("Microsoft.com")
Set objPaths    = objSite.objPaths

objPaths.Remove("C:\Tmp")

'Release objects
Set objPaths    = Nothing
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Add, ISitePath


Count Property

This read-only property specifies the number of path rules in the list of path rules.

Syntax

ISitePaths.Count

Example

The following example displays the number of path rules in the list of path rules for the site Microsoft.com.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite, objPaths

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objSites    = objCatalog.objSites
Set objSite     = objSites.Item("Microsoft.com")
Set objPaths    = objSite.objPaths

Wscript.Echo "There are " & objPaths.Count & " paths."

'Release objects
Set objPaths    = Nothing
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


Item Property

This read-only property accesses a path rule in the list of path rules.

Syntax

ISitePaths[.Item(Path)]

Parameters

Path

A path in the list of path rules that Search crawls or avoids.

Remarks

Since ISitePaths is a collection, you need only include Item to access an ISitePaths object by name (see the following Example).

Example

The following example displays the names of all of the path rules for the site Microsoft.com.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite, objPaths, objPath

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objSites    = objCatalog.objSites
Set objSite     = objSites.Item("Microsoft.com")
Set objPaths    = objSite.objPaths

Wscript.Echo "The restricted site " & objSite.Name & " has these paths:"

For Each objPath in objPaths
  If objPath.Included Then
    Wscript.Echo "  " & objPath.objPath & " is crawled."
  Else
    Wscript.Echo "  " & objPath.objPath & " is ignored."
  End If
Next

'Release objects
Set objPath     = Nothing
Set objPaths    = Nothing
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Add, Count, ISitePath


ISiteRestriction Interface

This interface specifies a site where Search crawls or avoids certain directories.

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog.ISiteRestrictions

The following table briefly describes this interface's methods and properties.

Method | Description
SetAccount | Sets the account through which Search accesses a site contents.
Property | Description
AccountName | The account name under which Search accesses a site.
AuthenticationType | The type of authentication that Search uses to access a site.
Included | Whether Search crawls or avoids the site when crawling.
Name | The name of the site.
Paths | The path rules (ISitePaths interface) associated with a site.


Creating an ISiteRestriction Object

You create an ISiteRestriction object by calling the ISiteRestrictions.Add method, as in the following example, where objSite is the name you give to the ISiteRestriction object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objSites    = objCatalog.objSites

Set objSite = objSites.Add "Microsoft.com", False

...

'Release objects
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


Accessing ISiteRestriction Objects

You access an ISiteRestriction object by calling the ISiteRestrictions.Item property. Since ISiteRestrictions is a collection, you can access all ISiteRestriction objects using a for each loop, as in the following example, where objSite is the name you give to the ISiteRestriction object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objSites    = objCatalog.objSites

For Each objSite in objSites
  ...
Next

'Release objects
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


SetAccount Method

This method sets the account through which Search accesses a site contents.

Syntax

ISiteResriction.SetAccount(Name, Password, AuthenticationType)

Parameters

Name

The account name under which Search accesses a site. This parameter sets the AccountName property for this restricted site.

Password

The password for this account.

AuthenticationType

The type of authentication that Search uses to access this site. This parameter sets the AuthenticationType property for this restricted site.

Remarks

The types of authentication are:

Name | Value | Description
AUTH_TYPE_ANONYMOUS | 0 | Use anonymous login (default).
AUTH_TYPE_NTLM | 1 | Use NT challenge-and-response login.
AUTH_TYPE_BASIC | 2 | Use basic (clear text) login.

Example

The following example accesses the MyLocalWeb.com site as user AdminTest with the password HelpMeMrWizard, using NT challenge-and-response authentication.

Option Explicit
On Error Resume Next

Const AUTH_TYPE_NTLM = 1

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objSites    = objCatalog.objSites

Set objSite   = objSites.Item("MyLocalWeb.com")

objSite.SetAccount "AdminTest", "HelpMeMrWizard", AUTH_TYPE_NTLM

'Release objects
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

AccountName


AccountName Property

This read-only property is the login name that Search uses to log on to a site.

Syntax

ISiteResriction.AccountName

Remarks

This property returns "Default" if the default account is used.

Example

The following example displays the account name used to access the sites in the restricted site list for the KMSampleCatalog2 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite, ActName

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objSites    = objCatalog.objSites

For Each objSite in objSites
  Wscript.Echo objSite.Name & " is accessed through the login name: "
    & ActName

Next

'Release objects
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

SetAccount


AuthenticationType Property

This read-only property specifies the type of authentication that Search uses to access a site.

Syntax

SiteResriction.AuthenticationType

Remarks

The types of authentication are:

Name | Value | Description
AUTH_TYPE_ANONYMOUS | 0 | Use anonymous login (default).
AUTH_TYPE_NTLM | 1 | Use NT challenge-and-response login.
AUTH_TYPE_BASIC | 2 | Use basic (clear text) login.

Example

The following example displays the authentication type for the sites with restrictions in the KMSampleCatalog1 catalog definition.

Option Explicit
On Error Resume Next

Const AUTH_TYPE_ANONYMOUS = 0
Const AUTH_TYPE_NTLM      = 1
Const AUTH_TYPE_BASIC     = 2

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objSites    = objCatalog.objSites

For Each objSite in objSites
  Select Case objSite.AuthenticationType
    Case AUTH_TYPE_ANONYMOUS
    Wscript.Echo objSite.Name & " uses anonymous login."
    Case AUTH_TYPE_BASIC
    Wscript.Echo objSite.Name & " uses basic login."
    Case AUTH_TYPE_NTLM
    Wscript.Echo objSite.Name & " uses NT login."
  End Select
Next

'Release objects
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

SetAccount


Included Property

This property specifies whether Search crawls or avoids the site when crawling.

Syntax

SiteResriction.Included

Remarks

If True, Search crawls the site; if False, Search does not crawl the site.

Example

The following example displays whether Search crawls the sites in the restriction list for the KMSampleCatalog1 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objSites    = objCatalog.objSites

Wscript.Echo objCatalog.Name & " has the following site restrictions:"

For Each objSite in objSites
  If objSite.Included Then
    Wscript.Echo "  " & objSite.Name & " is crawled."
  Else
    Wscript.Echo "  " & objSite.Name & " is avoided."
  End If
Next

'Release objects
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Name, Paths


Name Property

This read-only property specifies the name of the site.

Syntax

ISiteResriction.Name

Example

The following example displays the names of the restricted sites for the KMSampleCatalog1 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objSites    = objCatalog.objSites

Wscript.Echo objCatalog.Name & " restricts the following sites:"

For Each objSite in objSites
  Wscript.Echo "  " & objSite.Name
Next

'Release objects
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

SetAccount


Paths Property

This read-only property specifies the path rules (ISitePaths interface) associated with a site.

Syntax

ISiteResriction.Paths

Example

The following example displays the paths for the sites in the restricted site list for the KMSampleCatalog1 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite, objPaths, objPath

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog1")
Set objSites    = objCatalog.objSites

Wscript.Echo objCatalog.Name & " has the following restricted sites:"

For Each objSite in objSites
  Wscript.Echo "  " & objSite.Name & " has the following paths:"
  objPaths = objSite.objPaths
    For Each objPath in objPaths
      Wscript.Echo objPath.Name
    Next
    Wscript.Echo ""
Next

'Release objects
Set objPath     = Nothing
Set objPaths    = Nothing
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Name


ISiteRestrictions Interface

This interface is a list of restrictions (collection of ISiteRestriction objects) that tells Search whether to crawl or avoid certain sites and their directories.

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog

The following table briefly describes this interface's methods and properties.

Methods | Description
Add | Adds a site to the site restriction list.
ChangeOrder | Moves a site up or down in the site restriction list.
Remove | Removes a site from the site restriction list.
Property | Description
Count | The number of sites in the site restriction list.
Item | Accesses a site in the site restriction list.


Accessing an ISiteRestrictions Object

You access an ISiteRestrictions object by calling the IBuildCatalog.Sites property, as in the following example, where objSites is the name you give to the ISiteRestrictions object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objSites    = objCatalog.objSites

...

'Release objects
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing


Add Method

This method adds a site to the site restriction list.

Syntax

ISiteRestrictions.Add(SiteName, Included)

Parameters

SiteName

The name of the site to which the site rule applies.

Included

If True, Search crawls this site; if False, Search does not crawl this site.

Remarks

You must not supply the http:// prefix to the site name. If you have path restrictions that you want to specify for the site, you must first add the site, then apply the path restrictions (see the ISitePaths.Add method).

Example

The following example avoids the site Microsoft.com.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objSites    = objCatalog.objSites

objSites.Add "Microsoft.com", False

'Release objects
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

ISiteRestriction, Remove


ChangeOrder Method

This method moves a site up or down in the site restriction list.

Syntax

ISiteRestrictions.ChangeOrder(SiteName, Up)

Parameters

SiteName

The name of the site to move.

Up

If True, Search moves the site up in the list; if False, Search moves it down.

Remarks

If the site is not in the list of sites, Search ignores the request.

Example

The following example moves the site Microsoft.com up in the list, then displays the names of all of the sites in the list.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objSites    = objCatalog.objSites

objSites.ChangeOrder "Microsoft.com", True

Wscript.Echo objCatalog.Name & " has the following site restrictions:"

For Each objSite in objSites
  Wscript.Echo "  " & objSite.Name
Next

'Release objects
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

ISiteRestriction


Remove Method

This method removes a site from the site restriction list.

Syntax

ISiteRestrictions.Remove(Name)

Parameters

Name

The name of the site to remove from the list.

Example

The following example removes the site Microsoft.com from the list of sites with restrictions for the KMSampleCatalog2 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs
Set objCatalog  = objCatalogs("KMSampleCatalog2")
Set objSites    = objCatalog.objSites

objSites.Remove("Microsoft.com")

'Release objects
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Add, Count, ISiteRestriction


Count Property

This read-only property specifies the number of sites in the site restriction list.

Syntax

ISiteRestrictions.Count

Example

The following example displays the number of sites in the site restriction list for all catalogs.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  Set objSites  = objCatalog.objSites
  Wscript.Echo objCatalog.Name & " has " & objSites.Count "
    & " sites in its site restriction list."
Next

'Release objects
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Add, ISiteRestriction, Remove


Item Property

This read-only property accesses a site in the site restriction list.

Syntax

ISiteRestrictions[.Item(Name)]

Settings

Name

The name of the site.

Remarks

Since ISiteRestrictions is a collection, you need only include Item to access an ISiteRestriction object by name (see the following Example).

Example

The following example displays the names of all sites in the site restriction lists for all catalogs.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSites, objSite

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  Set objSites  = objCatalog.objSites
  Wscript.Echo objCatalog.Name & " restricts the following sites:"

  For Each objSite in objSites
    Wscript.Echo objSite.Name
  Next

  Wscript.Echo ""
Next

'Release objects
Set objSite     = Nothing
Set objSites    = Nothing
Set objCatalog  = Nothing
Set objCatalogs = Nothing
Set objBuildServer = Nothing
Set objSearchAdmin = Nothing

See Also

Add, Count, ISiteRestriction, Remove


IStartPage Interface

This interface is a location where Search starts crawling a site.

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog.IStartPages

The following table briefly describes this interface's properties.

Property | Description
EnumerationDepth | The number of page hops for a Web link crawl, the directory depth for a File crawl, or the folder depth for a Microsoft Exchange public folder.
FollowDirectories | Whether Search performs a File (or Microsoft Exchange public folder) crawl and crawls directories (or folders) or performs a Web link crawl and follows links out of the start address.
HostDepth | The number of site hops for a Web link crawl.
URL | The URL for the start address.


Creating an IStartPage Object

You create an IStartPage object by calling the IStartPages.Add method, as in the following example, where objStartPage is the name you give to the IStartPage object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objStartPages, objStartPage

Set objSearchAdmin    = CreateObject("Search.SearchAdmin.1")
Set objBuildServer    = objSearchAdmin.BuildServer
Set objCatalogs    = objBuildServer.BuildCatalogs
Set objCatalog     = objCatalogs("KMSampleCatalog2")
Set objStartPages  = objCatalog.objStartPages

Set objStartPage = objStartPages.Add("http://www.microsoft.com")

...

'Release objects
Set objStartPage  = Nothing
Set objStartPages = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing


Accessing IStartPage Objects

You can access a specific IStartPage object by calling the IStartPages.Item property. Since IStartPages is a collection, you can access all IStartPage objects using a for each loop, as in the following example, where objStartPage is the name you give to the IStartPage object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objStartPages, objStartPage

Set objSearchAdmin   = CreateObject("Search.SearchAdmin.1")
Set objBuildServer   = objSearchAdmin.BuildServer
Set objCatalogs  = objBuildServer.BuildCatalogs
Set objCatalog    = objCatalogs("KMSampleCatalog1")
Set objStartPages = objCatalog.objStartPages

For Each objStartPage in objStartPages
  ...
Next

'Release objects
Set objStartPage  = Nothing
Set objStartPages = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing


EnumerationDepth Property

This property specifies the number of page hops (jumps that cross a site boundary).

Syntax

IStartPage.EnumerationDepth

Example

The following example displays the number of page hops for the site Microsoft.com for the KMSampleCatalog1 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objStartPages, objStartPage

Set objSearchAdmin    = CreateObject("Search.SearchAdmin.1")
Set objBuildServer    = objSearchAdmin.BuildServer
Set objCatalogs    = objBuildServer.BuildCatalogs
Set objCatalog     = objCatalogs("KMSampleCatalog1")
Set objStartPages  = objCatalog.objStartPages
Set objStartPage   = objStartPages.Item("http://www.microsoft.com")

Wscript.Echo objCatalog.Name & " is configured with " & objStartPage.EnumerationDepth
  & " page hops For " & objStartPage.URL

'Release objects
Set objStartPage  = Nothing
Set objStartPages = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing

See Also

FollowDirectories, HostDepth , URL


FollowDirectories Property

This property specifies whether Search performs a File (or Microsoft Exchange public folder) crawl and crawls directories (or folders) or performs a Web link crawl and follows links out of the start address.

Syntax

IStartPage.FollowDirectories

Remarks

If True, Search crawls directories (or folders) that are beneath the start address; if False, Search performs a Web link crawl out of the start address.

Example

The following example displays whether Search crawls the directories under the Web page http://www.microsoft.com for the KMSampleCatalog1 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objStartPages, objStartPage

Set objSearchAdmin    = CreateObject("Search.SearchAdmin.1")
Set objBuildServer    = objSearchAdmin.BuildServer
Set objCatalogs    = objBuildServer.BuildCatalogs
Set objCatalog     = objCatalogs("KMSampleCatalog1")
Set objStartPages  = objCatalog.objStartPages
Set objStartPage   = objStartPages.Item("http://www.microsoft.com")

If objStartPage.FollowDirectories Then
  Wscript.Echo objCatalog.Name & " crawls directories under "
    & objStartPage.URL
Else
  Wscript.Echo objCatalog.Name & " does not search directories under "
    & objStartPage.URL

End If

'Release objects
Set objStartPage  = Nothing
Set objStartPages = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing

See Also

EnumerationDepth, HostDepth , URL


HostDepth Property

This property specifies the number of site hops Search can make when crawling the start address.

Syntax

IStartPage.HostDepth

Example

The following example displays the site hops for the start address http://www.microsoft.com for the KMSampleCatalog2 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objStartPages, objStartPage

Set objSearchAdmin    = CreateObject("Search.SearchAdmin.1")
Set objBuildServer    = objSearchAdmin.BuildServer
Set objCatalogs    = objBuildServer.BuildCatalogs
Set objCatalog     = objCatalogs("KMSampleCatalog2")
Set objStartPages  = objCatalog.objStartPages
Set objStartPage   = objStartPages.Item("http://www.microsoft.com")

Wscript.Echo objCatalog.Name & " goes " & objStartPage.HostDepth
  & " levels deep For Web page " & objStartPage.URL

'Release objects
Set objStartPage  = Nothing
Set objStartPages = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing

See Also

EnumerationDepth , FollowDirectories, URL


URL Property

This read-only property specifies the URL for the Web page.

Syntax

IStartPage.URL

Example

The following example displays the URL for the Web pages for the KMSampleCatalog2 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objStartPages, objStartPage

Set objSearchAdmin    = CreateObject("Search.SearchAdmin.1")
Set objBuildServer    = objSearchAdmin.BuildServer
Set objCatalogs    = objBuildServer.BuildCatalogs
Set objCatalog     = objCatalogs("KMSampleCatalog2")
Set objStartPages  = objCatalog.objStartPages

Wscript.Echo objCatalog.Name & " crawls the following For Web pages:"

For Each objStartPage in objStartPages
  Wscript.Echo "  " & objStartPage.URL
Next

'Release objects
Set objStartPage  = Nothing
Set objStartPages = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing

See Also

EnumerationDepth , FollowDirectories, HostDepth


IStartPages Interface

This interface is a list of locations (collection of IStartPage objects) where Search starts crawling.

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog

The following table briefly describes this interface's methods and properties.

Methods | Description
Add | Adds a Web page to the list of Web pages.
Remove | Removes a Web page from the list of Web pages.
Property | Description
Count | The number of Web pages in the list of Web pages.
Item | Accesses a Web page from the list of Web pages.


Accessing an IStartPages Object

You access an IStartPages object by calling the IBuildCatalog.StartPages property, as in the following example, where objStartPages is the name you give to the IStartPages object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objStartPages

Set objSearchAdmin   = CreateObject("Search.SearchAdmin.1")
Set objBuildServer   = objSearchAdmin.BuildServer
Set objCatalogs   = objBuildServer.BuildCatalogs
Set objCatalog    = objCatalogs("KMSampleCatalog1")
Set objStartPages = objCatalog.objStartPages

...

'Release objects
Set objStartPages = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing


Add Method

This method adds a Web page to the list of Web pages.

Syntax

IStartPages.Add(URL)

Parameters

URL

The URL of the Web page to add to the list of Web pages.

Example

The following example adds the http://www.microsoft.com Web page to the list of Web pages that Search crawls.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objStartPages, objStartPage

Set objSearchAdmin    = CreateObject("Search.SearchAdmin.1")
Set objBuildServer    = objSearchAdmin.BuildServer
Set objCatalogs    = objBuildServer.BuildCatalogs
Set objCatalog     = objCatalogs("KMSampleCatalog2")
Set objStartPages  = objCatalog.objStartPages

Set objStartPage = objStartPages.Add("http://www.microsoft.com")

...

'Release objects
Set objStartPage  = Nothing
Set objStartPages = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing

See Also

Count, IStartPage, Remove


Remove Method

This method removes a Web page from the list of Web pages.

Syntax

IStartPages.Remove(URL)

Parameters

URL

The URL of the Web page to remove from the list of Web pages.

Example

The following example removes the http://www.microsoft.com Web page from the list of Web pages that Search crawls.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objStartPages, objStartPage

Set objSearchAdmin    = CreateObject("Search.SearchAdmin.1")
Set objBuildServer    = objSearchAdmin.BuildServer
Set objCatalogs    = objBuildServer.BuildCatalogs
Set objCatalog     = objCatalogs("KMSampleCatalog2")
Set objStartPages  = objCatalog.objStartPages

objStartPages.Remove("http://www.microsoft.com")

'Release objects
Set objStartPages = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing

See Also

Add, Count, IStartPage


Count Property

This read-only property specifies the number of start addresses in the collection of start addresses.

Syntax

IStartPages.Count

Example

The following example displays the number of start pages for the KMSampleCatalog2 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objStartPages

Set objSearchAdmin    = CreateObject("Search.SearchAdmin.1")
Set objBuildServer    = objSearchAdmin.BuildServer
Set objCatalogs    = objBuildServer.BuildCatalogs
Set objCatalog     = objCatalogs("KMSampleCatalog2")
Set objStartPages  = objCatalog.objStartPages

Wscript.Echo objCatalog.Name & " has " & objStartPages.Count & " start pages."

'Release objects
Set objStartPages = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing

See Also

Item


Item Property

This read-only property accesses a Web page from the list of Web pages.

Syntax

IStartPages[.Item(URL)]

Parameters

URL

The URL of the Web page to add to the list of Web pages.

Remarks

Since IStartPages is a collection, you need only include Item to access an IStartPages object by name (see the following Example).

Example

The following example displays the URLs of the start pages for the KMSampleCatalog1 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objStartPages, objStartPage

Set objSearchAdmin    = CreateObject("Search.SearchAdmin.1")
Set objBuildServer    = objSearchAdmin.BuildServer
Set objCatalogs    = objBuildServer.BuildCatalogs
Set objCatalog     = objCatalogs("KMSampleCatalog1")
Set objStartPages  = objCatalog.objStartPages

Wscript.Echo objCatalog.Name & " searches the following start pages:"

For Each objStartPage in objStartPages
  Wscript.Echo "  " & objStartPage.URL
Next

'Release objects
Set objStartPage  = Nothing
Set objStartPages = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing

See Also

Add, Count, IStartPage, Remove


IStoplist Interface

This interface specifies a file containing words that Search ignores when building a catalog.

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog.ISearchSchema.IStoplists

The following table briefly describes this interface's properties.

Note Changes to these properties do not take effect until you call the ISearchSchema.Save method.

Property | Description
Filename | The full path to the file containing the list of words that Search ignores.
Language | The Win32 primary language ID for the language to which the list of ignored words applies.
Name | The name of the language and/or sublanguage stop list, for descriptive purposes only.
SubLanguage | The Win32 sublanguage ID to which the list of ignored words applies.


Creating an IStoplist Object

You create an IStoplist object by calling the IStoplists.Add method, as in the following example, where objStoplist is the name you give to the IStoplist object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSchema, objStoplists, objStoplist

Set objSearchAdmin   = CreateObject("Search.SearchAdmin.1")
Set objBuildServer   = objSearchAdmin.BuildServer
Set objCatalogs   = objBuildServer.BuildCatalogs
Set objCatalog    = objCatalogs("KMSampleCatalog1")
Set objSchema     = objCatalog.objSchema
Set objStoplists  = objSchema.objStoplists

Set objStoplist = objStoplists.Add("C:\objStoplists\Noise.enu")

...

'Release objects
Set objStoplist   = Nothing
Set objStoplists  = Nothing
Set objSchema     = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing


Accessing IStoplist Objects

You can access a specific IStoplist object by calling the IStoplists.Item property. Since IStoplists is a collection, you can access all IStoplist objects using a for each loop, as in the following example, where objStoplist is the name you give to the IStoplist object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSchema, objStoplists, objStoplist

Set objSearchAdmin = CreateObject("Search.SearchAdmin.1")
Set objBuildServer = objSearchAdmin.BuildServer
Set objCatalogs = objBuildServer.BuildCatalogs

For Each objCatalog in objCatalogs
  Set objSchema    = objCatalog.objSchema
  Set objStoplists = objSchema.objStoplists

  Wscript.Echo "The schema For " & objCatalog.Name
    & " has these stop lists:"

  For Each objStoplist in objStoplists
    Wscript.Echo "  Name:        " & objStoplist.Name
    Wscript.Echo "  Filename:    " & objStoplist.Filename
    Wscript.Echo "  Language:    " & objStoplist.Language
    Wscript.Echo "  SubLanguage: " & objStoplist.SubLanguage
    Wscript.Echo ""
  Next
  Wscript.Echo ""
Next

'Release objects
Set objStoplist   = Nothing
Set objStoplists  = Nothing
Set objSchema     = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing


Filename Property

This property specifies the full path to the file containing the list of words that Search ignores.

Syntax

IStoplist.Filename

Example

See Accessing an IStoplist Object.

See Also

Name


Name Property

This property specifies the name of the list of words that Search ignores.

Syntax

IStoplist.Name

Remarks

By convention, the Name value is the concatenation of the primary and sublanguage names. The value is for descriptive purposes only, and has no functional significance.

Example

See Accessing an IStoplist Object.

See Also

Filename


Language Property

This property specifies the primary language to which the list of ignored words applies.

Syntax

IStoplist.Language

Remarks

Language is an integer containing the Win32 primary language ID to which the list of ignored words applies.

The Language and SubLanguage values must be unique in this Searcg schema.

Example

See Accessing an IStoplist Object.

See Also

SubLanguage


SubLanguage Property

This property specifies the language dialect to which the list of ignored words applies.

Syntax

IStoplist.SubLanguage

Remarks

SubLanguage is an integer containing the Win32 sub-language ID to which the list of ignored words applies.

The Language and SubLanguage values must be unique in this Search schema.

Example

See Accessing an IStoplist Object.

See Also

Language


IStoplists Interface

This interface is a list of files (collection of IStoplist objects) containing words that Search ignores when building a catalog.

Hierarchy

ISearchAdmin.IBuildServer.IBuildCatalogs.IBuildCatalog.ISearchSchema

The following table briefly describes this interface's methods and properties.

Note The changes made by these methods do not take effect until you call the ISearchSchema.Save method.

Method | Description
Add | Adds a list of ignored words.
Clear | Clears a list of ignored words.
Remove | Removes a list of ignored words.
Property | Description
Count | The number of lists of ignored words.
Item | Accesses a list of ignored words.


Accessing an IStoplists Object

You access an IStoplists object by calling the ISearchSchema.Stoplists property, as in the following example, where objStoplists is the name you give to the IStoplists object:

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSchema, objStoplists

Set objSearchAdmin   = CreateObject("Search.SearchAdmin.1")
Set objBuildServer   = objSearchAdmin.BuildServer
Set objCatalogs   = objBuildServer.BuildCatalogs
Set objCatalog    = objCatalogs("KMSampleCatalog1")
Set objSchema     = objCatalog.objSchema
Set objStoplists  = objSchema.objStoplists

...

'Release objects
Set objStoplists  = Nothing
Set objSchema     = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing


Add Method

This method adds a list of ignored words.

Syntax

IStoplists.Add(Name, Filename, Language, SubLanguage)

Parameters

Name

A text string specifying the name of the stop list. Sets the Name property of the resulting stop list to this value.

Filename

A text string specifying the full path to the file containing the list of words that Search ignores. Sets the Filename property of the resulting stop list to this value.

Language

A vbLong specifying the language to which the stop list applies. Sets the Language property of the resulting stop list to this value.

SubLanguage

A vbLong specifying the language dialect to which the stop list applies. Sets the SubLanguage property of the resulting stop list to this value.

Remarks

The Language and SubLanguage values must be unique in this Search schema.

Validation is not performed until you execute the SearchSchema.Save method.

Example

The following example adds the stop list at C:\SiteStoplist\Noise.enu to the schema for the KMSampleCatalog1 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSchema, objStoplists

Set objSearchAdmin   = CreateObject("Search.SearchAdmin.1")
Set objBuildServer   = objSearchAdmin.BuildServer
Set objCatalogs   = objBuildServer.BuildCatalogs
Set objCatalog    = objCatalogs("KMSampleCatalog1")
Set objSchema     = objCatalog.objSchema
Set objStoplists  = objSchema.objStoplists

objStoplists.Add "Noise", "C:\objStoplists\Noise.enu", 9, 1

'Release objects
Set objStoplists  = Nothing
Set objSchema     = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing

See Also

Count, Remove


Clear Method

This method clears the schema stop lists.

Syntax

IStoplists.Clear

Remarks

This method is not permanent unless you subsequently call the Schema.Save method on the catalog.

Example

The following example clears the stop lists for the KMSampleCatalog1 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSchema, objStoplists

Set objSearchAdmin  = CreateObject("Search.SearchAdmin.1")
Set objBuildServer   = objSearchAdmin.BuildServer
Set objCatalogs   = objBuildServer.BuildCatalogs
Set objCatalog    = objCatalogs("KMSampleCatalog1")
Set objSchema     = objCatalog.objSchema
Set objStoplists  = objSchema.objStoplists

objStoplists.Clear

'Release objects
Set objStoplists  = Nothing
Set objSchema     = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer  = Nothing
Set objSearchAdmin   = Nothing

See Also

Count


Remove Method

This method removes a list of ignored words.

Syntax

IStoplists.Remove(Name)

Parameters

Name

The name of the stop list to remove.

Example

The following example removes the stop list Noise.enu from the KMSampleCatalog1 catalog definition's schema.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSchema, objStoplists

Set objSearchAdmin   = CreateObject("Search.SearchAdmin.1")
Set objBuildServer   = objSearchAdmin.BuildServer
Set objCatalogs   = objBuildServer.BuildCatalogs
Set objCatalog    = objCatalogs("KMSampleCatalog1")
Set objSchema     = objCatalog.objSchema
Set objStoplists  = objSchema.objStoplists

objStoplists.Remove("Noise.enu")

'Release objects
Set objStoplists  = Nothing
Set objSchema     = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing

See Also

Add, Count


Count Property

This read-only property specifies the number of stop lists.

Syntax

IStoplists.Count

Example

The following example displays the number of stop lists.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSchema, objStoplists

Set objSearchAdmin   = CreateObject("Search.SearchAdmin.1")
Set objBuildServer   = objSearchAdmin.BuildServer
Set objCatalogs   = objBuildServer.BuildCatalogs
Set objCatalog    = objCatalogs("KMSampleCatalog1")
Set objSchema     = objCatalog.objSchema
Set objStoplists  = objSchema.objStoplists

Wscript.Echo objCatalog.Name & " has " & objStoplists.Count & " stop lists."

'Release objects
Set objStoplists  = Nothing
Set objSchema     = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing

See Also

Add, IStoplist, Remove


Item Property

This read-only property accesses a stop list (IStoplist interface) by its Name property.

Syntax

IStoplists[.Item(List)]

Settings

List

A text string specifying the name of the stop list to access.

Remarks

Since IStoplists is a collection, you need only include Item to access an IStoplist object by name (see the following Example).

Example

The following example displays the names of all of the stop lists for the KMSampleCatalog2 catalog definition.

Option Explicit
On Error Resume Next

Dim objSearchAdmin, objBuildServer, objCatalogs, objCatalog, objSchema, objStoplists, objStoplist

Set objSearchAdmin   = CreateObject("Search.SearchAdmin.1")
Set objBuildServer   = objSearchAdmin.BuildServer
Set objCatalogs   = objBuildServer.BuildCatalogs
Set objCatalog    = objCatalogs("KMSampleCatalog2")
Set objSchema     = objCatalog.objSchema
Set objStoplists  = objSchema.objStoplists

Wscript.Echo "The schema For " & objCatalog.Name & " has these stop lists:"

For Each objStoplist in objStoplists
  Wscript.Echo objStoplist.Name
Next

'Release objects
Set objStoplist   = Nothing
Set objStoplists  = Nothing
Set objSchema     = Nothing
Set objCatalog    = Nothing
Set objCatalogs   = Nothing
Set objBuildServer   = Nothing
Set objSearchAdmin   = Nothing

See Also

Count, IStoplist


COM Interface Status Codes

The Search COM interfaces provide a set of custom HRESULT values that provide programmers or scripters with detailed information about the state of the system when either an exception occurs, or a status-related method invocation is used. Each of the custom HRESULT values supported by the Search COM interfaces is listed below. In all cases, the standard HRESULT FACILITY code portion of the value will be set to type FACILITY_ITF = 0x4. This identifies the result as having a specific meaning strictly in relation to the interface method or property that was executing when the HRESULT code was generated at runtime. The full HRESULT values will always therefore be prefixed with the first two bytes either 0x(8004)(0000) or 0x(0004)(0000) in hexadecimal format, indicating an exceptional situation has occurred, or extended "success" information is present, respectively. The remaining 2 bytes of information identify the specifics of the value as they relate to the Search interfaces and objects. The first of the two bytes breaks down the interface relative error into one of the following categories:

  • 0x0300 - Network Related

  • 0x1400 - Security Related

  • 0x0400 - Data Source Related

  • 0x0500 - Collator Related

  • 0x0600 - Connection Manager Values

  • 0x0700 - Query Related

  • 0x0c00 - Source Schema Related

  • 0x0d00 - Gatherer Service Related Values

  • 0x1200 - Protocol Handler Related

  • 0x1100 - Indexer Related

  • 0x11a0 - Indexer (Exchange) Related

  • 0x1300 - Setup Related

  • 0x1500 - Command-Line Tool Related

  • 0x1900 - Admin Related Values

The final byte uniquely identifies the error as a subset of one of the categories above.

Examples of use are given to demonstrate common procedures when working with custom HRESULT values.

A C header file accompanies the SDK that defines the error names and hexadecimal values listed here if direct use is desired.


Network Related Values

These values all have the bits 0x0300 in common.

HRESULT Value (Hex) | Status Code Name | Description
0x80040300 | NET_E_GENERAL | A network I/O operation failed.
0x80040301 | NET_E_UNEXPECTED | An unexpected network failure occurred.
0x80040302 | NET_E_RESOURCES | Operation failure: Not enough network resources to complete the operation.
0x80040303 | NET_E_DISCONNECTED | The network connection has been lost.
0x80040304 | NET_E_BADSEQUENCE | Internal error: Operation sequence is not valid.
0x80040305 | NET_E_NETDOWN | The network subsystem failed.
0x80040306 | NET_E_WINSOCKNOTINITIALIZED | Internal error: The Windows socket service is not initialized.
0x80040307 | NET_E_ADDRINUSE | Unable to initialize Search server. TCP/IP port is already in use.
0x80040308 | NET_E_INVALIDPARAMS | Internal error: The parameters passed were not valid.
0x80040309 | NET_E_OPERATIONINPROGRESS | Internal error: Another operation is already in progress on this socket.
0x8004030a | NET_E_HOSTNOTFOUND | Unable to find the specified host.
0x8004030b | NET_E_HOSTLOOKUPFAILED | Host lookup failed.
0x8004030c | NET_E_CONNABORTED | The network connection timed out or halted because of other errors.
0x8004030d | NET_S_MOREDATA | The current message contains additional data.
0x8004030e | NET_E_CONNREFUSED | The remote machine refused the connection.
0x8004030f | NET_E_TIMEOUT | The network operation timed out.


Security Related Values

These values all have the bits 0x1400 in common.

HRESULT Value (Hex) | Status Code Name | Description
0x80041403 | SEC_E_INVALIDCONTEXT | The Search Service is running in the context of the local machine. To access Exchange documents, make sure the Search Service is running in the context of a user having administrative privileges on the Exchange server.
0x80041401 | SEC_E_INITFAILED | Unable to initialize Exchange search provider.
0x80041402 | SEC_E_NOTINITIALIZED | The security provider has not been initialized.
0x800414ff | SEC_E_ACCESSDENIED | Access is denied.


Data Source Related Values

These values all have the bits 0x0400 in common.

HRESULT Value (Hex) | Status Code Name | Description
0x80040400 | DS_E_NOMOREDATA | Internal error: There is no more data to return.
0x80040401 | DS_E_INVALIDDATASOURCE | The requested catalog name is not valid.
0x80040402 | DS_E_DATASOURCENOTAVAILABLE | The requested catalog is disabled on the Search server.
0x80040403 | DS_E_QUERYCANCELED | The query was canceled at the caller's request.
0x80040404 | DS_E_UNKNOWNREQUEST | Internal error: The request code is not valid.
0x80040405 | DS_E_BADREQUEST | Internal error: The request data is not valid for the given request type.
0x80040406 | DS_E_SERVERCAPACITY | Unable to process request. The Search server is out of memory.
0x80040407 | DS_E_BADSEQUENCE | The request or function call is not valid at this time.
0x80040408 | DS_E_MESSAGETOOLONG | The query text is too long.
0x80040409 | DS_E_SERVERERROR | Unable to process request due to an internal error in the Search server.
0x8004040a | DS_E_CONFIGBAD | The configuration file for the catalog is not valid.
0x8004040b | DS_E_CANNOTBACKUP | The Search server is unable to create the backup configuration file.
0x8004040c | DS_E_MOVEFAILED | Unable to move a catalog file from the drop directory.
0x80040410 | DS_E_DATANOTPRESENT | The Search server is unable to find one or more catalog files.
0x80040411 | DS_E_SETSTATUSINPROGRESS | Unable to complete SetStatus operation. Another SetStatus operation is already in progress.
0x80040412 | DS_E_DUPLICATEID | Unable to create catalog. Another catalog with the same name already exists.
0x80040413 | DS_E_TOOMANYDATASOURCES | Unable to create catalog. The limit on the number of catalogs has been reached.
0x80040414 | DS_E_REGISTRY | The Search server encountered an error reading or writing to the registry. Verify that the Search server is running with administrative privilege.
0x80040415 | DS_E_DATASOURCENOTDISABLED | The catalog must be disabled before it can be removed.
0x80040416 | DS_E_INVALIDTAGDB | The tag database is not valid.
0x80040417 | DS_E_INVALIDCATALOGNAME | The catalog name is in the wrong format.
0x80040418 | DS_E_CONFIGNOTRIGHTTYPE | The configuration file is not the correct type.
0x80040419 | DS_E_PROTOCOLVERSION | Protocol versions do not match.
0x8004041a | DS_E_ALREADYENABLED | The catalog is already enabled.
0x8004041b | DS_E_DROPSHARE | Unable to create network share for drop directory.
0x8004041c | DS_E_INDEXDIRECTORY | Unable to create catalog directory structure.
0x8004041d | DS_E_VALUETOOLARGE | The value exceeds the maximum length.
0x8004041e | DS_E_UNKNOWNPARAM | The requested parameter is unknown.
0x8004041f | DS_E_BUFFERTOOSMALL | The buffer is too small.
0x80040420 | DS_E_PARAMOUTOFRANGE | The parameter value is out of range.
0x80040421 | DS_E_ALREADYDISABLED | The catalog is already disabled.
0x80040422 | DS_E_QUERYHUNG | Unable to complete the operation. One or more queries failed to terminate in a timely manner.
0x80040423 | DS_E_BADRESULT | The result is invalid.
0x80040424 | DS_E_CANNOTWRITEREGISTRY | Unable to write registry data. Please verify that the Search Service is running with administrator privileges.


Collator Related Values

These values all have the bits 0x0500 in common.

HRESULT Value (Hex) | Status Code Name | Description
0x80040501 | COLL_E_BADSEQUENCE | Internal error: The requested operation is not valid at this time.
0x80040502 | COLL_E_NOMOREDATA | Internal error: There is no more data to return.
0x80040503 | COLL_E_INCOMPATIBLECOLUMNS | Unable to collate the query. Columns using the same name have different types.
0x80040504 | COLL_E_BUFFERTOOSMALL | Internal error: Not enough buffer space to collate search results.
0x80040506 | COLL_E_BADRESULT | Internal error: The result row is corrupted.
0x80040507 | COLL_E_NOSORTCOLUMN | The Search server did not return a column required for collation.
0x80040508 | COLL_E_DUPLICATEDBID | Internal error: Duplicate database ID.
0x80040509 | COLL_E_TOOMANYMERGECOLUMNS | The data source merge exceeded the number of result columns.
0x8004050a | COLL_E_NODEFAULTCATALOG | No default catalog has been set.


Connection Manager Values

These values all have the bits 0x0600 in common.

HRESULT Value (Hex) | Status Code Name | Description
0x80040601 | CM_E_TOOMANYDATASERVERS | The limit on the number of Search servers has been reached.
0x80040602 | CM_E_TOOMANYDATASOURCES | The limit on the number of catalogs has been reached.
0x80040603 | CM_E_NOQUERYCONNECTIONS | Unable to establish any query connections to the server.
0x80040604 | CM_E_DATASOURCENOTAVAILABLE | The requested catalog is disabled.
0x80040605 | CM_E_CONNECTIONTIMEOUT | Timed out trying to acquire a connection to a Search server.
0x80040606 | CM_E_SERVERNOTFOUND | Internal error: Unable to find the specified server.
0x00040607 | CM_S_NODATASERVERS | Unable to establish a connection to any Search server.
0x80040608 | CM_E_REGISTRY | Unable to access the Windows NT registry.
0x80040609 | CM_E_INVALIDDATASOURCE | The requested catalog is empty or has not been added to the Search server.
0x8004060a | CM_E_TIMEOUT | The query timed out.
0x8004060b | CM_E_INSUFFICIENTBUFFER | Internal error: The buffer area passed to the function is not large enough.


Query Related Values

These values all have the bits 0x0700 in common.

HRESULT Value (Hex) | Status Code Name | Description
0x80040701 | QRY_E_QUERYSYNTAX | The query syntax is not valid.
0x80040702 | QRY_E_TYPEMISMATCH | The column type in the search query does not match the column type in the catalog.
0x80040703 | QRY_E_UNHANDLEDTYPE | The query type specified is unknown or not handled.
0x80040704 | QRY_E_NOROWSFOUND | No matching items were found for this query.
0x80040705 | QRY_E_TOOMANYCOLUMNS | The number of columns requested exceeds the limit.
0x80040706 | QRY_E_TOOMANYDATABASES | The query contained too many catalog IDs.
0x80040707 | QRY_E_STARTHITTOBIG | The query start hit is larger than the total number of results.
0x80040708 | QRY_E_TOOMANYQUERYTERMS | Too many query terms.
0x80040709 | QRY_E_NODATASOURCES | No catalogs specified.
0x8004070a | QRY_E_TIMEOUT | The query operation timed out.
0x8004070b | QRY_E_COLUMNNOTSORTABLE | The query specified sorting a non-sortable column.
0x8004070c | QRY_E_COLUMNNOTSEARCHABLE | The query specified searching a non-searchable column.
0x8004070d | QRY_E_INVALIDCOLUMN | The query specified a nonexistent column.
0x8004070e | QRY_E_QUERYCORRUPT | The query data is not valid or is inconsistent.
0x8004070f | QRY_E_PREFIXWILDCARD | A query term begins with a wildcard character.
0x80040710 | QRY_E_INFIXWILDCARD | A query term contains an invalid embedded wildcard character.
0x80040711 | QRY_E_WILDCARDPREFIXLENGTH | A wildcard term in the query does not contain a sufficiently long prefix.
0x00040712 | QRY_S_TERMIGNORED | SUCCESS: The query term was ignored.
0x80040713 | QRY_E_ENGINEFAILED | The Search server is unable to process the query.
0x80040714 | QRY_E_SEARCHTOOBIG | The search criteria are too general or matched too many terms.
0x80040715 | QRY_E_NULLQUERY | The query does not contain any meaningful restrictions.
0x00040716 | QRY_S_INEXACTRESULTS | The query found some matching items but is unable to compile the entire result set.
0x80040717 | QRY_E_NOCOLUMNS | The query did not specify any return columns.
0x80040718 | QRY_E_INVALIDSCOPES | The scopes specified for the query were incorrectly formatted.
0x80040719 | QRY_E_INVALIDCATALOG | The catalogs specified for the query were incorrectly formatted.
0x8004071a | QRY_E_SCOPECARDINALIDY | The number of scopes or depths was not valid.


Source Schema Related Values

These values all have the bits 0x0c00 in common.

HRESULT Value (Hex) | Status Code Name | Description
0x80040c01 | SCHEMA_E_LOAD_SPECIAL | The configuration file attempted to load a reserved column.
0x80040c02 | SCHEMA_E_FILENOTFOUND | Unable to find configuration file.
0x80040c03 | SCHEMA_E_NESTEDTAG | The tag nesting configuration is not valid.
0x80040c04 | SCHEMA_E_UNEXPECTEDTAG | The configuration file contains an unexpected tag.
0x80040c05 | SCHEMA_E_VERSIONMISMATCH | The configuration file version number is invalid.
0x80040c06 | SCHEMA_E_CANNOTCREATEFILE | Unable to create output configuration file.
0x80040c07 | SCHEMA_E_CANNOTWRITEFILE | Unable to write to output configuration file.
0x80040c08 | SCHEMA_E_EMPTYFILE | The configuration file contains invalid information.
0x80040c09 | SCHEMA_E_INVALIDFILETYPE | The configuration file type is not recognized.
0x80040c0a | SCHEMA_E_INVALIDDATATYPE | The configuration file column data type is not recognized.
0x80040c0b | SCHEMA_E_CANNOTCREATENOISEWORDFILE | Unable to create noise word file.
0x80040c0c | SCHEMA_E_ADDSTOPWORDS | There was an error writing to the temporary noise word file.
0x80040c0d | SCHEMA_E_NAMEEXISTS | The specified column name already exists.
0x80040c0e | SCHEMA_E_INVALIDVALUE | The attributes value is invalid.
0x80040c0f | SCHEMA_E_BADPROPSPEC | The property set GUID is invalid.
0x80040c10 | SCHEMA_E_NOMORECOLUMNS | (no more columns)
0x80040c11 | SCHEMA_E_FILECHANGED | Unable to write to the configuration file because it was modified since last read.
0x80040c12 | SCHEMA_E_BADCOLUMNNAME | The specified column name is invalid.
0x80040c13 | SCHEMA_E_BADPROPPID | The property ID specified is invalid.
0x80040c14 | SCHEMA_E_BADATTRIBUTE | An invalid attribute has been specified for this tag or a required attribute is missing.
0x80040c15 | SCHEMA_E_BADFILENAME | The specified filename is invalid.
0x80040c16 | SCHEMA_E_PROPEXISTS | A column having the specified property set and PID already exists.
0x80040c17 | SCHEMA_E_DUPLICATENOISE | A noise word file for this language and sublanguage already exists.


Gatherer Service Related Values

These values all have the bits 0x0d00 in common.

HRESULT Value (Hex) | Status Code Name | Description
0x80040d01 | GTHR_E_INTERNAL | Internal indexing error.
0x80040d02 | GTHR_E_DUPLICATE_OBJECT | Unable to complete operation. Object already exists.
0x80040d03 | GTHR_E_UNABLE_TO_READ_REGISTRY | Error reading registry value.
0x80040d04 | GTHR_E_ERROR_WRITING_REGISTRY | Unable to set value, the object is already deleted or not initialized properly.
0x80040d05 | GTHR_E_ERROR_INITIALIZING_PERFMON | Unable to initialize performance monitoring.
0x80040d06 | GTHR_E_ERROR_OBJECT_NOT_FOUND | Unable to find the specified object.
0x80040d07 | GTHR_E_URL_EXCLUDED | The specified URL is excluded and will not be cataloged.
0x80040d08 | GTHR_E_CONFIG_DUP_CRAWL_ENTRY | Duplicate crawl entry in registry.
0x80040d09 | GTHR_E_CONFIG_DUP_NNTP_SERVER | Duplicate NNTP server entry in registry.
0x80040d0a | GTHR_E_CONFIG_DUP_PROJECT | Duplicate project entry in registry.
0x80040d0b | GTHR_E_CONFIG_DUP_EXTENSION | Duplicate extension entry in registry.
0x80040d0c | GTHR_E_CRAWL_TOO_DEEP | The Gatherer attempted to follow a link deeper than the configured restrictions.
0x80040d0d | GTHR_E_DUPLICATE_URL | URL has already been processed during this crawl.
0x80040d0e | GTHR_E_TOO_MANY_PLUGINS | The Gatherer attempted to create more Gatherer plug-in objects than allowed.
0x80040d0f | GTHR_E_INVALIDFUNCTION | Unable to call function in this context or the function is not implemented.
0x80040d10 | GTHR_E_NOFILTERSINK | The plug-in has not provided a filter sink object.
0x80040d11 | GTHR_E_FILTER_PROCESS_TERMINATED | The filtering process is unavailable because it has terminated.
0x80040d12 | GTHR_E_FILTER_INVALID_MESSAGE | An unexpected message has been received from the filtering process.
0x80040d13 | GTHR_E_UNSUPPORTED_PROPERTY_TYPE | The filtering process has returned an unsupported property type.
0x80040d14 | GTHR_E_NAME_TOO_LONG | The length of the name specified has exceeded allowed limits.
0x80040d15 | GTHR_E_NO_IDENTITY | User agent or e-mail address has not been specified.
0x80040d16 | GTHR_E_FILTER_NOT_FOUND | Unable to create a filter for the document.
0x80040d17 | GTHR_E_FILTER_NO_MORE_THREADS | All threads in the filtering process are currently in use.
0x80040d18 | GTHR_E_PRT_HNDLR_PROGID_MISSING | Unable to obtain the progid for a protocol handler.
0x80040d19 | GTHR_E_NO_LOGICAL_PATH | There is no logical path for the document.
0x80040d1a | GTHR_E_UNKNOWN_PROTOCOL | Unable to find protocol handler. Possibly caused by no handler being installed or corrupt handler.
0x80040d1b | GTHR_E_PROJECT_NOT_INITIALIZED | Gatherer project has not been initialized.
0x00040d1c | GTHR_S_STATUS_CHANGE_IGNORED | Status change request has been ignored. The same status change is already pending.
0x00040d1d | GTHR_S_STATUS_END_CRAWL | End Of Crawl.
0x00040d1e | GTHR_S_STATUS_RESET | Reset
0x00040d1f | GTHR_S_STATUS_THROTTLE | Throttle
0x00040d20 | GTHR_S_STATUS_RESUME | Resume
0x00040d21 | GTHR_S_STATUS_PAUSE | Pause
0x80040d22 | GTHR_E_INVALID_PROJECT_NAME | Project name is invalid.
0x80040d23 | GTHR_E_SHUTTING_DOWN | Shutdown in progress.
0x00040d24 | GTHR_S_END_STD_CHUNKS | The Gatherer is done filtering standard properties.
0x80040d25 | GTHR_E_VALUE_NOT_AVAILABLE | The requested value has not been set by the filter process.
0x80040d26 | GTHR_E_OUT_OF_DOC_ID | All valid document IDs have been used.
0x80040d27 | GTHR_E_NOTIFICATION_PROJECT | Unable to start crawling on a project set up for notifications.
0x80040d28 | GTHR_E_CRAWL_PROJECT | Unable to accept notifications on a project set up for crawling.
0x80040d29 | GTHR_E_CONFIG_DUP_NOTIFICATION_SOURCE | Duplicate notification source mapping in registry.
0x80040d2a | GTHR_E_DUP_PROPERTY_MAPPING | Duplicate property mapping in schema.
0x80040d2b | GTHR_E_NO_CRAWL_SEEDS | Unable to start the crawl without start addresses.
0x80040d2c | GTHR_E_INVALID_ACCOUNT | The specified Account Information is invalid or the account name can not be used because it contains invalid characters [""].
0x80040d2d | GTHR_E_FILTER_MISMATCH | Unable to filter the document, possibly caused by document type and extension mismatch.
0x80040d2e | GTHR_E_FILTER_INIT | Unable to filter the document, possibly caused by document and filter version mismatch.
0x80040d2f | GTHR_E_FILTER_LOAD | Unable to load the document info filter.
0x00040d30 | GTHR_S_CANNOT_FILTER | No filter available or filter failed.
0x80040d31 | GTHR_E_PROXY_NAME | The proxy server name is missing.
0x80040d32 | GTHR_E_SERVER_UNAVAILABLE | The server has been marked as unavailable.
0x00040d33 | GTHR_S_STATUS_STOP | Stop
0x80040d34 | GTHR_E_INVALID_PATH | This path does not correspond to the selected site.
0x80040d35 | GTHR_E_FILTER_NO_CODEPAGE | Unable to filter document. The required code page is not installed.
0x00040d36 | GTHR_S_STATUS_START | Start Crawl
0x80040d37 | GTHR_E_NO_PRTCLHNLR | No protocol handler available, possibly caused by bad protocol handler.
0x80040d38 | GTHR_E_IE_OFFLINE | Internet Explorer is set to offline mode.
0x80040d39 | GTHR_E_BAD_FILTER_DAEMON | Unable to start the filter process.
0x80040d40 | GTHR_E_INVALID_MAPPING | The specified URL mapping is invalid.
0x80040d41 | GTHR_E_USER_AGENT_NOT_SPECIFIED | The user agent string has not been specified or contains invalid characters [""].
0x80040d42 | GTHR_E_NOTIFICATION_SOURCE_NOT_SPECIFIED | The notification source name has not been specified.
0x80040d43 | GTHR_E_FROM_NOT_SPECIFIED | The e-mail address is missing. Please enter an e-mail address.
0x80040d44 | GTHR_E_INVALID_STREAM_LOGS_COUNT | The specified number of logs to keep is invalid (it has to be greater than 0).
0x80040d45 | GTHR_E_INVALID_EXTENSION | The extension string is not specified or is invalid (can not contain [./?*:\\#] or white spaces).
0x80040d46 | GTHR_E_INVALID_GROW_FACTOR | The specified max grow factor is invalid (can not be less than 0).
0x80040d47 | GTHR_E_INVALID_TIME_OUT | The specified time out value is invalid (can not be less than 0).
0x80040d48 | GTHR_E_INVALID_RETRIES | The specified retry limit value is invalid (can not be less than 0).
0x80040d49 | GTHR_E_INVALID_LOG_FILE_NAME | The gatherer log file name is not specified.
0x80040d50 | GTHR_E_INVALID_HOST_NAME | The site name is not specified or is invalid (can not have [/\\@#|] or white spaces).
0x80040d51 | GTHR_E_INVALID_START_PAGE | The start page is not specified or is invalid (the host name can not contain * or white spaces).
0x80040d52 | GTHR_E_DUPLICATE_PROJECT | A project with the name specified already exists.
0x80040d53 | GTHR_E_INVALID_DIRECTORY | The path is not specified or contains invalid characters ["" ?*].
0x80040d54 | GTHR_E_FILTER_INTERRUPTED | The filtering has been aborted.
0x80040d55 | GTHR_E_INVALID_PROXY_PORT | The specified port for http proxy is invalid.
0x00040d56 | GTHR_S_CONFIG_HAS_ACCOUNTS | Project configuration contains account information.
0x80040d57 | GTHR_E_SECRET_NOT_FOUND | The account password was not specified.
0x80040d58 | GTHR_E_INVALID_PATH_EXPRESSION | The path expression can not contain wildcard characters in the directory specification and '|' - a reserved escape character.
0x80040d59 | GTHR_E_INVALID_START_PAGE_HOST | The start page specification is missing the host name.
0x80040d60 | GTHR_E_INVALID_START_PAGE_PATH | The start page path specification can not contain wildcard characters [?*].


Protocol Handler Related Values

These values all have the bits 0x1200 in common.

HRESULT Value (Hex) | Status Code Name | Description
0x80041200 | PRTH_E_COMM_ERROR | Communication error
0x80041201 | PRTH_E_OBJ_NOT_FOUND | Object not found
0x80041202 | PRTH_E_REQUEST_ERROR | Unable to complete request. Options are ambiguous or unsupported.
0x00041203 | PRTH_S_NOT_MODIFIED | Content has not changed.
0x80041204 | PRTH_E_INTERNAL_ERROR | Internal Error
0x80041205 | PRTH_E_ACCESS_DENIED | Access denied
0x80041206 | PRTH_E_SERVER_ERROR | Server internal error.
0x80041207 | PRTH_E_NOT_REDIRECTED | Redirected URL does not exist.
0x80041208 | PRTH_E_BAD_REQUEST | Bad request, possibly caused by bad URL.
0x00041209 | PRTH_S_MAX_GROWTH | This file has reached the maximum filter output limit. Filtering of this file has been aborted.
0x8004120a | PRTH_E_WININET | Exception caught in WinInet.
0x8004120b | PRTH_E_RETRY | Accessor requests retry.
0x8004120c | PRTH_E_MAX_DOWNLOAD | This file has reached the maximum download limit.
0x8004120d | PRTH_E_MIME_EXCLUDED | URL is excluded because content type is not supported.


Indexer Related Values

These values all have the bits 0x1100 in common.

HRESULT Value (Hex) | Status Code Name | Description
0x80041101 | IDX_E_INVALIDTAG | The tag is invalid.
0x80041102 | IDX_E_METAFILE_CORRUPT | The propagation configuration file is corrupt.
0x80041103 | IDX_E_TOO_MANY_SEARCH_SERVERS | The number of Search servers exceeded the limit.
0x80041104 | IDX_E_SEARCH_SERVER_ALREADY_EXISTS | The specified Search server already exists.
0x80041105 | IDX_E_BUILD_IN_PROGRESS | A catalog build is already in progress.
0x80041106 | IDX_IDX_E_IDXLSTFILE_CORRUPT | Index list file is corrupt.
0x80041107 | IDX_E_REGISTRY_ENTRY | Error reading or writing a registry entry required for catalog creation.
0x80041108 | IDX_E_OBJECT_NOT_FOUND | File or files required for catalog creation were not found.
0x80041109 | IDX_E_SEARCH_SERVER_NOT_FOUND | The Search server was not found.
0x8004110a | IDX_E_WB_NOTFOUND | Word-breaker not found for the given language.
0x8004110b | IDX_E_NOISELIST_NOTFOUND | Noise word list was not found for the given language.
0x8004110c | IDX_E_STEMMER_NOTFOUND | A stemmer was not found for the given language.
0x8004110d | IDX_E_PROP_STOPPED | Catalog propagation was stopped.
0x8004110e | IDX_E_DISKFULL | Disk is full.
0x8004110f | IDX_E_INVALID_INDEX | Index data is invalid.
0x80041110 | IDX_E_CORRUPT_INDEX | Index data is corrupt.
0x80041111 | IDX_E_NO_BACKUP | There is no backup catalog.
0x80041112 | IDX_E_PROPSTORE_INIT_FAILED | Property store initialization failed.
0x80041113 | IDX_E_PROP_STATE_CORRUPT | Propagation state information is corrupt.
0x00041114 | IDX_S_NO_BUILD_IN_PROGRESS | There is no build in progress.
0x00041115 | IDX_S_SEARCH_SERVER_ALREADY_EXISTS | The Search server already exists.
0x00041116 | IDX_S_SEARCH_SERVER_DOES_NOT_EXIST | The Search server does not exist.
0x80041117 | IDX_E_NOT_LOADED | The catalog is not loaded.
0x80041118 | IDX_E_PROP_MAJOR_VERSION_MISMATCH | There is a mismatch in the major version number.
0x80041119 | IDX_E_PROP_MINOR_VERSION_MISMATCH | Index is a mismatch in the minor version number.
0x8004111a | IDX_E_DSS_NOT_CONNECTED | A connection with the DSS could not be established.
0x8004111b | IDX_E_DOCUMENT_ABORTED | Document indexing has been aborted.
0x8004111c | IDX_E_CATALOG_DISMOUNTED | The catalog has been dismounted.
0x0004111d | IDX_S_DSS_NOT_AVAILABLE | Search Server was added successfully but could not be contacted.


Indexer (Exchange) Related Values

These values all have the bits 0x1100 in common.

HRESULT Value (Hex) | Status Code Name | Description
0x800411a0 | EXCI_E_NO_CONFIG | The configuration properties for Microsoft Exchange have not been set. Specify these properties, and then try again.
0x800411a1 | EXCI_E_INVALID_SERVER_CONFIG | The name of the Exchange Server specified in the start address does not match the Exchange Server specified in the Microsoft Exchange configuration properties. Change the name of the Exchange Server in the start address or configuration properties to match the other, and then try again.
0x800411a2 | EXCI_E_ACCESS_DENIED | Insufficient privilege to access Exchange server. Verify that the Exchange indexing configuration is valid and that the Search Service is running in the context of a user having administrative privileges on the Exchange server configuration node.
0x800411a3 | EXCI_E_INVALID_EXCHANGE_SERVER | The Exchange server name specified in the URL does not match the one specified in Exchange Indexing configuration.
0x800411a4 | EXCI_E_BADCONFIG_OR_ACCESSDENIED | Insufficient privilege to access Exchange server. Verify that the Exchange indexing configuration is valid and that the Search Service is running in the context of a user having administrative privileges on the Exchange server configuration node.
0x800411a5 | EXCI_E_WRONG_SERVER_OR_ACCT | The service cannot access the Exchange server. The configured Exchange server name may be invalid, the Exchange server may be temporarily unavailable, or the account used by the Search services may not have administrative access to the Exchange server.
0x800411a6 | EXCI_E_NOT_ADMIN_OR_WRONG_SITE | The service cannot access the Exchange Service. The account used by the Search services may not be an Exchange administrator, or the Site or Organization settings on the Search host may be invalid.


Setup Related Values

These values all have the bits 0x1300 in common.

HRESULT Value (Hex) | Status Code Name | Description
0x80041301 | SETUP_E_EXCEPTION | An unhandled exception occurred.
0x00041302 | SETUP_S_SERVICEUSERINFO | The user information for the service could not be set.


Command-Line Tool Related Values

These values all have the bits 0x1500 in common.

HRESULT Value (Hex) | Status Code Name | Description
0x80041501 | CMDLINE_E_UNEXPECTED | An unexpected error occurred.
0x80041502 | CMDLINE_E_PAREN | There is an unmatched parentheses on the command line.
0x80041503 | CMDLINE_E_PARAM_SIZE | There parameter is too long.
0x80041504 | CMDLINE_E_NOT_INIT | Object is not initialized. Must call Init() first.
0x80041505 | CMDLINE_E_ALREADY_INIT | Object is already initialized.
0x80041506 | CMDLINE_E_NUM_PARAMS | There are too many parameters.


Admin Related Values

These values all have the bits 0x1900 in common.

HRESULT Value (Hex) | Status Code Name | Description
0x80041901 | NLADMIN_E_DUPLICATE_CATALOG | A catalog with the name specified already exists.
0x00041902 | NLADMIN_S_NOT_ALL_BUILD_CATALOGS_INITIALIZED | At least one catalog definition failed to initialize. This may be due to insufficient disk space or invalid registry configuration.
0x80041903 | NLADMIN_E_FAILED_TO_GIVE_ACCOUNT_PRIVILEGE | The account could not be granted a privilege to log on as service on the domain controller.


Examples of Use

C++

The following C++ example demonstrates typical use of the Search custom failure HRESULT values. Note the use of the "bit mask" in the failure check. Checking the HRESULT for the FACILITY_ITF notifies the calling application that the interface has prepared the ErrorInfo object itself to communicate the exception. In most cases, this implies that some logic or operation related directly to the object has failed in some fashion. (e.g. not initializing the object or failure to pass necessary info before invoking a particular method, etc) This is in contrast to standard Win32 or COM HRESULT values such as E_FAIL or E_UNEXPECTED, which convey little information about the exception source.

If simply displaying the source and description of the error to a user in say an interactive setting is desired, the bit mask check can be removed, and the information retrieved for the exception, regardless of the source. The code below is very routine.

HRESULT hR = pISearchObject->SomeMethod( … );
if (FAILED(hR)) {
   ISupportErrorInfo *psei = 0;
   HRESULT hR2 = pISearchObject->QueryInterface( IID_ISupportErrorInfo,
                                                (void**)&psei );
   if( SUCCEEDED(hR2)) {
      hR2 = psei->InterfaceSupportsErrorInfo(IID_ISearchInterface);
      if ( hR2 == S_OK ) {
         IErrorInfo *pei = 0;
         hR2 = GetErrorInfo(0, &pei);
         if ( hR2 == S_OK ) {
            BSTR Source = 0;
            BSTR Description = 0;
            hR2 = pei->GetSource(&Source);
            assert(SUCCEEDED(hR2));
            hR2 = pei->GetDescription(&Description);
            assert(SUCCEEDED(hR2));

            /*  deal with this info, such as MessageBoxW, etc.. */
            SysFreeString(&Source);
            SysFreeString(&Description);
         }
      }
      psei-Release();
   }
   /*  try FormatMessage or something as the error was
        not designated as interface specific */
   void* pMsgBuf;
   ::FormatMessage(..,..,hR,..,(LPTSTR)pMsgBuf,0,NULL);
}

VB/VBScript

In Visual Basic or Visual Basic, Scripting Edition, the Err object is automatically populated with the COM exception information when a COM method invocation returns a failed HRESULT value. The code is very similar to the C++ code listed above:

Dim MyObject as ISearchAdmin
Set ISearchInterfaces = new SearchAdmin
…
On Error Resume Next
Set SearchServer = ISearchAdmin.SearchServer
… ' code omitted for brevity

If Err.Number <> 0 and  ( (Err.Number And Hex(0x7fff0000)) = Hex(0x00040000) )
   ' take some appropriate action
   '  in this case, we simply display the error info
   Debug.Print Err.Source
   Debug.Pring Err.Description
End If


Ad Server Programmer's Guide

Ad Server Programmer’s Guide

The following components of Ad Server work together to deliver ads to Web pages:

Ad Manager. Active Server Pages (ASP)-based application used to add and update customer and ad information and to track the progress of ads against delivery goals.

AdServer Object. COM (Component Object Model) object residing on the Web content server and called by ASP files to insert ads into Web pages. The AdServer object reads and evaluates information from the database to determine the best ad for insertion into the Web page. It also logs transaction data to the Microsoft® Internet Information Server (IIS) log, which is used for reporting.

This SDK documentation describes how to program the AdServer object using VBScript.

Database. SQL database that stores ads and ad information entered through Ad Manager and accessed by the Ad Server Component.


AdServer Object Overview

The AdServer object is usually created in the Application_OnStart function defined in the Global.asa file. Use the Active Server Pages (ASP) Server object’s CreateObject method to create an AdServer object. In addition, properties of this object can be set in Global.asa:

'  Create the AdServer object
Set  Ad = Server.CreateObject("Commerce.AdServer")

Ad.ConnectionString = “DSN=adsamples;UID=sa;PWD=;”

'  Set AdServer properties
Ad.DefaultAd = "<B><FONT SIZE=+4 COLOR=BLUE><MARQUEE WIDTH=400>This is the default ad</MARQUEE></FONT></B>"
Ad.RefreshInterval = 900
Ad.RetryInterval = 60
Ad.RedirectURL = "/adsamples/adredir.asp"
Ad.DesignMode = False
Ad.Application = "clocktower"

Also in Global.asa, store the new object in the Application object, as follows:

Set Application("Ad")  = Ad

Because the AdServer object is marked "both" under threading model, it has been designed to be "thread safe" and can be given application scope and used by ASP pages at any time without fear of data loss or collision.


Ad Server Programmer's Reference

Ad Server Programmer’s Reference

The AdServer object manages the delivery of advertisements to dynamically built web pages. The AdServer object serves as a link between script in an ASP page and the advertisement delivery database and Internet Information Server log file, handling all advertisement delivery, database updates, and event recording.

The AdServer object supports the following properties

Property | Description
Application | A name used to distinguish separate instances of the AdServer object in error messages in the NT Event Viewer.
ConnectionString | The connection string to be used when the AdServer object connects and authenticates itself to the AdServer database.
DefaultAd | The HTML text sent as the default when no appropriate advertisement can be determined
DesignMode | A Boolean Variant. If True, the AdServer object returns an error message when the GetAd method cannot determine an appropriate advertisement to return. If false, the method displays the default ad in this case.
RedirectURL | The URL of the redirecting ASP file, which logs the click event and redirects the user’s browser to the destination page.
RefreshInterval | The number of seconds that the AdServer object waits before connecting to the database to post its delivered advertisements and receive updated delivery schedule information.
RetryInterval | Specifies the number of seconds that the AdServer object waits between attempts to reconnect with the ad database if the connection fails.

The AdServer object supports the following methods.

Method | Description
DumpSchedule | Returns a table, in HTML format, of the current advertisement delivery schedule of the local instance of the AdServer object.
GetAd | Selects the most appropriate advertisement and returns HTML text that can be inserted into the calling page.
RecordEvent | Logs both ad requests and clicks to the Internet Information Server's log.
RefreshSchedule | Connects the AdServer object to the database immediately, and receives updated delivery information.


AdServer Properties

© 1997-1998 Microsoft Corporation. All rights reserved.


Application Property

The Application property is a string Variant that is used to distinguish separate instances of the AdServer object in error messages in the NT Event Viewer.

Syntax

AdServerObject.Application

Remarks

It is recommended that the Application property be set to the name of the application's virtual directory so that the virtual directory name will be included in all errors, making them easier to track down.

Example

The following line in Clocktower's Global.asa file would set the Application property of the AdServer object for the Clocktower application.

Ad.Application = "Clocktower"

After this line has been run, any error generated from this instance of the AdServer object will include " Clocktower " as part of the error message in the log.


ConnectionString Property

The ConnectionString property is a string Variant that specifies the connection string to be used when the AdServer object connects and authenticates itself to the AdServer database.

Syntax

AdServerObject.ConnectionString

Remarks

A connection string is a text string describing properties of a database connection as a series of argument = value statements separated by semicolons. The connection string usually includes all the information needed to make a connection, including user name and password.

Example

Ad.ConnectionString = "DSN=adsamples;UID=SA;PWD=;"


DefaultAd Property

The DefaultAd property is a string Variant that contains the HTML text to be returned by the GetAd method if the AdServer object cannot determine an appropriate advertisement.

Syntax

AdServerObject.DefaultAd

Remarks

If the DesignMode property is set to True, then in the situation in which the GetAd method cannot determine an appropriate advertisement, the method will return an appropriate error message to the developer instead of displaying the default ad.

Example

Ad.DefaultAd = "<B><FONT SIZE=+4 COLOR=BLUE><MARQUEE WIDTH=400>This is the default ad</MARQUEE></FONT></B>"

See Also

DesignMode, GetAd


DesignMode Property

The DesignMode property is a Boolean Variant that determines whether the AdServer object returns the default ad or an error message when the GetAd method cannot determine an appropriate advertisement to return.

Syntax

AdServerObject.DesignMode

Remarks

By default, this property is set to False, so that if an error occurs in serving an ad, the site visitor will see your default ad. However, for designing and troubleshooting your site, you can set this property to True so that you will see information about the error on the page rather than the default ad or a blank ad.

Note

Errors are always logged to the NT Event Viewer, whether DesignMode is used or not.

Example

The following line enables design mode.

  Ad.DesignMode = TRUE

See Also

DefaultAd, GetAd


RedirectURL Property

The RedirectURL property is a string Variant that specifies the URL of the redirecting ASP file, which logs the click event and redirects the user’s browser to the destination page.

Syntax

AdServerObject.RedirectURL

Remarks

This property does not specify the ultimate destination of the click-through, but rather an intermediary ASP file that logs the click and then redirects the visitor’s browser to the advertiser’s page.

If this property is not set explicitly, the default redirect page is "/adredir.asp".

The property must contain a URL which is correct on any page, regardless of where that page resides in the Application directory tree. For example, the following strings should not be used.

"adredir.asp
"../adredir.asp"

Instead, use a fully-qualified path, such as one of the following:

"/adredir.asp"
"http://www.yourcompany.com/adredir.asp"

Also, the destination page must be able connect to the AdServer object via the Application object.

Example

The following line might be used in Global.asa, after the AdServer object is created, so that ads will use a redirect page other than the default.

Ad.RedirectURL = "http://www.microsoft.com/adsamples/adredir.asp"


RefreshInterval Property

The RefreshInterval property is a Long Variant that specifies the number of seconds that the AdServer object waits before connecting to the database to post its delivered advertisements and receive updated delivery schedule information.

Syntax

AdServerObject.RefreshInterval

Remarks

AdServer periodically updates the database with current information about the number of ad requests or clicks that have been served and retrieves current ad information from the database. The RefreshInterval of the AdServer object represents the number of seconds between these updates.

You can set the refresh interval to any number between 60 and 86400 (which translates to one day). The default interval is 900 seconds.

Note

While database information is being refreshed, AdServer does not log ad requests or clicks. Short refresh intervals raise the probability any given ad request or click won’t be logged. On the other hand, long refresh intervals prevent ad delivery schedules from being adjusted to reflect current ad delivery status. Therefore, a refresh interval between 300 and 900 seconds is recommended.

Example

The following line, added to Global.asa, sets the refresh interval to 5 minutes.

Ad.RefreshInterval = 300

See Also

RefreshSchedule


RetryInterval Property

The RetryInterval property is a Long Variant that specifies the number of seconds that the AdServer object waits between attempts to reconnect with the ad database if the connection fails.

Syntax

AdServerObject.RetryInterval

Remarks

The default value is 60 seconds. You can set the retry interval to any number between 0 and 3600 (which translates to one hour). This value is usually set in Global.asa.

Example

The following line sets the retry interval to 2 minutes.

  Ad.RetryInterval = 120


AdServer Methods

© 1997-1998 Microsoft Corporation. All rights reserved.


DumpSchedule Method

The DumpSchedule method returns a table, in HTML format, of the current advertisement delivery schedule of the local instance of the AdServer object.

Syntax

AdServerObject.DumpSchedule( )

Parameters

None.

Remarks

The DumpSchedule method is used primarily as a tool for content developers and managers. It shows the current AdServer object's scheduling information at the time the call was made.

Example

Set Ad = Application("Ad")
Ad.DumpSchedule()


GetAd Method

The GetAd method selects the most appropriate advertisement and returns HTML text that can be inserted into the calling page.

Syntax

AdServerObject.GetAd([Response], [TagList], [History])

Parameters

Response

Optional. The ASP-intrinsic Response object, required for logging ad impression events to the IIS log file. The log file is later used by Usage Analyst. If this argument is omitted, the method does not log the ad impression event to the log file.

TagList

Optional. An array of text strings that specify the types of ads to be served and the way in which the ads are displayed on the page.

History

Optional. A string Variant that contains the user's advertisement viewing history. The string is a comma-separated list of the campaign item ids (ciids) of the ads that have already been selected for the current user. The string is usually persisted only for the duration of a user session.

Examples

The following example requests an ad from AdServer and enables it to record events for the returned ad to the IIS log file.

<% =Ad.GetAd(Response) %>

The following example creates a tag list, then passes this list to the GetAd method to specify a preference for ads targeted at people interested in sports and living in the Northwest region.

<% Set Ad = Application("Ad") %>
<% Taglist = Array("PageGroup.Sports", "Region.Northwest") %>
<% =Ad.GetAd (Response, TagList ) %>

The following example retrieves the visitor’s history string from the Session object, and makes a request for an ad that takes into consideration the visitor’s history. The AdServer uses the history string to exclude overexposed ads, delivers an ad, and appends the newly delivered ad to the history string. The last line of the script then resets the history to include the latest ad.

  <% Dim HistoryString %>
  <% HistoryString = Session("HistoryString") %>
  <% = Ad.GetAd(Response, Null, HistoryString) %>
  <% Session("HistoryString") = HistoryString %>

Remarks

In order for the GetAd method to log the impression event, you must set the logging properties for the Web site to enable URI Query.

If the ad being served can be clicked (that is, if the campaign item was specified as type IMG or BUYNOW in the Ad Manager), this method creates an HREF tag that includes the value of the RedirectURL property. For example, AdServer creates the following HREF tag for a clickable Trey Research ad on the Ad Samples default.asp page. The URL of the click-through page, in this case /adsamples/Trey.asp, which is passed as a parameter to the Adredir.asp page is set on the Campaign Item page in the Ad Manager.

<A HREF="/adsamples/adredir.asp?ciid=4&url=/adsamples/Trey.asp" TARGET=_top>

If the GetAd method cannot determine an appropriate ad, it returns the ad specified by the DefaultAd property. In this case, the RedirectURL property is not used.

See Also

RedirectURL, DefaultAd, Taglist Argument


The TagList Argument

The second argument to the GetAd method, TagList, provides a number of capabilities. You can use a list of tags to target advertisements by communicating properties about the user, the current page, or the current HTTP request.

The simplest way to pass tags in from the page is to use the following syntax:

  <% TagList=Array("ad.size.Banner","ad.targetframe._new","Money") %>
  <% =Ad.GetAd(Response, TagList, HistoryString) %>

This code will most likely result in the Trey Research ad being selected, since that ad is targeted to the Money tag. However, if another ad falls behind schedule, it may be selected instead.

The AddTag.inc file in the AdSamples directory defines the AddTag subroutine. This subroutine makes it easy to construct an array of tags programmatically, which is useful when you want to target properties that are not known at the time the page is authored. Examples are targeting user attributes from Site Server Membership or attributes of the request, such as the browser type and platform.

By using the Taglist argument, you can:

  • target ads

  • specify ad size

  • control how an ad displays


Using the TagList to Target Ads

The GetAd method compares the tags in the TagList to the target tags associated with the campaign items. Campaign item tags may be categorized in the Ad Manager as Target tags, Exclude tags, or Required tags.

  • Target. The ad’s selection weight increases when target tag matches.

  • Required. The ad is selected only if this target tag matches.

  • Exclude. The ad is not selected when this target tag matches.

The comparison is case-insensitive, but spaces and other non-alphanumeric characters in either string are significant. For example, the tag “PageGroup.Sports” matches “pagegroup.sports,” however the tag “MyHomePage” does not match “My Home Page.”

The AdSamples directory includes a file called Tags.asp which demonstrates how tags can be used to specify ad-selection criteria, including selections based on the visitor’s browser type.


Using the TagList to Specify Ad Size

Reserved tags have special meaning to the AdServer object. These are tags prefixed by ad. (ad-dot), and specify what size the ad is, what frame it should appear in, and how wide the ad border should be. You should not create new tags with the ad-dot prefix.

The Ad.Size.Tag reserved tag specifies what size of ad is eligible to be selected for this ad request. This tag is treated as a Required tag; that is, if you pass ad.size tag in an ad request, AdServer will only consider ads of that size for delivery. If Tag does not match one of the creative size tags as specified in Ad Manager, no ad is selected.

The following table shows the ads sizes and corresponding tags that are supported by default. Using Ad Manager, you can add or delete entries in this list as desired, as long as the Tag is specified correctly in the TagList.

Tag | Description | Width | Height
Banner | Full Banner | 468 | 60
NavBanner | Full Banner with Navigation Bar | 392 | 72
Half | Half Banner | 234 | 60
Square | Square Button | 125 | 125
Button1 | Button #1 | 120 | 90
Button2 | Button #2 | 120 | 60
Micro | Micro Button | 88 | 31
Vertical | Vertical Banner | 120 | 240

For example, if you put the tag “Ad.Size.Banner” in the TagList array and call the GetAd method, then the method will return only an ad that is 468 x 60 pixels.


Using the TagList to Control How an Ad Displays

Two other reserved tags control how the ad is displayed in the browser.

The Ad.TargetFrame.frame reserved tag specifies the frame or window to be the target of ad clicks. If this tag is not specified, GetAd uses the default value _top, so that if the visitor clicks on the ad, the resulting page appears in main browser window. The options for this tag are described in the following table.

Tag | Where click-through page displays
Ad.TargetFrame._top | main browser window
Ad.TargetFrame._self | same frame in which the ad itself was displayed
Ad.TargetFrame._parent | immediate parent frame of the frame containing the ad
Ad.TargetFrame.frame | frame named “frame”

The Ad.Border.n tag specifies the border size for the ad. The default border is one (1) pixel wide.

The following example requests a banner-sized ad, and displays it with a border of 2 pixels.

<% Dim TagList %>
<% TagList = Array("ad.size.Banner","ad.border.2") %>
<% =Ad.GetAd(null, Taglist, null) %>


RecordEvent Method

The RecordEvent method logs both ad requests and clicks to the Internet Information Server's log.

Syntax

AdServerObject.RecordEvent ([Response], [CampaignItemID], EventType)

Parameters

Response

Optional. The ASP built-in Response object, used to log ad events to the IIS log file.

CampaignItemID

Optional. A long Variant specifying the number of the campaign item being logged.

EventType

A string Variant containing either "IMPR" (for impressions) or "CLIK" (for click events).

Remarks

Usually you will not need to use this method directly. The method is used in the AdRedir.asp page. In this page, the CampaignItemID is provided in the string returned by the GetAd method for ads that can be clicked.

Impression events are logged automatically by the GetAd method, so that “IMPR” never needs to be passed in directly as an EventType argument.

In order for the RecordEvent method to log the click event, you must set the logging properties for the Web site to enable URI Query.

Example

The following example shows the entire AdRedir.asp file. When the visitor clicks an ad, the visitor’s browser is redirected to this script. This script logs the click event into the IIS log using the RecordEvent method before redirecting the visitor’s browser to the click-through page for the ad using the Redirect method of the Response object.

The ciid argument is the campaign item identifier, returned by the GetAd method in creating the URL and query string passed to this page.

<%
 Set Ad = Application("Ad")
 ciid = Request.Querystring("ciid")
 url = Request.Querystring("url")
 evt = Request.Querystring("evt")
 if evt = "" then evt = "CLIK"
 call Ad.RecordEvent(Response, ciid, evt)
 Response.Redirect(Request.QueryString("url"))
%>

See Also

RedirectURL, GetAd


RefreshSchedule Method

The RefreshShedule method connects to the database immediately, and receives updated delivery information.

Syntax

AdServerObject.RefreshSchedule()

Remarks

This method does not reset the internal timer for the next scheduled "refresh" connection to the database, nor does it redefine the RefreshInterval property.

Example

The following statement causes an immediate refresh of the AdServer object’s schedule:

<%
Application("Ad").RefreshSchedule()
%>

See Also

RefreshInterval


Commerce Server SDK

The Commerce Server version 3.0 SDK (Software Development Kit) contains the tools necessary to develop custom order processing components for the Commerce Server order processing pipeline (OPP), the Commerce Interchange Pipeline (CIP), and client payment components (CPCs) for the Microsoft® Wallet control.

The SDK is included in Commerce Server 3.0 and is installed in the \Microsoft Site Server\SiteServer\Commerce\SDK directory under the Site Server installation directory. The SDK is part of the Commerce Server 3.0 Custom installation.


SDK Contents

The Commerce Server 3.0 SDK includes the following items for creating custom order processing pipeline (OPP) and Commerce Interchange pipeline (CIP) components:

  • Header files
  • Libraries
  • Sample components
  • The Pipeline Component Wizard
  • Documentation

The SDK also includes files, samples, and documentation for creating Microsoft Wallet components.


Documentation

If you are writing order processing components, you should start by reading “The Order Processing Pipeline,” to get a good overview of the order processing pipeline and its components. In addition, the SDK documentation contains the following sections:

  • “Commerce Server SDK” (this document). An introduction to the SDK and its contents.
  • Creating Custom Components. How to write your own OPP or CIP component.
  • Commerce Server Interfaces. A reference section for the C++ COM interfaces and methods that you can use to write a custom component in C++.
  • “MinMaxShip C++ COM Component Sample.” A tutorial that guides you through the creation of a C++ COM order processing component, referencing sample files shipped with Commerce Server.
  • “Buy Now Overview.” How to use the Buy Now control in your store.

Wallet Controls

The following documents in the SDK contain information about building custom Wallet extensions:

  • “Wallet Controls Overview.” An overview of the Microsoft Wallet components.
  • “Scripting the Microsoft Wallet Controls.” Information on how to use the Wallet controls on a Web page.
  • “Payment Selector Interfaces.” Information on how to extend the payment options in the Microsoft Wallet to include branded credit cards and other payment types.
  • “Address Selector Interfaces.” Information on how to extract the values entered by the shopper in the Address Selector control.
  • “Sample Client Payment Component.” How to build a client payment component that plugs into the Wallet.
  • “Sample Other Card Component.” How to build a custom credit card (Other Card) that plugs into the Wallet.
  • “Payment Builder Interface.” Information on interfaces that allow third-party encryption and payment instruction (PI) building methods to plug into the Credit Card client payment component (CPC) in the Wallet.
  • “Webmaster Kit Overview.” An introduction to the Microsoft Wallet Webmaster Kit, which includes tools for embedding the Wallet controls on a Web page.


Samples

The Commerce Server SDK includes the following sample components:

  • DumpOrder.vbs. A sample VBScript component for use with the Scriptor component. Files: \Microsoft Site Server\SiteServer\Commerce\SDK\ Commerce\Samples\DumpOrder.vbs.
  • The MinMaxShip Sample. A sample component for the order processing pipeline, this example is implemented for the ATL, Java, and Visual Basic development environments. Building the Visual Basic version of this sample entails special considerations (see The Visual Basic MinMaxShip Sample).

    The ATL version of the sample resides in \Microsoft Site Server\SiteServer\Commerce\SDK\Commerce\Samples\minmaxship\ATL.

    The Java version of the sample resides in \Microsoft Site Server\SiteServer\Commerce\SDK\Commerce\Samples\minmaxship\Java.

    The Visual Basic version of the sample resides in \Microsoft Site Server\SiteServer\Commerce\SDK\Commerce\Samples\minmaxship\VB.

  • WriteToDB. A demonstration of an order processing pipeline component using ATL. Files: \Microsoft Site Server\SiteServer\Commerce\SDK\ Commerce\Samples\WriteToDb. To build this sample, you must download and install the OLE DB 1.5 software development kit. For information on where to get this SDK, and how to configure your development environment to build this sample, see The WriteToDB Sample.
  • Test. A one-stage pipeline template that can be used for standalone pipeline component testing. This template resides in \Microsoft Site Server\SiteServer\Commerce\SDK\Commerce\Samples\Test\ PipelineTemplates
  • PO850Template.txt. A sample template that can be used with MakePO to generate an ANSI X12 850 message, which is a purchase order (commonly referred to as an 850.) The template file resides in \Microsoft Site Server\SiteServer\Commerce\SDK\Commerce\Samples.
  • CPC. The client payment component sample enables you to write your own payment method that plugs in to the Wallet. Files: \Microsoft Site Server\SiteServer\Commerce\SDK\Commerce\Wallet\Samples\CPCs.
  • OtherCard. The Other Card sample enables you to write your own payment type, so that you can create a new credit-card type that plugs in to the Wallet. Files: \Microsoft Site Server\SiteServer\Commerce\SDK\ Commerce\Wallet\Samples\OtherCards.
  • PaymentBuilder. This sample enables third-party encryption methods to plug into the Wallet’s credit card component. Files: \Microsoft Site Server\SiteServer\Commerce\SDK\Commerce\Wallet\Samples\Payment Builders.

To build the Commerce Server 3.0 order processing pipeline component samples, you should configure your build environment to reference the following header files directory:

\Microsoft Site Server\SiteServer\Commerce\Sdk\Commerce\Include.

Note

The samples included in the Commerce Server SDK were built using Microsoft Development Studio 5.0 on the x86 platform. To build these samples on the Alpha platform, you simply open the projects in Microsoft Development Studio for the Alpha platform. The Development Studio performs the project conversion automatically.


The Visual Basic MinMaxShip Sample

The Visual Basic MinMaxShip sample is included in the \Microsoft Site Server\SiteServer\Commerce\Sdk\Commerce\Samples\minmaxship\vb directory.

This sample is not documented in this release.


Building and Running the Visual Basic MinMaxShip Sample

To load the Visual Basic MinMaxShip sample, you must have installed the Visual Basic Server Pack 2.


Special Considerations for Visual Basic Pipeline Components

The components that are included in Commerce Server 3.0 are free-threaded components. Visual Basic supports the creation of apartment-threaded components, but does not support the creation of free-threaded components.

Consequently, if you use Visual Basic to create components for either of the Commerce Server pipeline architectures, you should keep the following in mind:

If you include the component in a pipeline you load using the OrderPipeline object, and if you make this object globally available, your component will work as expected. This is because the OrderPipeline object checks the threading model of each component at load-time to determine how to marshal that component’s data.

For performance reasons, however, this checking is not performed by the MtsOrderPipeline or MtsTxOrderPipeline objects, objects that are generally created on a per-page basis. For MtsOrderPipeline or MtsTxOrderPipeline objects that you create on a page, this has no bearing on the proper functioning of Visual Basic pipeline components.

However, including such components in an MtsOrderPipeline or MtsTxOrderPipeline object that you make globally available (via the Application object, for example) is unsupported behavior. If you must include a Visual Basic component in a globally available pipeline object instance, you must use the OrderPipeline object to load and execute that pipeline.


The WriteToDB Sample

The WriteToDB component writes specified fields from an OrderForm to a database table.

To build this component, you must first install the OLE DB 1.5 software development kit (SDK). You can download this SDK free from http://www.microsoft.com/data/ado.

After installing the OLE DB SDK, perform the following to configure your development environment.

Set the include paths in the Visual C++ environment must reference the following path: \OLEDBSDK\include.

Set the library paths in the Visual C++ environment must reference the following path: \OLEDBSDK\lib.

To configure include and library paths, click the Options option on the Tools menu in Visual C++, and then, in the Options dialog, click the Directories tab. From this tab, you can add and remove paths from your include file and library settings.

The WriteToDB sample requires the path to the ADO include files in the build environement; otherwise WriteToDB does not build.

In addition, the sample has the following limitations:

  1. The schema of the table should match the number of fields configured and cannot have more than three fields
  2. The sample does not demonstrate the data type conversion, so the data types for the orderform attributes and tables fields must match; otherwise an error is generated.
  3. Error Description is not always present.


Software Requirements

To write components for Commerce Server, in addition to the software required to run Commerce Server you need the following software tools:

  • If you plan to develop components in C or C++: Microsoft Visual C++® version 4.1 or later.
  • If you plan to develop components in Java: A Java compiler such as Microsoft J++© version 1.0 or later.

You can use any compiler that supports VTABLE binding.


The Order Processing Pipeline

The Commerce Server pipeline is a software infrastructure that links one or more components and that runs them in sequence on an OrderForm or Dictionary object. Commerce Server version 3.0 uses this infrastructure to implement two pipeline models: the order processing pipeline (OPP) and the Commerce Interchange Pipeline (CIP).

This guide explains how the OPP works, and how to use the OPP in Commerce Server 3.0 sites. Topics covered include the following:

  • υThe Order Processing Pipeline (OPP) Overview. Provides a detailed overview of the default OPP. The default OPP provides a group of components, which is divided conceptually into stages. These components operate on an OrderForm, an object that stores customer and purchase data. All of these components can be configured within the Commerce Server Win32®-based or Active Server Pages (ASP) Pipeline Editor. In addition, the Commerce Server 3.0 pipeline takes advantage of the capabilities of Microsoft® Transaction Server (MTS).
  • υThe Default Components. Provides a detailed reference for the components that you can use in the default pipeline.


Order Processing Pipeline Basics

Imagine a situation in which a department within a company is charged with processing a large volume of orders daily. To deal with such volume, the company must break the processing of an order into discrete pieces, perhaps assigning one person the task of calculating shipping on an order, another with making sure the items on the order are in inventory, and another with ensuring that the prices on the order reflect the current price of the item.

In order for such an assembly-line approach to order processing to work, some level of coordination is essential among the people charged with order-related tasks. Thus, while breaking order processing into stages to make large-volume processing possible, this hypothetical processing department must also define the rules by which the people or departments charged with various tasks inter-operate.

The order processing pipeline (OPP) approaches work in much the same way as this order processing department. It addresses the need for compartmentalization by breaking the processing of orders into stages, abstractions that describe a category of work, and by determining the sequence in which each category of work is performed. Thus, a typical OPP may include a Shopper Information stage, a Payment stage, and a Shipping stage.

Each stage in a pipeline consists of zero or more components, and each of these components is run in sequence. A component is a Component Object Model (COM) object that is designed to perform some operation on an OrderForm. In many cases, the scope of this operation is quite small. For example, the DefaultShipping component, which is included in the Shipping stage, makes sure that another component has not already calculated the shipping cost on an order. If this cost has already been set on the OrderForm, the DefaultShipping component overwrites the set value with a zero (0) to ensure that the components that follow in the Shipping stage are starting with a reliable value.

The OPP further coordinates the work of components by ensuring that every component in an OPP is reading from and writing to the same purchase order. This purchase order is the OrderForm object. The OrderForm object, which constitutes the link between the Web site and the OPP, is designed to contain all the information necessary to process a purchase over the Web, including shopper, shipping, tax and item price information. In addition, the OrderForm object supports the methods necessary to add new items to itself. After each component in the OPP performs its work on the OrderForm, the OPP passes the OrderForm to the next component in the pipeline.

As the designer of the pipelines for your site, you also take measures to ensure that the OPP functions correctly. First, you should generally make sure that no pipeline component is configured to overwrite the work done by another component. (The required components, such as the DefaultShipping component previously described, are intentional exceptions to this rule.)

Second, define the circumstances under which the OPP will stop processing an OrderForm. As each component in the OPP executes, it returns a status constant that indicates success, a warning, or failure. If you configure a stage to tolerate warnings, the OPP continues to operate despite a warning generated by that component. If you configure a stage to tolerate only success, and the component returns a warning, then the OPP stops processing the OrderForm, and returns an error.


The Order Processing Pipelines

Commerce Server 3.0 includes five basic types of order processing pipelines (OPPs), which are used to implement both business-to-consumer and business-to-business sites.

These pipelines are explained in the following sections:

Business-to-Consumer Pipelines

  • υProduct
  • υPlan
  • υPurchase

Business-to Business Pipelines

  • υCorporate Purchasing Plan
  • υCorporate Purchasing Submit


Business to Consumer Pipelines

The business-to-consumer OPPs are used in Commerce sites designed for retail shopping by the public. These pipelines implement functions that are performed at different times during the customer’s shopping process, as described in the following list:

  • υProduct (Product.pct). Runs OPP components that compute price and discount information on individual products. This pipeline is often used to compute information that is displayed on the Product.asp page.
  • υPlan (Plan.pct). Runs OPP components that present the customer with an order total, including all promotional discounts, taxes, shipping and handling charges.
  • υPurchase (Purchase.pct). Runs OPP components that validate the customer’s payment, perform the actual purchase transaction, write an order to database storage and, optionally, finalize a receipt by writing the contents of the OrderForm to the receipt database..


The Product Pipeline

The Product Pipeline runs OPP components that compute price and discount information on individual products. This pipeline is often used to compute information that is displayed on the Product.asp page.

The template for this pipeline is Product.pct. An example of a pipeline based on this template is the Product.pcf file that is created in the /Config directory of a custom site created by the Site Builder Wizard.

The Product pipeline consists of the following stages.

Product Info Stage

The Product Info stage contains components that retrieve product information about the items in the items list from the site database. If information about a given item cannot be retrieved, Product Info stage components mark the item for deletion by creating a delete name/value pair in the item Dictionary, and initializing the name/value pair to one (1).

After the Product Information components have been executed, the required component in the Product Information stage iterates through the items list, deleting every item that has been marked for deletion.

The components related to this stage are shown in the following table.

Component | Description
QueryProdInfo | Executes a database query, based on the SKUs in the OrderForm's items list, and puts the returned data in the OrderForm’s items collection. If no data is found for the SKU, the item is marked for deletion, and a pur_badsku errir is added to the _Basket_Errors list.
QueryProdInfoADO | Executes a database query, using the Microsoft® ActiveX® Data Objects (ADO). This component differs from QueryProdInfo in that the query that it executes can take multiple parameters, and can reference a query in the QueryMap Dictionary.
RequiredProdInfo (embedded in stage) | If any items are marked for deletion, deletes them and writes appropriate error messages.

Shopper Information Stage

The Shopper Information stage adds information about the customer to the OrderForm.

The components related to this stage are shown in the following table.

Component | Description
DefaultShopperInfoz (included in template) | Initializes entries in the order form to contain the values read from the shopper dictionary.

Item Price Stage

The Item Price stage contains components that set the _iadjust_regularprice for each item in the items list and that verify that this value has been set. If this value cannot be set, an error is raised.

The purpose of this initialization is to ensure that the _iadjust_regularprice name/value pair contains the most current price information for the given SKU.

The components related to this stage are shown in the following table.

Component | Description
DefaultItemPrice (included in template) | For each item in the items list, initializes that item's _iadjust_regularprice name/value pair to the value stored in _product_list_price.
RequiredItemPrice (embedded in stage) | Ensures that _iadjust_regularprice is set for each item in the items list.

Item Adjust Price Stage

The Item Adjust Price stage contains components that initialize the _iadjust_currentprice name/value pair. When this stage is complete, _iadjust_currentprice contains the current price of the item, adjusted for sales or promotions.

If no sale or promotion component is included in this stage, the name/value pair is set to the value stored in _iadjust_regularprice.

Once the item._iadjust_currentprice name/value pair has be set for an item, that item cannot be adjusted a second time. For example, if a stage includes multiple both an ItemPromo and a SaleAdjust component, and an item on the order qualifies for both the promotion and the sale adjustment, the item’s _iadjust_currentprice will be initialized by the component that is executed first within the stage. This generalization applies for any combination of Item Price Adjust components that you include in your pipeline.

The components related to this stage are shown in the following table.

Component | Description
ItemPromo | Adjusts the _iadjust_currentprice name/value pair, based on promotional parameters.
SaleAdjust | Determines whether an item is on sale. If it is, SaleAdjust sets the item’s _iadjust_currentprice name/value pair to the value stored in the _product_sale_price name/value pair.
RequiredItemAdjustPrice (embedded in stage) | Verifies that the _iadjust_currentprice name/value pair is set.

Inventory Stage

This stage verifies that every item ordered is in stock.

The components related to this stage include the following.

Component | Description
FlagInventory | Flags items in the items SimpleList that are out of stock.
LocalInventory | Checks the OrderForm to ensure that an item does not require more of a given SKU than is in stock.
ReduceLocalInventory | For backward compatibility.


The Plan Pipeline

The Plan pipeline consists of 14 stages. These stages consist of components that verify the integrity of the OrderForm. For example, if the items list in an OrderForm contains no items, then the RequiredProdInfo component in the Product Info stage fails.

The template for this pipeline is Plan.pct. Examples of pipelines based on this template include the Plan.pcf files that appear in the \Config directory for the Volcano Coffee and Clocktower sample sites.

The Plan pipeline template consists of the following stages.

Product Info Stage

The Product Info stage contains components that retrieve product information about the items in the items list from the site database. If information about a given item cannot be retrieved, Product Info stage components mark the item for deletion by creating a delete name/value pair in the item Dictionary, and initializing the name/value pair to one (1).

After the Product Information components have been executed, the required component in the Product Information stage iterates through the items list, deleting every item that has been marked for deletion.

The components related to this stage include the following.

Component | Description
QueryProdInfo | Executes a database query, based on the SKUs in the OrderForm's items list, and puts the returned data in the OrderForm’s items collection. If no data is found for the SKU, the item is marked for deletion, and a pur_badsku errir is added to the _Basket_Errors list.
QueryProdInfoADO | Executes a database query, using the Microsoft® ActiveX® Data Objects (ADO). This component differs from QueryProdInfo in that the query that it executes can take multiple parameters, and can reference a query in the QueryMap Dictionary.
RequiredProdInfo (embedded in stage) | If any items are marked for deletion, deletes them and writes appropriate error messages.

Merchant Information Stage

The Merchant Information stage can retrieve static merchant data and write the data to the OrderForm. Commerce Server 3.0 includes no component for this stage (other than Scriptor). However, you can add your own custom component to process merchant information.

Shopper Information Stage

The Shopper Information stage contains the DefaultShopperInfo component, which adds information about the customer to the OrderForm.

The components related to this stage include the following.

Component | Description
DefaultShopperInfo (included in template) | Initializes entries in the order form to contain the values read from the shopper dictionary.

Order Initialization Stage

The Order Initialization stage sets initial order information on the OrderForm, and verifies that the OrderForm contains an order ID.

The components related to this stage include the following.

Component | Description
RequiredOrderInit (embedded in stage) | Initializes values in the order form prior to processing the order.

Order Check Stage

The Order Check stage verifies that the order can be processed. If necessary and possible, alters the order so that it can be processed.

The components related to this stage include the following.

Component | Description
RequiredOrderCheck | Ensures that there is at least one item in the OrderForm.

Item Price Stage

The Item Price stage contains components that set the _iadjust_regularprice for each item in the items list and that verify that this value has been set. If this value cannot be set, an error is raised.

The purpose of this initialization is to ensure that the _iadjust_regularprice name/value pair contains the most current price information for the given SKU.

The components related to this stage include the following.

Component | Description
DefaultItemPrice (included in template) | For each item in the items list, initializes that item's _iadjust_regularprice name/value pair to the value stored in _product_list_price.
RequiredItemPrice (embedded in stage) | Ensures that _iadjust_regularprice is set for each item in the items list.

Item Adjust Price Stage

The Item Adjust Price stage contains components that initialize the _iadjust_currentprice name/value pair. When this stage is complete, _iadjust_currentprice contains the current price of the item, adjusted for sales or promotions.

If no sale or promotion component is included by this stage, the name/value pair is set to the value stored in _iadjust_regularprice.

Once the item._iadjust_currentprice name/value pair has be set for an item, that item cannot be adjusted a second time. For example, if a stage includes both an ItemPromo and a SaleAdjust component, and an item on the order qualifies for both the promotion and the sale adjustment, the item’s _iadjust_currentprice will be initialized by the component that is executed first within the stage. This generalization applies for any combination of Item Price Adjust components that you include in your pipeline.

The components related to this stage include the following.

Component | Description
ItemPromo | Adjusts the _iadjust_currentprice name/value pair, based on promotional parameters.
SaleAdjust | Determines whether an item is on sale. If it is, SaleAdjust sets the item’s _iadjust_currentprice name/value pair to the value stored in the _product_sale_price name/value pair.
RequiredItemAdjustPrice (embedded in stage) | Verifies that the _iadjust_currentprice name/value pair is set.

Order Adjust Price Stage

The Order Adjust Price stage contains components that set the adjusted price of each item. This stage can use items other than those that are adjusted to adjust the order. This stage can use information used by the Item Price Adjust stage, as well as other information about the order.

The item._oadjust_adjustedprice name/value pair contains the total cost of a given item. For example, if a customer purchases three items costing $5.00 each, and none of the items are on sale or targeted by a promotion, the total for the item is $15.00. If two of the items are sold at the regular price, but the third is sold at half price (because of a promotion), the name/value pair is 12.50.

The components related to this stage include the following.

Component | Description
DbOrderPromo | Queries the database to determine a promotion amount.
DbOrderPromoADO | Queries the database to determine a promotion amount.
RequiredOrderAdjustPrice (embedded in stage) | Checks the _oadjust_adjustedprice member of every item in the items collection to ensure that it is set.

Order Subtotal Stage

The Order Subtotal stage calculates the subtotal for an order and stores the resulting value in the OrderForm’s _oadjust_subtotal name/value pair. The _oadjust_subtotal is the sum of the _oadjust_adjustedprice for all items.

The components related to this stage include the following.

Component | Description
DefaultOrderSubtotal | Calculates the subtotal for an order, and stores the result in the order._oadjust_subtotal.
RequiredOrderSubtotal (embedded in stage) | Checks the order._oadjust_subtotal name/value pair to ensure that it is not NULL.

Shipping Stage

This stage calculates the total shipping charge for the order and sets the order._shipping_total name/value pair accordingly. For information about how the components in this stage interact, see Using the Shipping Components.

The components related to this stage include the following.

Component | Description
DefaultShipping (included in template) | Ensures the integrity of the OrderForm by setting order._shipping_total to zero (0).
FixedShipping | Sets the order._shipping_total to a fixed amount.
LinearShipping | Sets the order._shipping_total name/value pair by multiplying a rate by the sum of a specified value on the OrderForm.
TableShipping | Sets the order._shipping_total name/value pair to a value returned by a specified query.
TableShippingADO | Identical to TableShipping, except that TableShippingADO uses Microsoft® ActiveX® Data Objects (ADO) to perform the query, and can be included in a transacted pipeline.
RequiredShipping (embedded in stage) | Checks the OrderForm to ensure that the order._shipping_total has been set.

Handling Stage

This stage calculates the total handling charge for the order and sets the order._handling_total name/value pair accordingly, if handling charges are not included in the shipping charge.

Multiple components can be specified to allow for different handling charges depending on the handling component used. The handling components are virtually identical to the shipping components; thus, you can use the shipping components to calculate shipping and handling charges together. However, some tax systems require shipping and handling charges to be calculated and taxed separately.

This stage verifies that order._handling_total is set. If not, it generates an error.

The components related to this stage include the following.

Component | Description
DefaultHandling (included in template) | Sets the order._handling_total name/value pair to zero (0).
FixedHandling | Sets the order._handling_total name/value pair to a fixed amount.
LinearHandling | Sets the order._handling_total name/value pair by multiplying a rate times the sum of a specified item on the OrderForm.
TableHandling | Calculates the value for the order._handling_total name/value pair based on the results of a query.
TableHandlingADO | Identical to the TableHandling component, except that TableHandlingADO uses Microsoft® ActiveX® Data Objects (ADO) to perform the query, and can be included in a transacted pipeline.
RequiredHandling (embedded in stage) | Checks the OrderForm to ensure that the order._handling_total has been set.

Tax Stage

This stage computes the sales tax for each item on the order, and the sum of tax for the entire order. The stage sets the item._tax_total, order._tax_total, and order._tax_included name/value pairs accordingly. Multiple components can be specified to allow for different tax rates depending upon the destination country. For information about how these components interact, see Using the Tax Components.

The components related to this stage include the following.

Component | Description
DefaultTax (included in template) | Sets the OrderForm's _tax_total and _tax_included values to zero (0).
SimpleCanadaTax | Computes a tax rate for Canada, including GST (goods and services tax) and PST (provincial sales tax).
SimpleJapanTax | Computes the tax rate for the Japanese model.
SimpleUSTax | Applies a given tax rate to any order sent to a specified state.
SimpleVATTax | Computes a value-added tax (VAT) on the items.
RequiredTax (embedded in stage) | Checks to make sure that the OrderForm’s _tax_total and _tax_included values are not NULL.

Order Total Stage

This stage sums the subtotal (less any discount), tax, shipping, and handling values and writes the total to the order._total_total name/value pair.

The components related to this stage include the following.

Component | Description
DefaultTotal (included in template) | Writes the total cost of the order to the _total_total name/value pair.
RequiredTotal (embedded in stage) | Performs a _VERIFY_WITH check of the OrderForm.

Inventory Stage

This stage verifies that every item ordered is in stock. For information about how the inventory components interact, see Using the Inventory Components.

The components related to this stage include the following.

Component | Description
FlagInventory | Flags items in the items SimpleList that are out of stock.
LocalInventory | Checks the OrderForm to ensure that an item does not require more of a given SKU than is in stock.
ReduceLocalInventory | For backward compatibility


The Purchase Pipeline

The Purchase pipeline consists of three stages. These stages use components that accept the final purchase of an order form, write an order to database storage and, optionally, finalize a receipt and write the contents of the OrderForm to the receipt database.

The Purchase pipeline can be run once you have run an OrderForm successfully through the Plan pipeline, and have confirmed the customer’s desire to finalize a purchase.

Because Purchase pipeline components write to a database, a Purchase pipeline is often a transacted pipeline. A transacted pipeline is a pipeline that consists exclusively of components that are designed and configured to support Microsoft Transaction Server (MTS) transactions.

The template for this pipeline is Purchase.pct. Examples of pipelines based on this template include the Purchase.pcf files that appear in the Config directory for the Volcano Coffee and Clocktower sample sites.

The Purchase pipeline template consists of the following stages.

Purchase Check Stage

The Purchase Check stage is used to verify that the address and credit-card information that the customer has provided meets certain validation criteria.

In the Purchase.pct template, this stage contains no components by default. For an example of components that can be used in this stage, refer to the Purchase.pcf file created by the Site Builder Wizard for custom sites. This pipeline configuration contains two Scriptor components:

  • υValidate Bill_to. Verifies that each of the bill_to_* fields on the order form contains data. If not, the script gets the appropriate message from the MessageManager object, adds the error text to the error list, and returns a return value of 2 indicating that an error occurred.
  • υValide CC Info. Verifies that each of the credit-card fields on the order form contains data, and that the credit-card type is one of a list of acceptable values. If not, the script gets the appropriate message from the message manager and adds the error text to the error list, and returns a return value of 2 indicating that an error occurred.

The components related to this stage include the following.

Component | Description
ValidateCCNumber | Performs a standard checksum test on the credit-card number.

Payment Stage

The Payment stage is used to approve credit-card payments. It sets the order._payment_auth_code name/value pair upon credit-card approval. This stage always ensures that _payment_auth_code is set. Otherwise, it generates a pur_bad_payment error.

If a credit card is not approved, this stage should set _payment_auth_code to DENIED and return error level 2.

The details of the payment components will vary depending upon the third-party payment processing system used.

The components related to this stage include the following.

Component | Description
DefaultPayment (included in template) | Places an initial setting on the _payment_auth_code name/value pair.
RequiredPayment (embedded in stage) | Ensures that the _payment_auth_code name/value pair is not NULL.

Accept Stage

This stage handles the completed order, including initiating order tracking, generating purchase orders, and inventory.

The components related to this stage include the following.

Component | Description
ExecuteProcess | Executes an application on the server with the specified arguments.
MakePO | Generates a purchase order, based on a template file.
PipeToPipe Transfer | Transfers an OrderForm or Dictionary from the currently running pipeline to another pipeline.
POtoFile | Sends a purchase order (typically the result of MakePO) to a file.
SaveReceipt | Writes the contents of the OrderForm to the receipt storage.
SendSMTP | Sends a mail message to the specified address.
SQLItem | Runs the specified SQL command for each item in the order with the given fields from the order and item as arguments.
SQLItemADO | Runs the specified SQL command for each item in the order with the given fields from the order and item as arguments. This component is identical to SQLItem, except that it performs its work using Microsoft® ActiveX® Data Objects (ADO), and can be included in a transacted pipeline.
SQLOrder | Runs the specified SQL command once per order, with the given fields from the order as arguments.
SQLOrderADO | Runs the specified SQL command once per order, with the given fields from the order as arguments. This component is identical to SQLOrder, except that it performs its work using Microsoft® ActiveX® Data Objects (ADO), and can be included in a transacted pipeline.


Business-to-Business Pipelines

The business-to-business OPPs are used in Commerce sites designed for the creation and transmission of purchase orders between businesses that have an established relationship. Like their business-to-consumer counterparts, these pipelines are performed at different times during the purchasing process:

  • υCorporate Purchasing Plan (CorpPurchasePlan.pct). Runs OPP components that compute the purchase order total, including all promotional discounts, taxes, shipping and handling charges. This pipeline is similar to the Plan pipeline used in business-to-consumer sites.
  • υCorporate Purchasing Submit (CorpPurchaseSubmit.pct). Runs OPP components that validate the purchase order requisition, transfer the purchase order to the vendor, and write the order to database storage. This pipeline is analogous to the Purchase pipeline used in business-to-consumer sites.


The Corporate Purchasing Plan Pipeline

The Corporate Purchasing Plan Pipeline runs OPP components that compute the purchase order total, including all promotional discounts, taxes, shipping and handling charges.

This template for this pipeline is CorpPurchasingPlan.pct. An example of a pipeline based on this template is the CorpPurchasingPlan.pcf file in the /Config directory of the Microsoft® Market sample site.

The Corporate Purchasing Plan pipeline consists of 14 stages. These stages correspond to the 14 stages in the business-to-consumer Plan pipeline.

Stage in Corporate Purchasing Plan pipeline | Corresponding stage in Plan pipeline
Requisition Item Info | Product Info
Supplier Information | Merchant Information
Buyer Information | Shopper Information
Requisition Initialization | Order Initialization
Requisition Check | Order Check
Requisition Item Price | Item Price
Requisition Item Adjust Price | Item Adjust Price
Requisition Adjust Price | Order Adjust Price
Requisition Subtotal | Order Subtotal
Shipping | Shipping
Handling | Handling
Tax | Tax
Requisition Total | Order Total
Inventory | Inventory


The Corporate Purchasing Submit Pipeline

The Corporate Purchasing Submit pipeline consists of two stages. These stages run components that validate the purchase order requisition, transfer the purchase order to the vendor, and write the order to database storage. This pipeline is analogous to the Purchase pipeline used in business-to-consumer sites.

The Corporate Purchasing Submit pipeline can be run once you have run an OrderForm successfully through the Corporate Purchasing Plan pipeline, and have confirmed the customer’s desire to finalize a purchase.

Because these pipeline components write to a database, the Corporate Purchasing Submit pipeline is often a transacted pipeline. A transacted pipeline is a pipeline that consists exclusively of components that are designed and configured to support Microsoft Transaction Server (MTS) transactions.

This template for the Corporate Purchasing Submit pipeline is CorpPurchaseSubmit.pct. An example of a pipeline based on this template is the CorpPurchasingSubmit.pcf file in the /Config directory of the Microsoft Market sample site.

The Corporate Purchasing Submit pipeline template consists of the following stages.

Purchase Order Validate Stage

The Purchase Order Validate stage is used to verify that the purchase order is valid.

Commerce Server 3.0 includes no component for this stage (other than Scriptor). However, you can add your own custom component to validate the purchase order.

Purchase Order Submit Stage

This stage handles the completed purchase order and transmits it to the vendor.

The components related to this stage include the following.

Component | Description
ExecuteProcess | Executes an application on the server with the specified arguments.
MakePO | Generates a purchase order, based on a template file.
PipeToPipe Transfer | Transfers an OrderForm or Dictionary from the currently running pipeline to another pipeline.
POtoFile | Sends a purchase order (typically the result of MakePO) to a file.
SaveReceipt | Writes the contents of the OrderForm to the receipt storage.
SendSMTP | Sends a mail message to the specified address.
SQLItem | Runs the specified SQL command for each item in the order with the given fields from the order and item as arguments.
SQLItemADO | Runs the specified SQL command for each item in the order with the given fields from the order and item as arguments. This component is identical to SQLItem, except that it performs its work using Microsoft® ActiveX® Data Objects (ADO), and can be included in a transacted pipeline.
SQLOrder | Runs the specified SQL command once per order, with the given fields from the order as arguments.
SQLOrderADO | Runs the specified SQL command once per order, with the given fields from the order as arguments. This component is identical to SQLOrder, except that it performs its work using ADO, and can be included in a transacted pipeline.


Using the Order Processing Pipeline

This section describes the following topics:

  • υThe structure of the OrderForm object.
  • υThe Microsoft® Transaction Server (MTS) and the Order Processing Pipeline (OPP).
  • υUsing an Order Log.
  • υDisplaying the Contents of an OrderForm.
  • υUsing the Scriptor Component.
  • υUsing the Shipping, Tax, and Inventory Components.


The OrderForm

The OPP requires that data passed from the site to the OPP, and from the OPP to the site, be passed in an OrderForm object. This requirement applies both to components included in the default OPP and to components designed to extend its functionality.

The OrderForm consists of a structured set of Dictionary and SimpleList objects that makes it possible to present a detailed summary of all or part of one or more shopping sessions to the customer or to the OPP. This summary includes customer data, such as name, address, and credit-card information, as well as product information related to the purchase.

As the preceding diagram illustrates, the OrderForm is a Dictionary. The first element in this Dictionary is a reference to a SimpleList of the items that make up the order, and each of these items is itself another Dictionary. The SimpleList is referred to as the items list.

The elements that make up both the order Dictionary and the Dictionary objects in the items SimpleList are called name/value pairs. Each component that you include in the OPP for your site is designed to operate on one or more of these name/value pairs. Typical operations include the following:

  • υName/value pair creation. Several components create name/value pairs in an OrderForm. For example, the QueryProdInfoADO component queries a specified database table for information on a given product, prepends _product_ to the column name, and adds the resulting name and the value for the associated row to the OrderForm.
  • υName/value pair initialization. The required components in the OPP fall into this category. These components check to make sure that certain name/value pairs are initialized, and if they are not, these components initialize them. Thus, the RequiredOrderInit component, which is part of the Order Initialization stage sets the _total_total, _oadjust_subtotal, _shipping_total, _tax_total, _handling_total, _tax_included and _payment_auth_code name/value pairs to Null.
  • υName/value pair verification. The OPP fails if certain name/value pairs on an OrderForm are not initialized when the pipeline is invoked. For example, the RequiredOrderInit component verifies that the items SimpleList on an OrderForm is not empty. If this SimpleList is empty, the component returns status indicating failure.
  • υName/value pair calculation. The optional components in the OPP initialize name/value pairs based on the work performed by other components. For example, the components in the Tax stage calculate the tax on an order, based on the list of items in the OrderForm’s items SimpleList, and writes the tax to the _tax_total name/value pair.

The underscore (_) character that precedes many of the name/value pairs in the OrderForm is known as a prefix. Generally, the inclusion of a prefix indicates the name/value pairs in an OrderForm that are not persistently stored.

Note

The contents of an OrderForm can vary, depending on how the pipeline for a site is configured. The figure listed previously is intended only to illustrate a typical OrderForm.

Related Topic

  • υValues Commonly Used on the OrderForm


Values Commonly Used on the OrderForm

The following table lists the typical name/value pairs on the OrderForm object, and includes a brief description of each item.

Name/Value Pair | Definition
order.shopper_id | Unique identifier for the customer who submitted this order. This name/value pair is initialized prior to the submission of the order to the OPP.
order.bill_to_* | Contains the billing address information for the current customer.
order.ship_to_* | Contains shipping information for the current customer. The ship_to_zip name/value pair can be used by the TableShipping and TableHandling components as one of the bases for computing shipping and handling costs.
order._Basket_Errors | A SimpleList in which components in the OPP store error messages retrieved from the MessageManager.
order._Purchase_Errors | A SimpleList in which components in the OPP store error messages retrieved from the MessageManager.
order.cc_name | Name that appears on the credit card used to finance the purchase. This name/value pair is initialized prior to the submission of the OrderForm to the OPP.
order.cc_type | Type of credit card submitted: VISA, MC, AMEX, or Discover. The ValidateCCNumber component uses this type as the basis for performing routine validation on the credit card number.
order._cc_number | Credit-card number for the card used to finance this purchase. By default, the SaveReceipt component, which persists other information on the OrderForm, does not save credit-card numbers.
order._cc_expmonth | Month in which the provided credit card expires.
order._cc_expyear | Day on which the provided credit card expires.
order.order_id | Unique identifier for this order.
order._total_total | Total cost of the order, including the order subtotal, shipping, handling, and tax. This value is initialized by the DefaultTotal component, and is verified by the RequiredTotal component.
order._tax_included | Value that indicates how much tax is included in the cost of the order.
order._handling_total | Total cost for handling the order. This value is initialized by Handling stage components (TableHandling, TableHandlingADO, FixedHandling).
order._shipping_total | Total cost for shipping the items on the OrderForm. By default, this is the name/value pair initialized by every Shipping component.
order._tax_total | Total tax for this order. This name/value pair is initialized by Tax stage components. How this value is calculated depends upon the Tax stage component used.
order._oadjust_subtotal | Subtotal of all the items in the items list. This value, which is initialized by the DefaultSubtotal component, represents a total of item._oadjust_adjustedprice for each item in the list. The item._oadjust_adjustedprice represents the total for a given item (its quantity times its list price, minus promotional discounts).
item.sku | Unique identifier of an item. The QueryProdInfo component passes this value as a parameter to the query that you specify to retrieve information on the item. This name/value pair can be ignored by QueryProdInfoADO.
item.Quantity | Number of items of a given SKU.
item.list_price | List_price of the item.
item._product_* | Name/value pairs contain information about items of a given SKU. These name/value pairs are initialized by the QueryProdInfo or QueryProdInfoADO components. The name portion of the name/value pair consists of the prefix _product_ followed by the name of the database table column from which the information was retrieved.
item._iadjust_regularprice | Name/value pair contains the regular price of the item. The DefaultItemPrice component, in the Item Price stage, initializes this name/value pair to the value _product_list_price. The RequiredItemPrice component ensures that this name/value pair is initialized. Promotional components, such as ItemPromo and DBOrderPromo uses this name/value pair as the basis for price adjustments. For example, if an item is to be reduced by a given percentage, that percentage is based on the value stored in _iadjust_regularprice.
item._iadjust_currentprice | Contains the current price of the item. Whereas the _iadjust_regularprice name/value pair contains the items regular price, this name/value pair reflects the regular price minus any promotional discounts.
item._oadjust_adjustedprice | Total cost of this item. This name/value pair contains the current price of the item times the quantity, minus discounts resulting from a promotion or sale.
item._n_unadjusted | Number of items of this SKU that have not participated in a promotional price reduction.
item._tax_total | Total tax for the items of this SKU.
item._tax_included | Value that indicates how much tax is included in the cost of the item.

The following table lists the name/value pairs on an OrderForm and the OPP components that read from or write to the specified pair.

Name/Value Pair | Read By | Written By
order.bill_to_* |  |
order.cc_name |  |
order.cc_type | ValidateCCNumber |
order.date_changed |  |
order.items |  |
order.order_id |  | RequiredOrderInit
order.ship_to_name |  |
order.ship_to_street |  |
order.ship_to_city |  |
order.ship_to_state | SimpleCanadaTax, SimpleUSTax |
order.ship_to_zip | TableShipping (optional), TableHandling (optional) |
order.ship_to_country | SimpleCanadaTax, SimpleJapanTax, SimpleUSTax, SimpleVATTax |
order.ship_to_phone |  |
order.shipping_method | TableShipping, TableShippingADO, TableHandling, TableHandlingADO |
order._shipping_total | RequiredShipping | DefaultShipping, FixedShipping, LinearShipping, TableShipping, TableShippingADO
order.shopper_id |  |
order._Basket_Errors |  | RequiredProdInfo
order._cc_expmonth | ValidateCCNumber |
order._cc_expyear | ValidateCCNumber |
order._cc_number | ValidateCCNumber |
order._handling_total | RequiredHandling, DefaultTotal, | RequiredOrderInit, DefaultHandling, FixedHandling, LinearHandling, TableHandling, TableHandlingADO
order._oadjust_subtotal | RequiredOrderSubtotal, DefaultTotal | DefaultOrderSubtotal, RequiredOrderInit
order._payment_auth_code | RequiredPayment | RequiredOrderInit, DefaultPayment
order._Purchase_Errors |  | FlagInventory, LocalInventory, RequiredHandling, RequiredItemAdjustPrice,RequiredOrderCheck, RequiredPayment, RequiredShipping, RequiredTotal, ValidateCCNumber
order._shipping_total | DefaultTotal | RequiredOrderInit
order._shopper_* | DbOrderPromo | DefaultShopperInfo, QueryProdInfoADO
order._tax_included |  | RequiredOrderInit, DefaultTax, SimpleCanadaTax, SimpleJapanTax, SimpleUSTax, SimpleVATTax
order._tax_total | DefaultTotal | DefaultTax, RequiredOrderInit, SimpleCanadaTax, SimpleJapanTax, SimpleUSTax, SimpleVATTax
order._tax_total_gst |  | SimpleCanadaTax
order._tax_total_pst |  | SimpleCanadaTax
order._total_total |  | DefaultTotal, RequiredOrderInit
order._verify_with | RequiredTotal |
item.delete | RequiredProdInfo, QueryProdInfo, QueryProdInfoADO |
item.placed_price | RequiredItemAdjustPrice | RequiredItemAdjustPrice
item.quantity | DbOrderPromo, DbOrderPromoADO, FlagInventory, LocalInventory, ReduceLocalInventory, RequiredOrderAdjustPrice, RequiredOrderInit | RequiredOrderInit
item.sku | LocalInventory, QueryProdInfo, QueryProdInfoADO, ReduceLocalInventory |
item._iadjust_currentprice | DbOrderPromo, DbOrderPromoADO, ItemPromo, RequiredItemAdjustPrice, RequiredOrderAdjustPrice | ItemPromo, RequiredItemAdjustPrice, SaleAdjust
item._iadjust_regularprice | ItemPromo, RequiredItemAdjustPrice, RequiredItemPrice | DefaultItemPrice
item._inventory_backorder |  | FlagInventory, LocalInventory
item._n_unadjusted | DbOrderPromo, DbOrderPromoADO, RequiredOrderAdjustPrice | DbOrderPromo, RequiredOrderInit
item._oadjust_adjustedprice | RequiredOrderAdjustPrice, SimpleCanadaTax, SimpleJapanTax, SimpleUSTax, SimpleVATTax |  | DbOrderPromo, DbOrderPromoADO, DefaultOrderSubtotal, RequiredOrderAdjustPrice,
item._oadjust_discount |  |  | RequiredOrderAdjustPrice
item._product_* | DbOrderPromo, QueryProdInfo, QueryProdInfoADO |  |
item._product_gst | SimpleCanadaTax |  |
item._product_in_stock | FlagInventory |  |
item._product_jpn_tax_included | SimpleJapanTax |  |
item._product_jpn_tax_rate | SimpleJapanTax |  |
item._product_list_price | DefaultItemPrice |  |
item._product_local_inventory | LocalInventory |  |
item._product_pst | SimpleCanadaTax |  |
item._product_sale_end | SaleAdjust |  |
item._product_sale_price | SaleAdjust |  |
item._product_sale_start | SaleAdjust |  |
item._product_tax_rate | SimpleVATTax |  |
item._oadjust_adjustedprice |  |  | RequiredOrderInit
item._tax_included |  |  | SimpleCanadaTax, SimpleJapanTax, SimpleUSTax, SimpleVATTax
item._tax_total |  |  | SimpleCanadaTax, SimpleJapanTax, SimpleUSTax, SimpleVATTax
item._tax_vat_item |  |  | SimpleVATTax


Referencing Items on an OrderForm

Throughout this document, name/value pairs are identified both by their names, and by the section of the OrderForm of which they are a part. Thus, the cc_name name/value pair on the order Dictionary is referenced conventionally as follows:

order.cc_name

Similarly, the elements of items in the items SimpleList are prefixed with the word item:

item.SKU

This mode of reference is not intended to demonstrate the technically accurate way of referencing elements of an OrderForm. It is intended only for clarity of reference.


Modifying the OrderForm Object

When you pass an OrderForm to the order processing pipeline (OPP), the OrderForm must already be initialized with certain elements of data.

You can modify an OrderForm in any of the following ways:

  • υBy direct assignment. To initialize the shopper_id name/value pair in a page, perform the following assignment:
    objOrderForm.shopper_id = objPage.GetShopperID()
  • υUsing the OrderForm object’s native methods. The OrderForm object implements the AddItem, ClearItems, and Clear methods, which are designed to add items to the items SimpleList, clear items from the items SimpleList, and clear the entire OrderForm, respectively.
  • υUsing the DBStorage object. The DBStorage object is designed to load a row of data from a database table into an OrderForm or Dictionary object.

Related Topic

  • υThe DBStorage Object Overview


The Pipeline Editor

Pipelines are described in pipeline configuration (.pcf) files. You create and configure these files using either the Active Server Pages (ASP)-based HTML Pipeline Editor or the Win32®-based Pipeline Editor.

The Pipeline Editor displays a tree, outlining the stages implemented by the default OPP, as well as the components that can be used in each stage of processing.

Stages and components are executed by the OPP in the order in which they are included in the tree.

Certain components are said to have an affinity with certain stages. This means that the component can function within that stage. Commerce Server does not enforce this stage/component association. You can include in any stage any component that can sensibly coordinate with other components in that stage.

Note

If you use the Commerce Server Pipeline Editor to display the components that have an affinity with a given stage, you will see the DCOMTransport and Scriptor components listed. These components have an affinity with all stages.


The Microsoft Transaction Server and the Order Processing Pipeline

A Microsoft® Transaction Server (MTS) transaction is a unit of work that is performed as an atomic operation. In the ASP environment, transactions occur on a per-page level. To mark an ASP as one that requires a transaction, you include the following script at the top of the page:

<%@ LANGUAGE=VBScript Transaction=Required%>

When you mark a page as transacted, all of the work that occurs on that page becomes part of the same transaction context. The objects that are created on the page, and the work performed by those objects, becomes part of that transaction context, provided that those objects are registered on the server system as MTS components. In the event of an error, the work performed by those objects can be rolled back, and the objects rendered stateless.

Suppose, for example, that you create a page that includes an object that uses the Microsoft® ActiveX® Data Objects (ADO) to insert or update data in a database. In the event that this component fails, you can call the MTS ObjectContext object’s SetAbort method to abort the transaction in which that object participates, and all of the modifications made by the object to the database are rolled back.

Related Topics

  • υCalling the MtsTxPipeline Object


Calling the MtsTxPipeline Object

The Commerce Server OPP supports MTS transactions through the MtsTxPipeline object. This object is registered as an MTS component during the Commerce Server installation, and is marked as requiring a transaction. If you create an MtsTxPipeline object on a page that is not marked as requiring a transaction, a transaction context is created for the MtsTxPipeline object, and the components that execute within that pipeline do so as part of a single, atomic operation. If you create an MtsTxPipeline object on a page marked as requiring a transaction, the MtsTxPipeline executes as part of the page-level transaction context.

In either case, the MtsTxPipeline object’s transaction support provides a host of benefits to the site builder. First, and most importantly, transaction support means that if any component in an MtsTxPipeline fails, the work of the preceding components in the pipeline is rolled back, and the MtsTxPipeline object ends the transaction.

The MtsTxPipeline object’s transaction support proves particularly beneficial in relation to OPP components such as SQLItemADO and SQLOrderADO, which modify the site database. If you use these components, or any other ADO-related OPP component that modifies the database, and a component that follows it fails, the modifications that the component makes to the database are automatically rolled back.

Moreover, this behavior holds true whether or not the page on which you execute the MtsTxPipeline is marked as requiring a transaction. If the page is marked as requiring a transaction, then the object instance that you create participates in that transaction. If the page is not marked as requiring a transaction, one is created for the MtsTxPipeline, and the MtsTxPipeline aborts the transaction in the event of a component failure.

Related Topics

  • υThe MtsTxPipeline Object


Error Handling

Error handling in the Commerce Server version 3.0 site environment revolves around the OPP’s interaction with the OrderForm, the MtsPipeline or MtsTxPipeline object, and the MessageManager object.

The OrderForm provides a detailed, in-memory summary of one or more shopping sessions, including merchant, customer, and item information. You pass an initialized OrderForm to the OPP by calling the OrderPipeline’s OrderExecute method.

As the OrderForm is passed through various stages of the OPP, the components associated with each stage read and write various values to and from the OrderForm.

For purposes of error processing, the most crucial members of the OrderForm are its _Basket_Errors and _Purchase_Errors collections. These collections are intended to store strings that describe error conditions that the OPP detects while processing other elements of the OrderForm.

The OPP gets these strings from the MessageManager. The MessageManager is a site’s central repository of locale-based error messages. Each message stored in the MessageManager consists of a string that describes a given error condition, and a string identifier that uniquely identifies the message to the OPP. The MessageManager creates the association between string identifier and string message through the AddMessage method that adds a message to the MessageManager.

Although the string used to describe a given error condition can vary from one site environment to the next, the string ID that identifies a message is hard coded. For example, if the OPP is unable to validate a credit card in the OrderForm, the pipeline attempts to retrieve the string associated with the message ID pur_bad_cc in the site's MessageManager. If the site builder has not associated a string with this message ID, the error condition is ignored. Otherwise, the OPP retrieves this message and writes it to the OrderForm’s _Purchase_Errors collection. When the OrderExecute method that initiated the pipeline returns, this collection can be examined, and the strings in this collection can be used to provide site users with a detailed description of any errors that occurred during order processing.

The following example, from the Volcano Coffee sample site, illustrates the object interaction described in the preceding paragraphs.

The Volcano Coffee site creates a MessageManager component in its Global.asa file. Next, the MessageManager's AddMessage method is called multiple times to add a group of messages to the MessageManager:

REM -- Create a message manager for use by the pipeline
Set  MSCSMessageManager = Server.CreateObject("Commerce.MessageManager")
Call MSCSMessageManager.AddLanguage("usa", &H0409)
MSCSMessageManager.defaultLanguage = "usa"
Call MSCSMessageManager.AddMessage("pur_out_of_stock", "At least one item is out of stock.")
Call MSCSMessageManager.AddMessage("pur_badsku", "Products in your basket were deleted because they don't exist in this store.")
Call MSCSMessageManager.AddMessage("pur_badplacedprice", "Prices of products in your basket have been updated.")
Call MSCSMessageManager.AddMessage("pur_noitems", "An order must have at least one item.")
Call MSCSMessageManager.AddMessage("pur_badshipping", "Unable to complete order. Cannot compute shipping cost.")
Call MSCSMessageManager.AddMessage("pur_badtax", "Unable to complete order. Cannot compute tax.")
Call MSCSMessageManager.AddMessage("pur_badhandling", "Unable to complete order. Cannot compute handling cost.")
Call MSCSMessageManager.AddMessage("pur_badverify", "Changes to the data require your review. Please review and resubmit.")
Call MSCSMessageManager.AddMessage("pur_badpayment", "There was a problem authorizing your credit.  Please verify your payment information or use a different card.")
Call MSCSMessageManager.AddMessage("pur_badcc", "Bad Credit Card Number.")

After messages are added to the MessageManager, the MessageManager is initialized as an Application variable named MSCSMessageManager. Because the OPP must use the Active Server Pages (ASP) context to retrieve a site's instance of a given object, and must request this object by name, the MSCSMessageManager Application variable name is not optional:

REM Set up the Application instrinsic object
    Set Application("MSCSMessageManager")   = MSCSMessageManager

Related Topic

  • υThe Pipe Context Dictionary


Using an Order Log

There are two ways to view order processing pipeline (OPP) information. You can create an OPP run-time information log, which includes all the name/value pairs that are written to the OrderForm by each component in each stage. You can also view the contents of the OrderForm using the DumpOrder sample Scriptor component.

You can log run-time information for each stage in the pipeline to a text file. By doing so, you see each stage and each component within that stage as it is executed, including the information written to the OrderForm at each stage. This is useful for debugging the order process. To do this, add a call to the SetLogFile function.

To set up an order debug log for Volcano Coffee
  1. In a text editor, open Util.asp for the Volcano Coffee site. This file is usually located in the \Inetpub\WWWRoot\Vc30\Include subdirectory.
  2. In Util.asp, a pipeline object is created. Search for the following code:
    REM Call pipeline.SetLogFile("c:\temp\pipeline.log")
  3. Delete the REM keyword from the second line of code.
  4. Repeat steps 2 and 3 for a second call to SetLogFile.
  5. Save the file.

When you run the pipeline, stage and component information will be written to the specified file.

Warning

For the log file to be created, you must specify a location in which you have Write permission; otherwise, the log file creation will fail without a warning.

Remember that the order processing system is a series of components that execute in turn; the stages are merely an abstract grouping of those components. Thus, in the log file, components are numbered in the order that they are run and listed by name, but are not separated by pipeline stage.

Some stages have a built-in component that performs certain consistency tasks but does not appear in the list of pipeline components in either Pipeline Editor. These components are included in the log file and in the ordinal list, however.

For example, the following entry in the log file refers to the first component in the site. For the Clocktower, that would be the QueryProdInfo component (in the Product Information stage):

PIPELINE:++ component[0x0] about to be called    PROGID:  Commerce.QueryProdInfo.1

The next entry in the log file refers to the second component in the site. For the Clocktower, that would be the required component (in the Product Information stage):

PIPELINE:++ component[0x1] about to be called    PROGID:  Commerce.RequiredProdInfo.1
Note

The log file is easier to read if you use a spreadsheet application, such as Microsoft® Excel, to view it.


Displaying the Contents of an Order Form

A sample Microsoft® Visual Basic® script, DumpOrder.vbs, is supplied in the \Microsoft Site Server\SiteServer\Commerce\SDK\Commerce\Samples subdirectory. When it runs, DumpOrder writes the contents of the OrderForm to a file.

To use the DumpOrder script
  1. Add the Scriptor component to any stage in the pipeline. Double-click its icon. In the resulting property page, click the Scriptor tab, click VBScript in the Language drop-down list, and then click File.
  2. In the File box, type the path to the DumpOrder.vbs file (or click Browse to find it).
  3. DumpOrder takes a file name as a parameter, so type the full path name of the output file in the Config field. For example, filename=c:\order.log.
  4. Click OK, and then save the pipeline configuration file.
    5. Stop and restart Microsoft® Internet Information Server (IIS), or modify the Global.asa file to restart the application. DumpOrder will write a file with the name you specified as a parameter when the order processing pipeline runs.

Related Topic

  • υUsing the Scriptor Component
  • υConfiguring a Scriptor Component


Using the Scriptor Component

The Scriptor component makes it possible to insert code modules into your pipeline. These modules are written using either the Microsoft® Visual Basic® Scripting Edition (VBScript) or JavaScript. From within a Scriptor component, you can access the OrderForm, pipe context information, create other objects, and even execute other pipelines. In addition, because the Scriptor component supports configuration parameters, the Scriptor component provides perhaps the easiest way to write custom components for the order processing pipeline (OPP).

When you add a Scriptor component to your pipeline, you configure the component using the Scriptor component’s property page.

The Scripting Engine setting identifies the scripting engine you want to use to process the script. You can select any scripting engine installed on your computer.

Next, you specify whether you want the Scriptor component to execute an Internal or an External script. An Internal script is one in which the text of the script is stored in the Scriptor component itself. For example, if you select Internal, and then click Edit, the Scriptor component displays a Script Editing window that you use to write your script.

An External script is one that resides in a file on your hard disk. If you use the External script option, click the Browse button to locate the file in which the script is stored.

In the Config box, type the parameters and values that you want to pass to the script that you write. The ability to pass configuration parameters to the Scriptor component represents one of its most valuable features, because it allows you to set persistent property values on the Scriptor component, just as you would on any other component in the OPP.

Configuration parameters must be written using the name=value form. For example:

tax=1.35;shipping=2.00

The values of these parameters can be accessed by your script.

Related Topic

  • υThe Scriptor Methods
  • υConfiguring a Scriptor Component


The Scriptor Methods

When you display the property pages for a Scriptor component in the Win32®-based Pipeline Editor, select Internal, and then click the Edit button, the Scriptor component displays an edit window that contains the three routines that the Scriptor component can process:

'The following entry points are available (shown in VBScript format):

function MSCSExecute(config, orderform, context, flags)

    MSCSExecute = 1
end function

sub MSCSOpen(config)

end sub

sub MSCSClose()

end sub

These routines are called the Scriptor component’s entry points, and you can think of them as you would think of the event handlers for a Visual Basic object or Microsoft® ActiveX® control. You fill in the body of these routines with your own task-specific scripting code, and when the order processing pipeline (OPP) runs the Scriptor component, it executes the code that you write.

The script that you write for your MSCSOpen subroutine is executed immediately after the Scriptor component is created. The MSCSExit subroutine is executed after the Scriptor component is destroyed. The MSCSExecute function is called after MSCSOpen and before MSCSExit.

Of the three exports that make up a default Scriptor component, only the MSCSExecute method is required. The parameters that the Scriptor component passes to this function include the following:

  • υconfig. The configuration Dictionary for the Script, which contains the following information.
    Name | Value
    User-defined configuration parameters. | Parameter value. For example, if you type tax=1 in the Config box on the Scriptor component’s property page, the tax name/value pair appears in the configuration Dictionary.
    script_type | Identifies whether the script is internal or external. If internal, script_type contains the value INTERNAL; otherwise, EXTERNAL.
    script_text | Contains the entire script for the component.
    script_name | Contains the fully qualified path to the file that contains the script to execute. If the script_type is INTERNAL, this name/value pair contains no value.
    engine_prog_id | Identifies the scripting engine used to interpret the script. Possible values are VBScript and JScript.

  • υorderform. The OrderForm or Transport Dictionary that you pass to the pipeline object’s Execute method.
  • υcontext. The Pipe Context Dictionary that you pass to the pipeline object’s Execute method.
  • υflags. The flags that you pass to the pipeline object’s Execute method.


Using the ExecuteProcess Component

The ExecuteProcess component runs a specified executable, passing the executable the arguments that you provide. The process must not display any user interface elements. This component is typically run during the Accept stage, but can be run in any stage.

Related Topics

  • υExecuteProcess


Component Coordination

Unless an error of sufficient severity is returned, all the components in a given stage will be run on the OrderForm. By convention, components cooperate and do not overwrite a previous component’s results, unless the overwriting component is specifically designed for that purpose.

Consider, for example, a pipeline that includes the SimpleCanadaTax, SimpleUSTax, and SimpleJapanTax components in its Tax stage. All of these components read the same name/value pair, order.ship_to_country, to determine if they need to calculate tax on the OrderForm.

If the SimpleCanadaTax component precedes the SimpleUSTax component in the pipeline, and order._ship_to_country equals Canada, the SimpleCanadaTax component calculates the tax and writes the resulting value to order._tax_total. When the SimpleUSTax component, which appears next in the pipeline, reads the order.ship_to_country name/value pair and finds that it does not evaluate to US, the component should simply return without setting any values.

By convention, certain name/value pairs in the OrderForm help a component determine whether or not to write values. The following table shows the name/value pairs for four stages. These are the four stages in the pipeline in which errors are most likely to occur.

The Apply column in this table shows the name/value pairs that hold key information that a component can use to determine whether or not it should be used against this particular OrderForm’s contents. The Complete column shows what name/value pairs are set when the intended functionality of the stage is met.

Stage | Apply | Complete
Shipping | shipping_method | _shipping_total
Handling | shipping_method | _handling_total
Tax | ship_to_country | _tax_total
Payment | payment_method, cc_name, cc_type, _cc_number, _cc_exp_month, _cc_exp_year | _payment_auth_code

The single exception to the scenario outlined previously occurs in the case of components that are specifically designed to overwrite the values existing in a given name/value pair. To ensure that these components do not overwrite values that have been properly set, make sure that these components are inserted in their appropriate place in the pipeline.

Consider, for example, the following two components that have an affinity with the Shipping stage: the DefaultShipping and FixedShipping components. These components are all designed to set the shipping cost on an OrderForm.

The DefaultShipping component sets the OrderForm’s shipping cost to zero (0). The FixedShipping component writes a shipping cost to the OrderForm, if the shipping cost is not already set.

If these components are inserted into the Shipping stage in the order in which they are described in the preceding paragraph, they produce the expected result; they set the shipping cost for an order.

However, if the DefaultShipping component follows the FixedShipping component in the pipeline, unexpected results follow. The FixedShipping component sets the shipping cost on the order, and the DefaultShipping component overwrites the shipping cost with a zero (0).

After inserting a component into your pipeline, double-click it in the Win32®-based Pipeline Editor to display its property pages, and then click the Values Read and Written tab. This tab identifies the OrderForm values that are read and written for that component.

In addition, if a component writes a value to the OrderForm, consult the documentation on that component to find out the value it writes, and how it determines that value.

Note

If you are writing a component, you should design the component so that if the value that it is designed to write already contains a value, the value is not overwritten by your component.

Failure Scenario

The following scenario is an example of a failure that can possibly occur if the coordination rules documented previously are not followed.

During the payment stage, the customer is presented with two payment options: pay by credit card or pay on account, probably by using a billing system statement. The customer chooses the billing method. If the credit card processing component ignores payment_method, the component will fail (because the customer did not enter a credit-card number). A possible solution might be to place the billing system component before the credit-card processing component in the OPP component sequence. However, if the billing system component does not set _payment_auth_code, the credit-card processor will still fail. Even if the billing system component does set _payment_auth_code, if the credit card component ignores the fact that _payment_auth_code is set, it will run and fail.


Required Components

The order processing pipeline (OPP) contains required components, components that generally verify the integrity of work performed within a given stage.

Unless you run the Win-32® Pipeline Editor in expert mode, these components are not displayed. They are simply appended to the end of each stage. To run the Pipeline Editor in expert mode, type the path to the Pipeline Editor at the command line, followed by the /g switch.


Third-Party Components

In addition to the components described in this document, the order processing pipeline (OPP) can include components that you create to extend the pipeline’s capabilities.

For information on how to do this, see Creating Custom Components.


Using the Shipping Components

The _shipping_total name/value pair on the OrderForm object stores the total cost of shipping for an order. Commerce Server version 3.0 supplies a number of components that you can use to compute the value to be stored in this name/value pair.

The DefaultShipping component sets this name/value pair to zero (0). If you do not want to charge shipping on an order, you can include this component alone in the stage.

Multiple components can be specified to allow for different shipping costs depending upon the shipping carrier used. Because you cannot anticipate which carrier your customer will select, you anticipate either situation in your pipeline.

Suppose, for example, that you offer customers the option of shipping by either UPS or Federal Express, and that you charge $19.95 to ship by one of these carriers and $29.95 to ship by the other. To configure the Shipping stage to handle this situation, include two instances of the FixedShipping component in your pipeline. One instance would be configured to apply the shipping cost to the OrderForm's _shipping_total name/value pair where the _shipping_method is equal to UPS, and the other would apply a different shipping cost to the _shipping_total name/value pair where the _shipping_method is FEDEX.

Related Topic

  • υHow to use Table Shipping


How to use Table Shipping

The TableShippingADO component is designed to retrieve a single currency value from a database table based on a query that you specify, and to write this currency value to order.[_shipping_total]. To use this component, perform the following steps:

  • υDetermine the basis of the calculation. For example, the basis might be the total weight of all the items in the order, and might also depend on the shipping method selected by the customer.
  • υCreate a table in the site database that stores the shipping cost as a function of the basis.
  • υCreate a query designed to retrieve this value to the site’s QueryMap Dictionary. If this query uses a product characteristic such as the sum total of the weight of the items in the order form, you may also need to modify the query that you use in the Product Information stage to ensure that this product information is present in the order form.
  • υConfigure the TableShippingADO component’s property page to reference this query.

The sections that follow illustrate how to perform these steps. In this example, we will modify the custom site generated by the Site Builder Wizard so that it uses a table to determine shipping cost based on total weight and on shipping method.

Adding a Weight Attribute to the Product Table

In this example, the weight of each product is used to calculate the shipping cost, For this reason, weight must be specified for every item in the store. The following procedure describes how to add a column called weight to the product table.

To add a database column using SQL Enterprise Manager
  1. On the Start menu, point to Programs, then Microsoft SQL Server, then click SQL Enterprise Manager.
  2. Expand the nodes for the server, then Databases, then the name of the database containing the Commerce Server site databases, then Objects, then Tables. Double-click the product table for the site. (In this example, the short name of the site is healthy, so the table is called healthy_product.)
  3. In the Manage Tables dialog, add a new column by entering weight in the Column Name field on the last row. For Datatype, select Float. Close the dialog and, when prompted to apply changes, click Yes.

Next, add the weight column to the query that is used by the QueryProdInfoADO component in the site’s Plan pipeline. In this example, the name of this query is product_info, and is defined in Global.asa.

To add the weight attribute to the product query
  1. Using Windows NT Explorer, open the site’s Global.asa file using an editor such as Notepad.
  2. Locate the script where product_info is added to the query map. It begins with the following commands:
    Set MSCSQueryMap.product_info = AddQuery("SELECT
  3. Add pf.weight to the list of columns returned by the SELECT statement. This ensures that the product weight is included in the item list for each product in the order form.

Creating the Shipping Cost Table

Add a shipping cost table to the database. The shipping cost table in this example uses the sum of the weight of each of the items in the items list, as well as the shipping method, as the basis of the shipping cost. The weight of each item is expressed in pounds. The shipping cost is expressed as an integer, in the smallest units of the currency (in this example, pennies). The following SQL script generates such a table.

CREATE TABLE dbo.healthy_shipping_costs (
    shipping_method varchar (20) NOT NULL ,
    min_weight float NOT NULL ,
    max_weight float NOT NULL ,
    cost int NOT NULL
PRIMARY KEY (shipping_method,min_weight,max_weight)
)
GO
truncate table healthy_shipping_costs
go
insert into healthy_shipping_costs values ('shipping_method_1', 0.0, 2.0, 450)
go
insert into healthy_shipping_costs values ('shipping_method_1', 2.0, 3.0, 540)
go
insert into healthy_shipping_costs values ('shipping_method_1', 3.0, 4.0, 630)
go
insert into healthy_shipping_costs values ('shipping_method_1', 4.0, 5.0, 720)
go
insert into healthy_shipping_costs values ('shipping_method_1', 5.0, 6.0, 810)
go
insert into healthy_shipping_costs values ('shipping_method_1', 6.0, 7.0, 900)
go
insert into healthy_shipping_costs values ('shipping_method_1', 7.0, 8.0, 990)
go
insert into healthy_shipping_costs values ('shipping_method_1', 8.0, 9.0, 1080)
go
insert into healthy_shipping_costs values ('shipping_method_1', 9.0, 15.0, 1400)
go
insert into healthy_shipping_costs values ('shipping_method_1', 15.0, 100.0, 2000)
go
insert into healthy_shipping_costs values ('shipping_method_2', 0.0, 2.0, 300)
go
insert into healthy_shipping_costs values ('shipping_method_2', 2.0, 3.0, 390)
go
insert into healthy_shipping_costs values ('shipping_method_2', 3.0, 4.0, 480)
go
insert into healthy_shipping_costs values ('shipping_method_2', 4.0, 5.0, 570)
go
insert into healthy_shipping_costs values ('shipping_method_2', 5.0, 6.0, 660)
go
insert into healthy_shipping_costs values ('shipping_method_2', 6.0, 7.0, 750)
go
insert into healthy_shipping_costs values ('shipping_method_2', 7.0, 8.0, 840)
go
insert into healthy_shipping_costs values ('shipping_method_2', 8.0, 9.0, 930)
go
insert into healthy_shipping_costs values ('shipping_method_2', 9.0, 15.0, 1000)
go
insert into healthy_shipping_costs values ('shipping_method_2', 15.0, 100.0, 1200)
go

After creating a table like this one, add a query to the site’s QueryMap Dictionary. This query should be designed to take as parameters all the values that are used as the basis. In this example, these parameters are the weight of all the items in the order along with the shipping method. The query should be included among the queries initialized in your site’s Global.asa file, as shown in the following script:

Set MSCSQueryMap.ship_cost = AddQuery("SELECT cost FROM healthy_shipping_costs WHERE min_weight <= ? AND max_weight > ? AND shipping_method = ?")

Because the site’s QueryMap Dictionary is usually included in the pipe context that is passed to the OPP, the TableShippingADO component can be configured to reference this query.

Enabling Selection of Shipping Method

When you create a custom site using the Site Builder Wizard, the wizard’s Shipping and Handling page enables you to specify up to three shipping method names and costs. By default, two are defined. They are labeled Overnight and 2nd Day.

When the customer clicks Purchase on the basket page, the Shipping.asp page is displayed. This page enables the customer to select the desired shipping method by using a drop-down menu containing the shipping methods defined in the Site Builder Wizard. This page posts the customer’s selection as either the text shipping_method_1 or the text shipping_method_2.

When the form is posted, the receiving page (Xt_orderform_prepare.asp) adds the shipping_method name/value pair to the order form, with its value depending on the which shipping method the customer selected from the form on the page.

Configuring the Component

To configure the TableShippingADO component to use the query that you added to the site’s QueryMap described earlier, use the Pipeline Editor to insert the TableShippingADO component into the Plan pipeline. This component should be inserted in the Shipping stage, and should appear after the DefaultShipping component.

Next, double-click the component in the Pipeline Editor to display its property pages. When you are finished configuring this page, it should look like this:

The table shipping component

The Apply When setting identifies the circumstances under which the value returned by the query is written to the _shipping_cost name/value pair. Here, the setting is Has any value, which means that the query is executed only when the order form contains a shipping_method value. This setting enables the Plan pipeline to be run in the Basket.asp page, before the customer has selected a shipping method and before the _shipping_cost name/value pair has been added to the order form. (If this field were set to Always, this component would fail on the Basket page because the query could not run successfully.) When the Plan pipeline is run again on the Payment.asp page, the shipping_method name/value pair now appears in the order form, and the ship_cost query is run.

In the Query box, type the name of the query to be executed. This example uses ship_cost, the name of the Dictionary entry that was added to the QueryMap Dictionary.

In the Parameter List box, type the values to pass to the query. The first two values must be the same (the weight of the total order), because the weight is used as the first two parameters in the query. The third parameter is the shipping method. To implement this example, enter the following parameter list:

sumq._product_weight  sumq._product_weight  order.shipping_method

In the Column box, type the name of the column that contains the shipping cost. In this example, this setting equates to the column cost that was defined as part of the shipping table. If no value is entered in this column, the component defaults to the value cost. In addition, if you specify a query that returns multiple rows of data, all rows after the first row are ignored.

When configuring the TableShippingADO component, keep the following in mind.

The TableShippingADO component should always be inserted after the DefaultShipping component in the Pipeline Editor. The DefaultShipping component ensures the integrity of the OrderForm’s _shipping_cost name/value pair by setting it to an initial value of zero (0). If you insert the TableShippingADO component, or any other shipping component, before the DefaultShipping component, the _shipping_cost name/value pair will be overwritten.

If your query references an item in the item Dictionary, you should make sure that the query that you execute in the Product Information stage is designed to retrieve that value from the product database. For example, if the TableShippingADO component references _product_weight as a parameter to the component’s query, then your product table should contain a column named weight, and your QueryProdInfo or QueryProdInfoADO component should execute a query that retrieves this column to storage in the item Dictionary.


Using the Tax Components

The Tax Stage and its components ensure that order._tax_total and order._tax_included are set. If not, an error is generated. If you are writing a custom tax processing component, be sure that your component sets both of these values when appropriate.

All components in the Tax stage will execute (unless a fatal error is returned). To cooperate, each component must check the resulting _tax_* values. If these values are already set, the component should return without doing anything. If the values are not set, the component will attempt to calculate the tax and if it is successful, set the _tax_* values.

In addition, the tax components must ensure that the value of _ship_to_country is set to the intended country; otherwise, the component will not execute. Furthermore, the OrderForm expects _tax_total to be set by the tax component. The tax component may set other name/value pairs during its execution, but in order for the stage to complete successfully, _tax_total must be set.

In each of the tax components, the country name must be specified as a parameter even though the name of the country is part of the name of the component (for example, SimpleCanadaTax). This is because the name of the component describes only the model for computing sales tax, and not the country to which it applies. For example, another country may actually use a tax model similar to Canada. Because the country name is specified, the tax model (and its corresponding component) can be used for more than one country.

Note

The tax components shipped with Commerce Server are provided only for evaluation and testing purposes only. Microsoft strongly recommends that you have an independent tax professional verify all applicable tax rates and data generated by this component before you use such information for personal or business purposes.

Related Topics

  • υDefaultTax
  • υSimpleCanadaTax
  • υSimpleJapanTax
  • υSimpleUSTax
  • υSimpleVATTax
  • υRequiredTax


Using the Inventory Components

Inventory management in Commerce Server sites usually occurs in two stages in the order processing pipeline (OPP).

The first stage, the Inventory stage, is usually configured to include components that determine whether a sufficient number of items is available to fill the order for a given SKU.

The second stage, the Accept stage, may be configured to modify the product table for a site to reflect the new number of items available for a given SKU. Optionally, you can use the SQLItemADO component in either the Inventory or Accept stages to reduce the local inventory once it has been added to a customer’s basket.

This section explains how to use the inventory components included in Commerce Server 3.0, and explains how you can use Commerce Server to address issues that arise in the context of inventory control.


Inventory and Backordering

How you manage inventory in your site depends largely on how you want to respond to a situation in which a given item is out of stock. In such a situation, you can either place the item on backorder, or you can notify the customer that the item is not currently available.

The FlagInventory and LocalInventory components, which have an affinity with the Inventory stage, coordinate with the QueryProdInfoADO component (Product Information stage) to support either response.

Flag Inventory Checking

The FlagInventory component is designed to identify items in the items SimpleList that are out of stock. When this component runs, it iterates through the items in the items SimpleList to verify that the _product_in_stock name/value pair for a given item is not zero (0).

If the _product_in_stock name/value pair evaluates to zero (0), FlagInventory can respond in either of several ways. The component supports a Disallow Backorder property, which you set using the component’s property page. If the Disallow Backorder check box is selected, and evaluates to 0, FlagInventory adds a _pur_out_of_stock message to the _Purchase_Errors SimpleList. If Disallow Backorder is not selected, and _product_in_stock evaluates to zero (0), then the _inventory_backorder name/value pair for the affected item is set to zero (0).

Note

If you include the FlagInventory component in your pipeline, but do not design the query that you execute in the Product Information stage to reference the in_stock column in your product table, the component fails.

Quantity-Based Inventory Checking

The LocalInventory component compares the number of units in the Quantity name/value pair to the number in the _product_local_inventory name/value pair. The _product_local_inventory value pair should represent the actual number of items in stock. If the Quantity exceeds _product_local_inventory, the difference between these two numbers is written to the _inventory_backorder name/value pair, provided that LocalInventory is configured to allow backordering. Otherwise, LocalInventory, like FlagInventory, writes a _pur_out_of_stock message to the _Purchase_Errors SimpleList.

If you include the LocalInventory component in your site’s pipeline, the script that you use to display the basket to customers should be written to notify them that a requested item is either out of stock or on backorder.

Note

If you include the LocalInventory component in your pipeline, but do not design your Product Information query to reference the local_inventory column in your product table, LocalInventory fails.


Reducing Inventory

The FlagInventory and LocalInventory components, discussed in the section on Inventory and Backordering, are strictly informational components. This means that while they provide notification that a given item is out of stock, they assume that the product table column that identifies the number of items in stock has been maintained by some other process.

Usually, this process involves including the ReduceLocalInventory or SQLItem components in the Accept stage of the purchase pipeline. Both of these components are designed to execute a query that you provide, and that decrements the value stored in the product table column that indicates how many of a given item are in stock.

Suppose, however, that a situation arises in which two customers are contending for an item of which there is only one in stock. As the OrderForm of each customer passes through the plan pipeline, the Inventory components indicate to both that the product is in stock. This is correct behavior, because the number that indicates how many items of a given SKU are in stock has not yet been reduced to zero (0) by an Accept stage component.

However, when the first customer runs the purchase pipeline, the SQLItemADO or ReduceLocalInventory component will reduce the in-stock value to zero (0). When the second customer runs the purchase pipeline, the SQLItemADO or ReduceLocalInventory component will reduce this value to a negative integer. In this scenario, back-ordering will effectively have been permitted, even though the site’s plan pipeline may have been configured to disallow backordering.

There are several ways to address this problem.

One solution to this problem is to include at the beginning of the Accept stage a SQLItemADO component that checks to ensure that number of items in stock for a given SKU is larger than zero (0). If no items for a given SKU are in stock, the SQLItemADO component can simply place the items on backorder (by initializing the _inventory_backorder name/value pair) or can raise the _pur_out_of_stock error.

A second solution is simply to include an instance of the appropriate inventory component (FlagInventory, for example) in both the Inventory stage (plan pipeline) and in the Accept stage (purchase pipeline). Following this component, you would include a ReduceLocalInventory component. This component would execute the query to decrement the in-stock value for the item.

The use of SQLItemADO is preferred in MtsTxPipelines. SQLItemADO supports transacted behavior, and ReduceLocalInventory does not.


Specifying the Basis Item Key

Many of the OPP components use a Basis Item Key to determine applicable rates. For this field, you can use any of the following values.

Basis Item Key prefix | Description
order.fieldname | The value of the specified field, where fieldname is a property on the order form.
sum.fieldname | The sum of value of the specified field for each item, where fieldname is a property in the item list.
sumq.fieldname | The sum of value of the specified field for each item, where fieldname is a property in the item list, times the quantity of that item.
count | The number of line items in the order form. (Does not depend on quantity of each item.)

The following table illustrates some useful values for Basis Item Key:

Example Basis Item Key | Result
order._oadjust_subtotal | Subtotal on the order form.
sum.quantity | Sum of all quantities (total number of items ordered).
sum._oadjust_adjustedprice | Sum of adjusted prices.
sumq._iadjust_currentprice | Sum of current price times quantity for all items in the order.
sumq._product_weight | Total weight of order. (Assumes that the weight column exists in the product table and that the query used by QueryProdInfoADO includes this field.)

For example, if sumq._product_weight is specified, and if the order has two items, one item weighing 2 pounds with a quantity of 3 and the other item weighing 4 pounds with a quantity of 1, then the basis value is 10 pounds.


Creating EDI messages with MakePO

The MakePO component is used to generate forms such as purchase orders (PO) from an Active Server Pages template file and information on the OrderForm. In order to demonstrate how to create EDI messages, Microsoft has created a sample template that can be used with MakePO to generate an ANSI X12 850 message, which is a purchase order (commonly referred to as an 850.)

The template file for generating an 850 is contained in the file PO850Template.txt, which can be found in \Microsoft Site Server\SiteServer\Commerce\SDK\Commerce\Samples.

The 850 template can be used with the MakePO component in the Microsoft Market SubmitViaInterchange pipeline, which is used to send orders for office supplies over the Commerce Interchange Pipeline. The template may also be used with the MakePO component in the Map stage of the Microsoft Market InterchangeTransmit.pcf pipeline.

The 850 template for MakePO is compatible only with Microsoft Market. It can be used in the Purchase Order Submit stage of the SubmitViaInterchange pipeline or in the Map stage of the InterchangeTransmit pipeline in Microsoft Market.


Order Processing Component Reference

The following components are commonly run in the order processing pipeline (OPP).

  • υDbOrderPromo
  • υDbOrderPromoADO
  • υDefaultHandling
  • υDefaultItemPrice
  • υDefaultOrderSubtotal
  • υDefaultPayment
  • υDefaultShipping
  • υDefaultShopperInfo
  • υDefaultTax
  • υDefaultTotal
  • υExecuteProcess
  • υFixedHandling
  • υFixedShipping
  • υFlagInventory
  • υItemPromo
  • υLinearHandling
  • υLinearShipping
  • υLocalInventory
  • υMakePO
  • υPipeToPipe Transfer
  • υPOtoFile
  • υQueryProdInfo
  • υQueryProdInfoADO
  • υReduceLocalInventory
  • υRequiredHandling
  • υRequiredItemAdjustPrice
  • υRequiredItemPrice
  • υRequiredOrderAdjustPrice
  • υRequiredOrderCheck
  • υRequiredOrderInit
  • υRequiredOrderSubtotal
  • υRequiredPayment
  • υRequiredProdInfo
  • υRequiredShipping
  • υRequiredTax
  • υRequiredTotal
  • υSaleAdjust
  • υSaveReceipt
  • υScriptor
  • υSendSMTP
  • υSimpleCanadaTax
  • υSimpleJapanTax
  • υSimpleUSTax
  • υSimpleVATTax
  • υSQLItem
  • υSQLItemADO
  • υSQLOrder
  • υSQLOrderADO
  • υTableHandling
  • υTableHandlingADO
  • υTableShipping
  • υTableShippingADO
  • υValidateCCNumber


The Commerce Interchange Pipeline

The Commerce Interchange Pipeline (CIP) enables businesses of all sizes to exchange information electronically. The CIP packages and transports business data objects from one application to another, over local-area network (LAN), wide-area network (WAN), Value-Added Network (VAN), or the Internet. It supports business-to-business trading scenarios, including corporate purchasing and supply-chain purchasing.

The CIP interoperates with existing transport systems such as e-mail and HTTP, as well as with new systems such as the Distributed Component Object Model (DCOM) and Microsoft® Message Queue (MSMQ), and is designed to work with systems yet to be devised.

The CIP exposes Component Object Model (COM) interfaces so that developers and third-party vendors can create compatible components and easily link them together into any desired configuration. The architecture of the CIP allows components to be developed independently of transport protocols and of specific data formats.

Any application, including accounting and business database applications, can use the CIP simply by creating and executing a pipeline. The CIP is both data-format independent and data-transport independent. Because the CIP provides a common interface, you can take advantage of a wide variety of components, whether included with the CIP or provided by third-party vendors, to conform to the protocols required by any other enterprise.


Business-to-Business Communications

All businesses, whether large or small, depend on continuous and accurate communications with other businesses. Traditionally, these messages have taken the form of printed forms, letters sent by mail, or telephone calls. More recently, many large businesses have turned to electronic communications, such as the Electronic Data Interchange (EDI), for the transmission of certain business documents.

The Commerce Interchange Pipeline (CIP) simplifies the electronic communication of business data, enabling even small businesses to take advantage of the benefits of electronic data transmission without incurring the cost overhead of a value-added network. These benefits include greater accuracy, improved security, lower cost, and faster response times.

Any type of business transaction can be conducted electronically using the CIP. The following example illustrates how a business might use the CIP to communicate with another business, creating a large network of inter-related enterprises.

Suppose that a business named Volcano Coffee, a national chain of coffee and tea shops, needs to order a large supply of coffee beans from Cascade Coffee Roasters and tea from the Margo Tea Company.

Cascade Coffee Roasters may not have the stock on hand to immediately fill this order, so it may need to purchase part of the order fulfillment from the East Indonesia Coffee Company.

If the Margo Tea Company finds itself in a position similar to that of the Cascade Coffee Roasters, it may need to purchase from the Northwind Traders. The interactions among these companies may occur as follows.

Supply chain scenario with Commerce Interchange Pipelines

In this illustration, Volcano Coffee sends its order over a transmit pipeline to Cascade Coffee Roasters. That company may or may not acknowledge having received the order. If it does, it will use its transmit pipeline to send a return receipt to Volcano Coffee, which will receive this return receipt on its receive pipeline. A similar series of transactions occurs between Cascade Coffee Roasters and its supplier, the East Indonesia Coffee Company, and between the Margot Tea Company and its supplier, Northwind Traders.

This scenario, which is an example of the supply-chain, could be expanded to encompass any number of trading partners. Regardless of the number or configuration of trading partners involved, the sequence of operations, as well as the structure of the business data objects exchanged among these trading partners, is dictated by the ordinary course of business, rather than by any limitations imposed by the software.

Although the preceding illustration is commerce-based, nothing in the CIP model ties it specifically to commerce. The CIP model fits into any scenario that requires the automated exchange of data.

The CIP Transmit and Receive pipelines can run on distinct sites on separate servers, or can exist on the same server. In fact, the Transmit pipeline does not necessarily have to transmit its data to a Receive pipeline, nor does a Receive pipeline necessarily have to receive its data from a Transmit pipeline. A Transmit pipeline needs only to transmit to some software component (such as an EDI translator) that is designed to interpret the data sent, and the Receive pipeline needs only to know how to interpret the data it receives.

The following diagram illustrates how a CIP, running under Microsoft Windows NT, can communicate either with a CIP on another computer running Windows NT, or with an EDI translator running under any operating system.

The CIP can communicate with non-CIP components


Interoperable Connectivity

The Commerce Interchange Pipeline (CIP) architecture suggests that you can transmit any data object to any application using any transport protocol, by mixing and matching interoperable, standardized components.

Because the configuration of a transmit or receive pipeline differs depending on the trading partner for which the pipeline was configured, a different transmit pipeline and receive pipeline is created for each trading partner.

Different sets of pipelines can be created for each trading partner

It each case, it is the pipeline configuration, stored in the .pcf file and loaded into the pipeline object, that identifies the exact configuration to be used in each case. Thus, it becomes realistic for any business to maintain any number of pipeline configurations to serve each trading partner.


Pipeline Architecture

The Commerce Interchange Pipeline (CIP) is an implementation of the Microsoft® Commerce Server version 3.0 pipeline architecture.

Each pipeline is essentially a framework that executes processes in sequence. The framework consists of stages, where each stage is an abstraction that describes generally the kind of work performed by one or more components associated with a stage. Each stage can be completely tailored to your application.

Each stage consists of one or more pipeline components. A component is a Component Object Model (COM) in-process server that performs some operation on the business object. For example, the CIP Encryption stage may contain the EncryptPCKS component, which is designed to encrypt a business data object.

Each component receives data from a previous component, performs its own process on the Transport Dictionary, and then makes the results available to the next component. You can add, move, and reconfigure the pipeline components in the order suited for your commerce application.

A CIP configuration file is created in the same way that a Commerce Server order processing pipeline (OPP) configuration file is created: using the Win32®-based Pipeline Editor or the ASP-based pipeline editor.

Related Topics

  • υThe Pipeline Editor


The Transport Dictionary

The Transport Dictionary is a Dictionary object that applications pass to the Commerce Interchange Pipeline (CIP). The Transport Dictionary has the same relationship with the CIP that the order form has with the order processing pipeline (OPP); it is the target of all CIP activity.

An application creates a Transport Dictionary to be passed as an argument to the CIP’s Execute method. This method can be invoked on the MtsPipeline or MtsTxPipeline object.

Once the Execute method is called, the various components that make up the sequentially executed stages of the CIP read data out of the Transport Dictionary into memory, perform various operations (for example, encryption and digital signing) on this data, and then write the result back into the Transport Dictionary.

In the case of a transmit pipeline, the pipeline begins with the Transport Dictionary that contains a name/value pair, usually called Object, which references the business data object, which is the object that contains the business document that you want to transmit. The Transport Dictionary may also contain an optional receipt request and an optional application identifier.

The business data object is referenced by the Transport Dictionary

As the Transport Dictionary is passed by the CIP from one component to the next, these components write new values to the Transport Dictionary (or overwrite old values), based on the contents of the business data object. Unlike the order processing pipeline, in which various components write various name/value pairs to an OrderForm, CIP components generally work with a single name/value pair on the Transport Dictionary: the working_data name/value pair. As the Transport Dictionary is passed to a component, it reads the contents of working_data into memory, performs some operation on the data, and overwrites the original working_data value. Where a component reads from or writes to a name/value pair other than working_data, this name/value pair is noted in the documentation on that component.

In the case of a receive pipeline, the pipeline begins with a Transport Dictionary that contains the data received. Depending on the transport used, this data may have been encrypted, converted to text and sent as e-mail or posted as an HTTP request. Whatever the mode of transmission, components in the receive pipeline are usually configured to process this data, converting it step-by-step back into a data object or other format such as EDI that can be used by the business application. Along the way, the pipeline components add the results of their conversions to the Transport Dictionary.

Note

While working_data is the default name/value pair for most CIP components, you can configure CIP components to use any name/value pair that you want.


Business Data Object

A business data object is a data container for business information such as purchase orders, purchase order acknowledgements, ship notices, invoices, billing records, and functional acknowledgements.

A business data object can be any object that supports Component Object Model (COM) interfaces for reading and writing the contained data. Specifically, the business data object can consist of any of the following:

  • υADO recordset
  • υOLEDB rowset
  • υCommerce Server Dictionary object
  • υCommerce Server SimpleList object
  • υCommerce Server OrderForm object

The business data object is usually referenced by the Object name/value pair in a Transport Dictionary.

Note

There is no interface that a business data object must implement to be a business data object. However, if you want to use CIP Mapping objects, this object must implement the IPersistXML, IPersistStream, or IPersistStreamInit interfaces (see MapToXML and MapFromXML). Optionally, you can write your own mapping component.

Related Topic

  • υThe Transport Dictionary


The Commerce Interchange Pipelines

A business-to-business scenario often involves two Commerce Interchange pipelines. One of these pipelines, the Transmit pipeline, packages an order and transmits it over a network or to a pipeline on the same computer. The second pipeline, a Receive pipeline, receives and reads the data, and performs various unpacking operations, such as decrypting the data, verifying the digital signature, and mapping the data to a format that can be read by an application.

Commerce Interchange Pipeline architecture

The configuration of a particular pipeline is saved in a pipeline configuration (.pcf) file. The pipeline configuration contains the following component types:

  • υMapping Components. Converts the contents of a business data object to a transmissible format, or converts received data to the object in which it was originally stored.
  • υAdd/Open Header. Adds/removes elements to and from the Transport Dictionary including sender and receiver addresses and receipt requests.
  • υDigital Signature component. Determines the type of digital signature used (if any) to digitally sign a business data object, or to verify its signature.
  • υEncryption/Decryption component. Determines how to encrypt or decrypt the contents of the business data object, using certificates.
  • υAudit Components. Writes various pieces of the business data object to the audit database.
  • υTransport connector. Designed and configured to transmit or receive a business data object.
  • υApplication Integration. Invokes an application to process the received business data object.

For each stage and component in the Transmit pipeline, there is usually a counterpart in the Receive pipeline (in reverse order).


The Transmit Pipeline

The Transmit pipeline is a form of the Commerce Interchange Pipeline that packages and transmits a business data object to a business partner.

The template for this pipeline is Transmit.pct. An example of a pipeline based on this template is the InterchangeTransmit.pcf file that is used by the Microsoft Market sample site.

The Transmit pipeline consists of the following stages.

Map Stage

The Map stage translates the business data object in the Object name/value pair into a stream of bytes suitable for transmission. By default, this stage writes the results of the conversion to a value in the Transport Dictionary called working_data.

For information about this stage, see Using Mapping Components.

The supplied components for this stage represent two ways to format the business data object as text.

Component | Description
MapToXML | Reads the data stored in the business data object in the Transport Dictionary, converts this data to an XML stream or to an XML-enclosed binary stream, and then writes the resulting stream to a specified name/value pair in the Transport Dictionary.
MakePO | Generates a text-based purchase order (PO) by merging the information on the order form with a purchase order template.

Add Header Stage

The Add Header stage encapsulates the working data within a header that provides additional information about the transmission, and writes the result back to the working data.

The components related to this stage include the following.

Component | Description
AddHeader | Appends a series of XML tags to the working data, including a transaction ID, the date and time on which the transaction occurred, and optionally, a return receipt request, and sender and receiver addresses. Usually, AddHeader is used only in a Transmit pipeline in which MapToXML appears in the Map stage, and when the OpenHeader component is needed in the Receive pipeline.
EncodeMIME | Applies MIME-encoding to the data in the working data name/value pair.

Digitally Sign Stage

The Digitally Sign stage places a digital signature on the stream of bytes. Optionally, you can use the components in this stage to apply S/MIME encoding to the data.

The components related to this stage include the following.

Component | Description
DigitalSig | Digitally signs the data in the working data name/value pair, using the Public Key Crypto System 7 (PKCS7), using a specified certificate.
EncodeSMIME | Applies secure MIME-encoding to the data in the working data name/value pair. This operation can include digitally signing and encrypting the business data object. EDIINT standard.

Encrypt Stage

The Encrypt stage encrypts the working data for transmission. The components use the encryption technology supported by the Microsoft® Cryptographic application programming interface (CryptoAPI), including the following:

  • υPublic Key Crypto System (PKCS7) standard-based
  • υS/MIME encapsulation of EDI Messages using the IETF EDIINT draft Internet standard
  • υCustom or third-party components

The components related to this stage include the following.

Component | Description
EncryptPKCS | Encrypts a business data object using the Public Key Crypto System (PKCS) security standard.
EncodeSMIME | Applies IETF EDIINT draft Internet standard secure MIME-encoding to the data in the working_data name/value pair. This operation can include digitally signing and encrypting the business data object.

Audit Stage

The Audit stage writes selected elements of information about the business transaction to the audit database.

The components related to this stage include the following.

Component | Description
Audit | Writes specified values from the Transport Dictionary into a database table in the audit database.
AuditReceipt | Writes data from the receipt into the audit database table. Not used in a Transmit pipeline.

Transport Stage

The Transport stage transmits the mapped, signed, and encrypted stream of bytes to the destination. For information about this stage, see CIP Transports.

The components related to this stage include the following.

Component | Description
PipetoPipeTransfer | Initializes and executes a remote pipeline to receive the Transport Dictionary from the current pipeline.
SendSMTP | Converts the signed and encrypted working data to text, and then sends it as an e-mail message to the specified recipient.
SendHTTP | Converts the signed and encrypted working data to text, and then sends it using an HTTP POST to transmit the data to a Web page (CGI, ISAPI, ASP, and so on)
SendDCOM | Sends the converted working data using Distributed Component Object Model (DCOM) to create and execute an MtsTxPipeline or MtsPipeline object on a remote Commerce Server computer.


The Receive Pipeline

The Receive pipeline is a form of the Commerce Interchange Pipeline that is used to receive a business data object sent by a business partner.

This template for this pipeline is Receive.pct. An example of a pipeline based on this template is the InterchangeReceive.pcf file that is used by the Microsoft Market sample site.

The Receive pipeline consists of the following stages.

Decrypt Stage

The business data is usually received in an encoded form suitable for transmission. The Decrypt stage decrypts the incoming data stream and writes the result to working data in the Transport Dictionary.

The components related to this stage include the following.

Component | Description
DecodeSMIME | Decodes a data stream that was encapsulated in the IETF EDIINT draft Internet standard S/MIME (secure MIME) format, and writes the result to working data.
DecryptPKCS | Decrypts the data stream using the PKCS7 standard, and writes this data and writes the result to working data.

Verify Digital Signature Stage

The Verify Digital Signature stage verifies the digital signature on the data stored in the Transport Dictionary.

The components related to this stage include the following.

Component | Description
DecodeSMIME | Decodes a business data object that was encapsulated in the IETF EDIINT draft Internet standard S/MIME (secure MIME) format.
VerifyDigitalSig | Verifies the digital signature on the data stored in the Transport Dictionary, using the PKCS7 standard.

Open Header Stage

The Open Header stage performs the counterpart operations to any components used in the Add Header stage of the Transmit pipeline. The stage saves message attributes in the Transport Dictionary and unwraps the business data for the Map stage.

The OpenHeader component creates a digest only if the sender has requested a return receipt. The digest is instead intended to confirm that the business data object was received, and is transmitted to the original sender by Generate Receipt stage.

The components related to this stage include the following.

Component | Description
DecodeMIME | Decodes a business data object that was encapsulated in the MIME format.
OpenHeader | Parses the XML data appended to the business data object by the Add Header stage, and writes the transaction ID, the data and time of the transmission, and an optional digest of the message data to the Transport Dictionary as name/value pairs, as well as the optional sender and receiver addresses.

Generate Receipt

If a receipt has been requested, the Generate Receipt stage creates a return receipt business data object, and then invokes a transmit pipeline to send the receipt object back to the trading partner that originally transmitted the business data.

The components related to this stage include the following.

Component | Description
GenerateReceipt | Reads values written to the Transport Dictionary by the OpenHeader component, and if requested, creates a receipt object and then invokes a transmit pipeline to send the receipt object back to the original sender.

Map Stage

The Map stage in the Receive pipeline converts the working data to a business data object.

The components related to this stage include the following.

Component | Description
MapFromXML | Reconstitutes the original business data object from the XML stream, and writes the object to the transport dictionary.

Audit Stage

The Audit stage writes selected elements of information about a business transaction to the audit database.

The components related to this stage include the following.

Component | Description
Audit | Writes specified values from the Transport Dictionary into a database table in the audit database.
AuditReceipt | Writes data from the receipt into the audit database table.

Application Integration Stage

The Application Integration stage is intended to contain components that map business object data to a format that can be read by a target application. For example, one might create an application integration component designed to read a Commerce Server SimpleList and write the contents of that SimpleList to an Excel spreadsheet.

The components related to this stage include the following.

Component | Description
SQLOrderADO | Runs a SQL query.


CIP Operations

This section provides a general description of the operations performed by components in a Commerce Interchange Pipeline (CIP), and how these operations fit within the CIP architecture. Topics covered include:

  • υObject mapping. Mapping designates the process by which an object is translated into a transmissible format, and is reconstituted from that format into the original object.
  • υReceipt and Request Generation. The CIP generates return receipts by performing a one-way hash of the business data object. This hash results in a message digest, a “fingerprint” of the original business data object. The party returning this receipt to the party that placed the original order can, additionally, digitally sign the message to verify that the order was received, that the receipt is genuine, and that it has not been tampered with in transit.
  • υEncryption and Digital Signing. The CIP includes components that support certificate-based public key encryption and digital signing. The use of public key encryption ensures that the business data object can only be deciphered by the party that possesses the private key for the certificate used to encrypt the object. Digital signing adds the advantage of ensuring the origin of the message, enabling the receiver to ensure that the message has not been modified, and preventing the original sender from repudiating the message.

    The use of secure MIME-encoding (S/MIME) encoding enables the sender to encode the business data object into a MIME message, digitally sign the message, and encrypt it.


Using Mapping Components

Mapping describes the process by which an object’s data is converted from one format to another. For example, in a Transmit pipeline, mapping involves translating an object’s data into a format suitable for transmission. In a Receive pipeline, mapping generally involves reconstituting the object from the transmitted data.

The map stage can include converting Electronic Data Interchange (EDI) communications into a form suitable for transmission. These components are available from third-party providers. For a partial listing of some of these companies and more information on how their applications enhance Site Server Commerce, please refer to http://www.microsoft.com/commercezone.

In the Transmit pipeline, the Map stage can contain the MapToXML component, which reads the data from the object referenced by the business data object’s Object name/value pair, converts the data to an XML-enclosed binary or a pure XML stream, and writes the results into the Transport Dictionary as a new name/value pair called working_data.

If MapToXML is used in the Transmit pipeline, then the MapFromXML component can be used in the Receive pipeline. MapFromXML converts an XML stream and returns a data object of the same type that was originally converted by the transmit pipeline component. The resulting business data object can then be used by the receiving application.

The MapToXML and MapFromXML components can map data to or from any object that implements the IPersistStreamInit or IPersistXML interfaces. Such objects include the Commerce Server Dictionary, SimpleList, OrderForm, and the Active Data Objects (ADO) Recordset.

The Map stage does not necessarily require the use of XML, however. The MakePO component can be used in the Transmit pipeline. This component reads specified data from the business data object and merges it with a text-based template to produce a text stream that can be human-readable. For example, this component can be used to format a purchase order as text. This text can then be transmitted by the SendSMTP component in the Transport stage.

Related Topic

  • υThe Extensible Markup Language
  • υMapToXML
  • υMapFromXML


The Extensible Markup Language

As the Commerce Server Interchange (CIP) Transport Dictionary passes through the various pipeline stages, the Transport Dictionary’s contents, and particularly its business data object, are encoded into the Extensible Markup Language (XML).

The XML standard is a subset of the Standard Generalized Markup Language (SGML), and was developed in 1996 by the SGML Working Group. The reasons for its development, and for its prominence in the CIP, are numerous. For information on the development of this standard by the World Wide Web Consortium, see http://www.w3.org/xml.

First, because XML conforms to the SGML specification, XML data can be transferred over the World-Wide Web, but is not required to conform to the HTML specification. This is a crucial element in its development, because one of the driving objectives behind the development of XML was to diversify the kinds of information that could be transferred and presented over the Web.

Second, XML supports the creation of “self-describing” documents through the use of a document type definition and/or XML data schemas, XML headers in which the creator of a document describes the kinds of information in the document, and the types of resources the document contains.

For purposes of business-to-business commerce, however, the most important feature of XML is that it allows you to define your own document tags, accommodating a great deal of flexibility in the way that business data is described. The baseline requirement for the way business documents are packaged into XML is the minimal provision that the document conform to the expectations of the XML processor, an application designed to interpret the XML data for presentation to the intended recipient.

Related Topic

  • υMapToXML


Receipt Request and Generation

When you transmit a business data object through a transmit pipeline, you have the option to request a return receipt for that data. Return receipts in the Commerce Interchange Pipeline (CIP) work very much as they do when you send a certified letter. You fill out a form indicating that you want some acknowledgement that the letter was received. When the letter is received, the recipient of the letter signs to get it, and the signed receipt is then transmitted back to you, the original sender.

In the CIP, a similar series of events occurs. To request a receipt, a property named Receipt_requested is added to the transport dictionary, and its value is set to the text Yes.

In the Add Header stage of the CIP, if Receipt_requested is present and is set to Yes, then the AddHeader component writes the receipt request to the Transport Dictionary prior to transmission.

The receipt request includes the following items:

  • υThe algorithm to be used to hash the business object data to derive a digest. SHA1 is a standard hash algorithm.
  • υA document type tag that identifies the kind of document requested from the receiving pipeline.

In the receive pipeline, the Transport Dictionary enters the Open Header stage. This stage contains the OpenHeader component. This component reads the XML tags appended to working_data by the AddHeader component, and writes them as name/value pairs to the Transport Dictionary. If, among these XML tags, appears a request for a return receipt, the OpenHeader component hashes the business data object to create the digest. The digest is not human-readable, and is intended to serve as a receipt. The digest also is written as a name/value pair to the Transport Dictionary.

The OpenHeader component is simply preparing the Transport Dictionary to be processed by the GenerateReceipt component. The Generate Receipt component reads the values written by OpenHeader, creates a return receipt business data object, and then sends the receipt back to the original sender using a new transmit pipeline.

The GenerateReceipt component does not send back to the sender all of the values stored in the original Transport Dictionary. It sends only the transaction ID, the system date and time on the receiving system, the digest created by the OpenHeader component, and optionally, the document type, source and destination that were described in the original transmission.

The original sender then provides a Receive pipeline to receive the receipt. This pipeline can contain the AuditReceipt component, which writes the receipt to the audit database.


Auditing

The Audit stage can appear in the Transmit pipeline and in the Receive pipeline. The Audit stage saves information about the business transaction to the audit database.

Four pipelines are required to implement receipts

Related Topics

  • υAudit
  • υAuditReceipt
  • υGenerateReceipt


Encryption and Digital Signing

Once the Transport Dictionary emerges from the Add Header stage, it contains all the data required for transmission. Usually, to ensure the secure transmission of this data, you will want also to encrypt and/or digitally sign the data. Alternatively, you may want to MIME-encode or S/MIME encode the data.

You can approach the encryption of the working_data in one of numerous ways, depending usually on the type of business data you are sending, the level of security you need.

The Digitally Sign stage contains the DigitalSig component, which uses a sender certificate to sign either the working data, a hash of the working data, or both the data and the hash, using the Public Key Crypto System 7 (PKCS7) standard.

The Encrypt stage contains the EncryptPKCS component, which uses a receiver certificate to encrypt the business data object into a PKCS7 message.

The Add Header stage usually contains the EncodeMIME stage, while both the Digitally Sign and the Encrypt stages can contain the EncodeSMIME component. The EncodeMIME component supports MIME-encoding (Base-64 or Quoted Printable). The EncodeSMIME component uses certificates to MIME-encode, digitally sign, and/or encrypt the business data object in accordance with the S/MIME specification.

The Receive pipeline contains the Decrypt and Verify Digital Signature and stages. These stages contain components that perform the reverse of their counterparts in the transmit pipeline.

The Verify Digital Signature stage, for example, contains the VerifyDigitalSig component, which uses the sender’s certificate to verify the digital signature on the business data object. The Encrypt stage contains the DecryptPKCS component, which uses the receiver certificate to decrypt the business data object.

When designing a transmit or receive pipeline, you can use virtually any combination of these components to secure the business data object. However, the following general considerations apply.

The design of your pipeline must be mirrored on the receiving side. For example, if you include the EncodeSMIME component in a transmit pipeline, the receive pipeline must contain a DecodeSMIME component. If your transmit pipeline contains a DigitalSig component, the receiving pipeline must contain a VerifyDigitalSig component.

Because most of the components in the Encrypt/Decrypt and Digitally Sign/Verify Digital Signature stages rely on certificates, you must also manage the exchange of these certificates with your trading partners, and must use the Certificate Management Tool to install the appropriate certificates on your system. If you include a DigitalSig component in your transmit pipeline, you must provide your trading partner with this certificate for use by the VerifyDigitalSig component in the receive pipeline. To use the EncryptPKCS component in your transmit pipeline, you must obtain a certificate from your trading partner (see Certificates).

Finally, because the encryption and digital signature components can be configured to use specific algorithms to perform their work, you must coordinate with your trading partners to ensure that the algorithm with which you choose to encrypt or digitally sign the business data object is available also on the receiving system.


Certificates

The CIP components that perform encryption/decryption and digital signing/verification rely upon certificates. A certificate is a packet of data that contains a user’s public key, in addition to the data that serves to identify the user in the real world. Every certificate is created and signed by a trusted entity known as a certificate authority (CA).

To use certificates with the encryption and digital signature components included with the CIP, you generally follow these procedures.

If you are encrypting data to send to a trading partner, you obtain from your trading partner the certificate that contains his or her public key. You import this certificate onto your system, using the Certificate Management Tool, and you use this certificate to configure the EncryptPKCS component, which uses the public key of your trading partner to encrypt the data. When your trading partner receives the data, it is decrypted using the certificate’s private key, which your trading partner has installed on the receiving system.

If you are digitally signing data to send to a trading partner, you use a certificate that you have obtained from a CA, and that you have installed on your system. You provide your trading partner with a copy of that certificate.

When the DigitalSig component is executed, it uses the certificate to perform the digital signing by calling the Microsoft® Cryptographic application programming interface (CryptoAPI). On the receiving end, the VerifyDigitalSig component uses the certificate that you have provided to your trading partner, and verifies that the signature on the data is yours.

Related Topic

  • υCertificate Management Tool


CIP Transports

The Transport stage in the transmit pipeline contains components that prepare the working data for transmission and that transmit the data. This stage isolates the other components from the details of the actual transport protocol.

Currently supported transports include the following:

  • υDCOM. The SendDCOM component uses the Distributed Component Object Model (DCOM) to create a receive connector object on the remote computer over a LAN, WAN, or the Internet. The remote DCOM object then creates a Receive pipeline, passing the Transport Dictionary to the remote pipeline instance.
  • υSMTP. The SendSMTP component transmits the working data as an e-mail message, using a SMTP-based server. For this connector to work, a process, operating in conjunction with a SMTP server (a mail server like Exchange) must wait for and process messages as they arrive at the receive end.
  • υHTTP. The SendHTTP component transmits data using an HTTP post. At the receive end, a Web page processes the HTTP post message.
  • υCustom or third-party. Any transport mechanism can be used, including EDI translators with a network connection to a Value Added Network (VAN).

For example, in a transmit pipeline that uses the EncryptPKCS component, the transport component reads the value in the working_data name/value pair and transmits the data as HTTP, as e-mail, or by any other protocol.

Commerce Interchange Pipeline transport protocols

For the transports previously defined, the format of the data sent over the transport can be one of the following:

  • υXML
  • υXML-wrapped binary COM object
  • υEDI
  • υAny third-party-supported formats


Creating a Receiving Agent for SMTP Transport

The SendSMTP component can send e-mail to any mail recipient. However, in order to receive a business data object and pass it to an application on the receive side, the receiving mail system must invoke the receive pipeline.

If you are using Microsoft® Exchange 5.5, you can run a Visual Basic script to invoke an OrderPipeline object (but not an MtsPipeline or MtsTxPipeline) on the Exchange server when mail arrives in the designated mailbox to process the received messages. Commerce Server includes the Recvsmtp.vbs example script, which is installed into \Microsoft Site Server\SiteServer\Commerce\. The following procedure describes how to use this script with an Exchange 5.5 mail server and Microsoft Outlook 8.03 installed on a client computer that connects to the Exchange server.

To create a receiving agent
  1. Create a new alias (for this example, name this alias Client1) on the Exchange 5.5 server (Server1) to monitor and program the receiving script.
  2. Start the Outlook 8.03 client on any computer on the network. Log on with a profile that chooses the alias Client1 on Server1.
  3. Create a public folder called CIReceive (for “Commerce Interchange Receive”).
    • υOn the File menu, point to New, and then click Folder.
    • υIn the Make this folder a subfolder of box, expand Public Folders, and then click All Public Folders.
    • υIn the Name box, type a name for the new folder.
    • υClick OK to create the folder.
  4. Grant users permissions to run scripts.
    • υIn the Administrator window, select the System Folders container for your organization.
    • υClick Events Root, and then select the EventConfig folder that corresponds to the Microsoft Exchange Server computer on which the folder owner should be granted permission.
    • υOn the File menu, click Properties.
    • υClick Client Permissions.
    • υClick Add, and then select the user (Client1) who will have permission to run applications or other event handlers on this server.
    • υIn the Roles box, select the Editor role. This enables the user to create scripts that handle events on this server.
  5. Make the chosen public folder accept mail.
    • υIn the Administrator window, select the Public Folders container for your organization.
    • υSelect the CIReceive folder that you created in Step 3.
    • υOn the File menu, click Properties.
    • υClick the Advanced tab. Clear the Hide from address book check box.
    • υClick the E-mail Address tab. Write down the e-mail address corresponding to SMTP (CIReceive@org1.com, in this example). Use this e-mail address for the SMTP Host when configuring the SendSMTP component for your Commerce Interchange transmit pipeline
  6. Create a new script.
    • υUsing the Outlook client, select the CIReceive public folder.
    • υOn the File menu, click Properties.
    • υClick the Agents tab, and then click New.
    • υType a name for the new agent.
    • υSelect the event A new item is posted in the folder to enable the agent to respond when a new item is posted.
    • υClick Edit Script. If Microsoft® Visual InterDev™ is installed, it is started with a blank script that you can edit. If it is not installed, Notepad is started with a blank script.
    • υCopy the Visual Basic script from \Microsoft Site Server\SiteServer\Commerce\recvsmtp.vbs, and then paste it into the blank file. Make any desired changes, and then save the file and exit from Visual InterDev or Notepad.
    • υClick OK to save the new agent.


Microsoft Transaction Server and the Commerce Interchange Pipeline

A Microsoft® Transaction Server (MTS) transaction is a unit of work that is performed as an atomic operation. In the Active Server Pages (ASP) environment, transactions occur on a per-page level. To mark an ASP as one that requires a transaction, you include the following script at the top of the page:

<%@ LANGUAGE=VBScript Transaction=Required%>

When you mark a page as transacted, all of the work that occurs on that page becomes part of the same transaction context. The objects that are created on the page, and the work performed by those objects, become part of that transaction context, provided that those objects are registered on the server system as MTS components. In the event of an error, the work performed by those objects can be rolled back, and the objects rendered stateless.

Suppose, for example, that you create a page that includes an object that uses the Active Data Objects (ADO) to insert or update data in a database. In the event that this component fails, you can call the MTS ObjectContext object’s SetAbort method to abort the transaction in which that object participates, and all of the modifications made by the object to the database are rolled back.

Commerce Interchange Pipelines and Microsoft Transaction Server

Neither SMTP nor HTTP are transacted protocols. Therefore, an MTS-based transaction cannot pass over these protocols. A CIP that uses the SendSMTP or SendHTTP components can create transactions that span the transmit side and the receive side respectively, but that do not span the Internet protocol used. Instead, there is one transaction context on the transmit side and another transaction context on the receive side. DCOM, however, is a protocol that supports MTS, and thus a single transaction context can span both the transmit and receive sides of the CIP.


The MtsTxPipeline Object

The Microsoft® Commerce Server Commerce Interchange Pipeline (CIP) supports MTS transactions through the MtsTxPipeline object. This object is registered as an MTS component during the Commerce Server installation, and is marked as requiring a transaction. If you create an MtsTxPipeline object on a page that is not marked as requiring a transaction, a transaction context is created for the MtsTxPipeline object, and the components that execute within that pipeline do so as part of a single, atomic operation. If you create an MtsTxPipeline object on a page marked as requiring a transaction, the MtsTxPipeline executes as part of the page-level transaction context.

In either case, the MtsTxPipeline object’s transaction support provides a host of benefits to the site builder. First, and most importantly, transaction support means that if any component in an MtsTxPipeline fails, the work of the preceding components in the pipeline is rolled back, and the MtsTxPipeline object aborts the transaction.

The MtsTxPipeline object’s transaction support proves particularly beneficial in relation to CIP components such as Audit, which modify the site database. If you use these components, or any other ADO-related order processing pipeline (OPP) component that modifies the database, and the component fails, the modifications that the component makes to the database are automatically rolled back.

Moreover, this behavior holds true, whether or not the page on which you execute the MtsTxPipeline is marked as requiring a transaction. If the page is marked as requiring a transaction, then the object instance that you create participates in that transaction. If the page is not marked as requiring a transaction, one is created for the MtsTxPipeline, and the MtsTxPipeline aborts the transaction in the event of a component failure.


Error Handling

If an error occurs in a Transmit pipeline, such as a Scriptor component with a scripting error, the pipeline returns both an error value and an error description string, such as

80020101: Component Execution failed for component ProgID.Scriptor

If an error is generated in this Receive pipeline on a remote computer, this error is logged to the event log of the remote computer, and the error number is returned to the calling component in the Transmit pipeline.

The error returned by the pipeline may contain sensitive information which should remain in the control of the hosting operation. For this reason, when an error occurs in a Receive pipeline, the error description string is not returned to the Transmit pipeline.


CIP Example: Microsoft Market

The Microsoft® Market sample site illustrates the use of a Commerce Interchange Pipeline (CIP) in an extended, practical example. Microsoft Market is a business-to-business site demonstrating internal corporate purchasing, based on Microsoft’s own internal corporate purchasing site. The application enables employees to order office supplies from their desktop using a Web browser. The result of the shopping process is the generation and transmission of a purchase order to the vendor that supplies the goods.

This section illustrates how the Market site uses a Commerce Interchange Pipeline (CIP) transmit pipeline to transmit a purchase order by HTTP.

A Pipeline Within a Pipeline

In most Commerce Server sites, the final purchase is processed by an OPP running a purchase configuration. Microsoft® Market follows the same model. In this case, the purchase configuration file is called SubmitViaInterchange.pcf, which is based on the Corporate Purchasing Submit Pipeline template.

Microsoft Market's SubmitViaInterchange pipeline

This pipeline configuration checks whether the order total requires manager approval and sends mail to the approving manager. If the order is pre-approved, it inserts the requisition in the database and executes a Commerce Interchange Pipeline (CIP) that includes stages for digitally signing and encrypting the requisition and sending it to the vendor using an HTTP post.

As the following figure illustrates, three pipelines are involved. Within the OPP, a CIP is created to perform the business-to-business transaction.

Microsoft Market's OPP and CIP pipelines

The outer pipeline executes the Scriptor component that runs TxHTTP.vbs. TxHTTP.vbs, in turn, creates and executes the Commerce Interchange Pipeline. When the Interchange pipeline completes execution, control returns to the outer pipeline. The last component of that pipeline is then executed.

Meanwhile, the purchase order is received on the vendor’s system using HTTP post. (In the sample site, for simplicity of the demonstration, GetOrder.asp is run on the same computer that is hosting Microsoft Market.)

The outer pipeline, the OPP, is created as an MtsTxPipeline object so that all operations within that pipeline are supported as a single transaction by Microsoft® Transaction Server (MTS). The inner pipeline, the Interchange, is created as an MtsPipeline object so that its components run within the same transaction created by the outer pipeline. (If the inner pipeline were created as MtsTxPipeline object, a failure of any process within it would only roll back the processes in the inner pipeline, not in the outer pipeline.)

Creating and Executing the Transmit Pipeline (Config\TxHTTP.vbs)

The Transmit pipeline is created and executed by a Scriptor component running the script TxHTTP.vbs.

The function defined in this script takes four arguments, but only the orderform argument is used in the function. This argument represents the requisition that is being transmitted to the vendor.

Assuming the requisition is pre-approved, the function begins by creating a non-transacted pipeline (mscsMtsPipeline) and loading the InterchangeTransmit.pcf pipeline configuration file. This is the Commerce Interchange Pipeline (CIP).

Next, the function creates a Transport Dictionary to be passed as an argument to the CIP. The Transport Dictionary contains a name/value pair that contains the business data object being sent (in this case, the requisition). In this function, the following phrase adds a value called Object to the Transport Dictionary, and sets this value as the requisition passed into this function:

Set TransportDictionary.object = orderform
Note

Although the Microsoft Market sample uses the name working_data to represent the business data object, the preferred standard convention is to name this value Object. Also, the name object, and not working_data, should be specified as the Object Source Key in the MapToXML component that appears in Microsoft Market’s Transmit pipeline. This documentation uses the correct convention.

The object property is used by the first component in the Interchange Transmit pipeline, MapToXML, which reads the object¸ maps the object to serialized binary form, and writes the result back into the working_data property.

Finally, the function executes the Interchange pipeline’s Execute method, passing the transport dictionary and the PipeContext dictionary as arguments.

Function mscsexecute(config, orderform, context, flags)
mscsexecute = 1
if (not orderform.needapproval) then
    Dim mscsMtsTxPipeline
    Set mscsMtsTxPipeline = CreateObject("Commerce.MtsTxPipeline")

    Dim pathPipeConfig
    REM  -- INTTRANSMIT is used , in global.asa to map the interchange pipeline to the file InterchangeTransmit.PCF.
    pathPipeConfig = context.pipemap("INTTRANSMIT")
    mscsMtsTxPipeline.loadpipe (pathPipeConfig)
    REM -- Comment here to turn logging off
    if (context.logpipeline) then
        call mscsMtsTxPipeline.setlogfile(context.approot + "\data\InterchangeTransmitPipe.log")
    end if

    REM -- create the outer dictionary which the Interchange pipeline components will use as their black-board
    Dim TransportDictionary
    Set TransportDictionary = CreateObject("Commerce.Dictionary")

   Set TransportDictionary.object = orderform

    REM -- for the auditlog
    TransportDictionary("requisitionid") = orderform.requisitionid
    TransportDictionary("insertby") = orderform.insertby
    TransportDictionary("reqemailalias") = orderform.reqemailalias

    Dim ierrorlevel
    REM -- kick off the Interchange pipeline
    On error resume next
    ierrorlevel = mscsMtsTxPipeline.execute(1, TransportDictionary,Context, 0)

    REM -- return any errors from the Interchange pipeline execution
    if (0 <> Err) then
          orderform.[_purchase_errors].Add("#:" & Err.Number & "," & Err.Description)
          mscsexecute = 3
    End if
    on error goto 0

    if (1 < iErrorlevel) and (0 = orderform.[_purchase_errors].Count) then
        orderform.[_purchase_errors].Add(replace(mscsMessageManager.GetMessage("cip_transmit_error"),"%1",ierrorlevel))
    end if

end if
End Function

The Transmit Pipeline Configuration

Microsoft Market’s InterchangeTransmit.pcf pipeline configuration is an example of a Commerce Interchange Transmit pipeline.

Microsoft Market's InterchangeTransmit pipeline

The pipeline begins with the requisition object passed to it in the transport dictionary, and during the course of running the pipeline, various components write new values into the transport dictionary.

The Map stage in this pipeline contains a MapToXML component, which reads the data in the business data object (using the object’s IPersistXML or IPersistStreamInit implementation), and writes the data as an XML-enclosed binary stream or as pure XML data to the working_data name/value pair.

The Digitally Sign and Encrypt stages in this pipeline are empty so that the Market sample site will work even on servers that do not have installed the certificates that these components require.

The Transport stage contains the SendHTTP component, which send the business data object as an argument to an HTTP request.

When the pipeline has completed execution, the transport dictionary is automatically destroyed (although the original order form object remains).

GetOrder.asp

Getorder.asp is the page that is run on the vendor system to receive the requisition posted by HTTP.

The TxHTTP.vbs script previously described creates a transport dictionary to pass the order form to the InterchangeTransmit pipeline. This Dictionary initially contains the order form object, and is used by other components in the CIP Transmit pipeline to write intermediate values.

Similarly, the script in GetOrder.asp creates a transport dictionary, which it passes as an argument to the pipeline. This script uses the request.form method to retrieve the information posted to the page using HTTP, and creates a name/value pair in the transport dictionary (called Text) to contain this text.

Next, this script creates a transacted pipeline (mscsMtsTxPipeline) and loads the Receive.pcf pipeline configuration.

<!-- #include file="include/shop.asp"-->
<!-- #include file="include/utility.asp"-->

<html>
<head>
    <!-- #include file="include/standardhead.asp"-->
</head>
<body>
<%
   REM -- receive the orderform that is posted thru HTTP.
   Dim TransportDictionary
   set TransportDictionary = server.createobject("commerce.dictionary")
   TransportDictionary.working_data = request.form

   Dim mscsMtsTxPipeline
   set mscsMtsTxPipeline = server.createobject("commerce.MtsTxPipeline")

   REM -- Get the name of the Commerce Interchange Pipeline using INTRECEIVE to key into the pipemap dictionary.
   REM -- INTRECEIVE maps to /market/config/InterchangeReceive.pcf in global.asa
   call mscsMtsTxPipeline.loadpipe(pipemap("INTRECEIVE"))

   if (logpipeline) then
        call mscsMtsTxPipeline.setlogfile(Request.ServerVariables("APPL_PHYSICAL_PATH") + "/data/InterchangeReceivePipe.log")
   end if

   Dim ierrorlevel,context
   set Context = server.createobject("commerce.dictionary")
   Context.DefaultConnectionString = MSCSSite.DefaultConnectionString
   Context.SiteName = MSCSSite.DisplayName
   set Context.CIP_receiveerrors = Server.CreateObject("Commerce.SimpleList")
   set Context.CIP_receiveDBerrors = Server.CreateObject("Commerce.Dictionary")

   on error resume next
   ierrorlevel = mscsMtsTxPipeline.execute(1, TransportDictionary, Context, 0)

   REM -- Errors are logged to the W3SVC error logs. In order for the specified string to be recorded in the log file,
   REM -- select the URI Query option of the Extended Logging Properties sheet for the site.

   Dim ErrNumber, ErrText, iError
   ErrNumber = Err.Number    REM -- store the errors if any, and display if no errors raised by other pipeline components.
   ErrText = Err.description
   on error goto 0

   for each iError in Context.CIP_receiveDBerrors
        Response.AppendToLog(Context.CIP_receiveDBerrors(iError))
   next

   for iError = 0 to Context.CIP_receiveerrors.Count - 1
        Response.AppendToLog(Context.CIP_receiveerrors(iError))
   next

   if (0 = Context.CIP_receiveDBerrors.count) and (0 = Context.CIP_receiveerrors.count) and (0 <> ErrNumber) then
        Response.AppendToLog("#:" & ErrNumber & "," & ErrText)
   end if

   if (1 < iErrorlevel) then
        Response.AppendToLog(E_PIPELINE_ERRORLEVEL)
   end if

%>
</body>
</html>

The Receive Pipeline Configuration

Microsoft Market’s InterchangeReceive.pcf pipeline configuration is an example of a Commerce Interchange Receive pipeline.

Microsoft Market's InterchangeReceive pipeline

Essentially, this pipeline performs the opposite actions of the Commerce Interchange Transmit pipeline, and in reverse order. Specifically, the pipeline contains the following stages and components.

The Decrypt and Verify Digital Signature stages are empty, because the object was not encrypted or digitally signed when transmitted.

In the Map stage, the MapFromXML component converts the binary stream to a Transport Dictionary, the OBJECT name/value pair of which references the business data object (an OrderForm).

In the Application Integration stage, a Scriptor component (VendorPOAccept.vbs) writes the values from the OrderForm object to the vendor’s database.


Appendix A: Implementing IPersistXML, IPersistStreamInit, or IPersistStream

If you are using the Commerce Interchange Pipeline (CIP) MapToXML and MapFromXML components, then the OBJECT name/value pair in the Transport Dictionary must reference an object that implements IPersistXML, IPersistStream, or IPersistStreamInit interface. The Commerce Server SimpleList, Dictionary, and OrderForm objects implement these interfaces.

If you map a business data object as binary data, the CIP mapping components check to see if the business data object implements IPersistStream or IPersistStreamInit. Although there is no limit on how deeply objects referenced within the business data object may be nested, both the root object and all nested object must implement one of these interfaces, or an error is raised.

If you map a business data object as XML, the CIP mapping components first attempt to get the business data object’s implementation of IPersistXML. If the object does not support IPersistXML, the mapping components attempt to get the business data object’s IPersistStreamInit or IPersistStream implementation (in that order). If the object (or nested object) implements one of these interfaces, the mapping component uses that implementation to save/load the object and its direct links to other objects. In this case also, there is no limit on how deeply objects referenced in the business data object can be nested.

If you use a SimpleList, OrderForm, or Dictionary, be aware that these object’s implementations of IPersistXML/IPersistStreamInit do not persist the following types of data:

  • υError Objects
  • υVARIANTs of type VT_EMPTY or VT_NULL.
  • υReferences.
  • υSAFEARRAYs.
  • υSub-objects that do not themselves implement IPersistXML or IPersistStreamInit. For example, if a name/value pair in a Dictionary references an object that does not support one of these interfaces, the Dictionary will be mapped, but the referenced object’s data will not.


CIP Component Reference

The following components are commonly run in the Commerce Interchange Pipeline (CIP).

  • υAddHeader
  • υAudit
  • υAuditReceipt
  • υBinaryFromText
  • υBinaryToText
  • υDecryptPKCS
  • υDecodeMIME
  • υDecodeSMIME
  • υDigitalSig
  • υEncryptPKCS
  • υEncodeMIME
  • υEncodeSMIME
  • υGenerateReceipt
  • υMakePO
  • υMapFromXML
  • υMapToXML
  • υOpenHeader
  • υPipetoPipeTransfer
  • υSendDCOM
  • υSendHTTP
  • υSendSMTP
  • υVerifyDigitalSig
  • υ
  • υ


Pipeline Component Reference

The following topics describe the usage of each of the order processing and Commerce Interchange Pipeline components.


AddHeader

The AddHeader component appends a series of XML tags to the value of working_data. This XML data consists of a transaction ID (a globally unique identifier (GUID) that uniquely identifies the transaction), the date and time on which the transaction occurred, and an optional return receipt request.

  • υInput Field. Specifies the name of the field on the Transport Dictionary from which the business data object is read.
  • υOutput Field. Specifies the name of the field on the Transport Dictionary to which the XML-formatted business data object is written.

AddHeader adds the following information to the XML header.

AddHeader adds the date and time (Universal Coordinated Time) of the transmission using the <UTCDATETIME></UTCDATETIME> tags.

If the Transport Dictionary contains any of the name/value pairs listed in the following table, then AddHeader writes these values as XML into the header.

Name/value pair name | Description | Example value | XML added to header
Document_Type Tag describing the type of business object being transmitted PO <DOCUMENTTYPE>PO
</DOCUMENTTYPE>
Document_Source | Tag describing the source of the business object, usually the name of the company transmitting it. | Volcano Coffee | <DOCUMENTSOURCE>Volcano Coffee</DOCUMENTSOURCE>
Document_Destination Tag describing the destination of the business object, usually the name of the company receiving it. Cascade Coffee Roasters <DOCUMENTDESTINATION>
Volcano Coffee
</DOCUMENTDESTINATION>

AddHeader checks whether the Receipt_requested name/value pair exists and has a value of Yes. If it does, AddHeader appends the following XML items to the data.

  • υThe algorithm to be used to hash the business object data to derive a digest. This value is always SHA1. (SHA1 is a standard hash algorithm.)
  • υA document type tag that identifies the kind of document requested from the receiving pipeline. This value is always Receipt, indicating that a receipt is requested.

This information appears in the XML header as the following:

<RETURNREQUEST>
    <DIGESTALGORITHM>
        SHA1
    </DIGESTALGORITHM>
    <DOCUMENTTYPE>
        Receipt
    </DOCUMENTTYPE>
</RETURNREQUEST>

Finally, AddHeader adds a transaction ID to the header. The transaction ID for a transaction is a string of data that uniquely identifies the transaction. If the transport dictionary contains a name/value pair named txid, then AddHeader writes this value. Otherwise, AddHeader generates a globally unique ID (GUID), and writes a string representation of that GUID to the txid name/value pair. In either case, AddHeader appends the transaction ID to the XML header in the form <TRANSACTIONID>transactionid</TRANSACTIONID>.

Example

In this example, a transport dictionary has been created and given the following values, in addition to the business object in working_data:

transportDictionary.Value("Receipt_Requested") = "Yes"
transportDictionary.Document_Type = "PO"
transportDictionary.Document_Source = "Volcano Coffee"
transportDictionary.Document_Destination = "Cascade Coffee Roasters"

In this example, no transaction ID is supplied initially, so that the ID is generated by the AddHeader component.

The AddHeader component produces the following XML:

<UTCDATETIME>4/27/98 1:42:28 PM</UTCDATETIME>
<DOCUMENTDESTINATION>Cascade Coffee Roasters</DOCUMENTDESTINATION>
<DOCUMENTSOURCE>Volcano Coffee</DOCUMENTSOURCE>
<DOCUMENTTYPE>PO</DOCUMENTTYPE>
<RETURNREQUEST>
<DIGESTALGORITHM>SHA1</DIGESTALRORITHM>
<DOCUMENTTYPE>Receipt</DOCUMENTTYPE>
</RETURNREQUEST>
<TRANSACTIONID>94htns70082p12noklmq3vhqu0</TRANSACTIONID>
<OBJECTDATA>
    <MAPXML ( XML text written by MapToXML)
    </MAPXML>
</OBJECTDATA>

Related Topics

  • υOpenHeader
  • υGenerateReceipt


Audit

The Audit component, which usually appears in the Audit stage of a Commerce Interchange Pipeline, writes the specified values from the Transport Dictionary into a database table in the audit database.

  • υConnection String. Specifies the connection string used for connecting to the database into which the audit data is saved. The connection string must include either the full connection string (the DSN, database login ID, and database password) or the name of a named connection stored in the connection map.
  • υTable. Specifies the name of the database table into which the audit data is saved. This table must exist in the database identified by the connection string.
  • υAdd a field. Specifies the name of a field that the Audit component reads from the Transport Dictionary. This name must exactly match the name of a column that exists in the database table identified in the Table field. If the field exists on a child object, the name to be added must be a fully qualified path (for example, object1.field). Column names must be unique, otherwise the component takes only the first instance of the field name. Type the name, and then click Add to add the column to the Fields to record list.
  • υFields to record. Lists the names of the optional fields on the Transport Dictionary that the Audit component will write to the database table identified in the Table field, in addition to those fields written be default (as described later in this topic). To add a name, type the name in the Add a field box, and then click Add. To remove a name, select it, and then click Remove.

Remarks

The Audit component always writes the values of the following name/value pairs in the Transport Dictionary into columns in the database with the same names:

Name | Description
txid | Transaction ID. A name/value pair originally written to the Transport Dictionary by the transmitting application or by the AddHeader component in the Transmit pipeline. (Must be the primary key in the database table).
utc_datetime | Time (Universal Coordinated Time) when the Audit component runs.

In addition, the Audit component writes the values of the following name/value pairs in the Transport Dictionary, if they exist, into columns in the database with the same names:

Name | Description
receipt_requested | Optional name/value pair originally written to the Transport Dictionary by the transmitting application, indicating a request for the receiving application to send a receipt.
AppID | Application ID. An optional name/value pair originally written to the Transport Dictionary by the transmitting application, usually indicating the programmatic ID (progID) of the transmitting application.
return_receipt_request | Optional name/value pair written to the Transport Dictionary by the OpenHeader component, containing the hashing algorithm (<DIGESTALGORITHM>) and the type of receipt document requested (<DOCUMENTTYPE>).
msg_digest | Digest (hash) of the business data object written to the Transport Dictionary by OpenHeader.
document_type | Optional. Description of the type of business object being transmitted.
document_source | Optional. Description of the source of the business object, usually the name or address of the company transmitting it
document_destination | Optional. Description of the destination of the business object, usually the name or address of the company receiving it.
send_datetime | The date and time of the OpenHeader operation.

When using the Audit component, observe the following notes:

  • υEach column in the table must be one of the default columns or have a corresponding entry in the Fields to record list.
  • υEach column in the table must allow nulls to be inserted.
  • υValues that contain text, where the text includes a single-quote (') character, cannot be logged by the Audit component.

For an example of this component, see the Commerce Interchange Transmit pipeline used by the Microsoft Market sample site (Inetpub\Wwwroot\Market\Config\InterchangeTransmit.pcf).

Related Topics

  • υAuditing
  • υAuditReceipt
  • υ Commerce Server Connection Strings
  • υ Changing the Default Connection String From MMC
  • υ Changing the Default Connection String From WebAdmin


AuditReceipt

The AuditReceipt component, which usually appears in the Audit stage of a Commerce Interchange Pipeline, writes data from the receipt into the specified database table. These elements include the date and time of the receipt request, a digest of the receipt, the algorithm used to hash the working data to produce the digest, the return request document type, and the transaction ID.

  • υInput Field. Specifies the name of the field on the order form from which the component reads the receipt data.
  • υConnection string. Specifies the connection string used for connecting to the database. The connection string must include either the full connection string (the data source name (DSN), database login ID, and database password) or the name of a named connection stored in the connection map.
  • υTable. Specifies the name of the database table into which the component will save the receipt data.

Remarks

The AuditReceipt component is usually used by the original sender of the business data object in a Receive pipeline. AuditReceipt is the counterpart to the GenerateReceipt component in the recipient’s Receive pipeline.

The following table shows the information that is inserted into the specified table, and the required name of the corresponding column.

Receipt information | Required column in database
The return request transaction ID. | txid
The date/time written by GenerateReceipt. | receive_datetime
A digest of the receipt. | receive_msg_digest
The algorithm used to hash the working data to produce the receipt. | receive_digest_algorithm
The return request document type. | document_type

The Receipt Audit component assumes that these columns are formatted to contain text data.

If the component’s attempt to insert the data fails (for example, due to a primary key violation) the component updates the record.

Related Topic

  • υGenerateReceipt
  • υReceipt Request and Generation


BinaryFromText

The BinaryFromText component converts ASCII-encoded data in an HTTP request (or other text transport protocol such as SMTP) to the binary form required by the DecryptPKCS or VerifyDigitalSig components. The BinaryFromText component restores binary data that was originally encoded to ASCII by the BinaryToText component.

  • υSource Text Field. Specifies the name of the field on the Transport Dictionary whose ASCII text value is to be converted to binary form.
  • υDestination Binary Field. Specifies the name of the field on the Transport Dictionary to which the binary data will be written.


BinaryToText

The BinaryToText component encodes binary data to ASCII text so that it can be transmitted by an appropriate transport protocol. (Because the SendHTTP and SendSMTP components can perform this conversion automatically, BinaryToText is not needed when using these transport protocols.)

  • υSource Binary Field. Specifies the name of the field on the Transport Dictionary whose binary value is to be encoded as ASCII text.
  • υDestination Text Field. Specifies the name of the field on the Transport Dictionary to which the ASCII-encoded text will be written.

Use the BinaryFromText component to restore the data to its original form.

Related Topic

  • υBinaryFromText


DBOrderPromo

The DBOrderPromo component, which usually appears in the Order Adjust Price stage of an order processing pipeline, runs a query to retrieve data about promotions from the database and then adjusts the item price accordingly.

Note

This component is used for compatibility with Commerce Server version 2.0 sites, in which the database connection is provided by the Content object in the Pipe Context. Commerce Server 3.0 sites should use the DBOrderPromoADO component.

  • υQuery. Specifies either the full SQL text of the query that is executed by this component or the name of a query whose full SQL text is stored in the Content object.

This query must return at least the following database columns:

  • υcond_column. Name of the item attribute against which the promotion condition is checked. If it is a promotion on hats, then this would be set to the name of the column that stores the product description (for example, _product_type).
  • υcond_op. Comparison operator that compares cond_column with cond_value; for example = or <>.
  • υcond_value. Value indicating the item being promoted; for example, hats. If this value is a number, it must be an integer value; floating point numbers (for example, 10.0) are not accepted.
  • υcond_all. Optional field. If set to 1 (True), then any product in the set of products to be purchased will trigger this promotion. Otherwise, this promotion will be triggered only by products that meet the criteria defined in cond_column, cond_op, and cond_value (the condition set). Products are removed from the condition and award sets after they have been involved in a promotion , in order to prevent a single product from being a participant in multiple promotions.
  • υaward_column. Value indicating the award criterion.
  • υaward_op. Comparison operator that compares award_column with award_value; for example = or <>.
  • υaward_value. Indicates the item being awarded, for example, gloves.
  • υaward_all. Optional field. If set to 1 (True), then the award can be applied to any product. Otherwise, this award will be applied only to products that meet the criteria defined in award_column, award_op, and award_value (the award set).
  • υshopper_column. Value indicating the shopper-specific information; can be @ (a wildcard value) indicating that all shoppers are eligible for the promotion.
  • υshopper_op. Should be set to = if a shopper is specified; otherwise, it is @.
  • υshopper_value. Value indicating the type of shopper; if it is any shopper, set it to @.
  • υshopper_all. Optional field indicating whether this promotion is available to all customers. If this value is 0 (False), the promotion is available only to customers who meet the criteria defined in shopper_column, shopper_op, and shopper_value.
  • υcond_min.Value, in cents (or other currency unit), or a number of units of the minimum purchase necessary to be eligible for the promotion. The interpretation of cond_min depends on cond_basis.
  • υcond_basis. Value indicating whether cond_min is measured in price or quantity (P or Q, respectively).
  • υaward_max. Size of the award set.
  • υdisc_value. Number indicating the amount of the discount.
  • υdisc_type. Type of discount, either % or $.
  • υdate_start. Optional field. Date the promotion begins, at one second after midnight.
  • υdate_end. Optional field. Date the promotion ends, at one second after midnight. Because date_start and date_end are actually date/time pairs that specify midnight, date_end excludes the date specified. Thus, if you want the last day of a sale to be 3/31, be sure to specify that the sale ends on 4/1.

Remarks

An order promotion has three criteria: the customer criterion, a condition criterion, and an award criterion. If the customer does not match the customer criterion, the promotion is not applied. If the customer does match the customer criterion, then the other two criteria are applied to all the items in the order, producing two sets: the condition set (those matching the condition criterion) and the award set (those matching the award criterion).

For example, if the promotion is Buy $100 in hats, get a free pair of gloves, the condition set is all of the hats the customer bought, and the award set is the gloves the customer will receive for free. Often, the same item is in both sets.

The condition set must be of some minimum size ($100 in this example). This is given by two variables: cond_min (10000 in this case, because the value is given in cents) and cond_basis (P in this case, meaning that size is measured by price and not by quantity).

The award set is limited to a maximum size (one in the example); this size is always measured in quantity:

  • A maximum of 0 means no maximum; thus, if a customer meets the qualifications, discount on as many of the award items as the customer chooses to purchase. In this example, that would mean Buy $100 in hats, get as many free pairs of gloves as you want.
  • If the size of the condition set doubles (or triples or quadruples), the maximum size of the award is similarly multiplied. In this example, if the customer buys $500 worth of hats, the customer gets five free pairs of gloves.

There are two types of discounts (specified by the value disc_type):

  • υPercentage. Where disc_type is % and disc_value is interpreted to mean percentage.
  • υCents off. Where disc_type is $ and disc_value is interpreted to mean number of currency units off each product in the award set.

The preceding example has the values set as follows.

Field | Value
cond_column | _product_type
cond_op | =
cond_value | hat
award_column | _product_type
award_op | =
award_value | gloves
shopper_column | @
shopper_op | @
shopper_value | @
cond_min | 10000
cond_basis | P
award_max | 1
disc_value | 100
disc_type | %

Note

A given product can be adjusted only once. For this reason, the order in which promotions are applied is important. For example, if you apply a query that returns two rows from a promotion table, only the first promotion will be applied.

Related Topic

  • υDbOrderPromoADO


DBOrderPromoADO

The DBOrderPromoADO component, which usually appears in the Order Adjust Price stage of an order processing pipeline, runs a query to retrieve data about price promotions from the database and then adjusts item prices accordingly.

  • υQuery. Specifies either the full SQL text of the query that is executed by this component or the name of a query whose full SQL text is defined in the site’s Global.asa file.
  • υConnection string. Specifies the connection string used for connecting to the database. The connection string must include either the full connection string (the data source name (DSN), database login ID, and database password) or the name of a named connection stored in the connection map. If this field is blank, the default connection string is used.

Remarks

The DBOrderPromoADO component executes a query to determine if the promotional conditions defined in a database table have been met by items in the OrderForm. If they have, DBOrderPromoADO applies the promotion to the OrderForm by initializing the item._oadjust_adjustedprice and item._n_unadjusted name/value pairs for the item affected by the promotion.

The item._oadjust_adjustedprice name/value pair reflects the total cost of a given item, adjusted for promotions. The item._n_unadjusted name/value pair contains the number of items that were not affected by the promotion.

Suppose, for example, that you define a promotion in which a customer who purchases one of Item A gets one of Item B at half-price. Suppose further that the following conditions exist.

  • υThe customer has purchased one of Item A.
  • υThe customer has purchased three of Item B.
  • υItem B has a regular price of 1.00.

When the DBOrderPromoADO component is run, the user will, by the terms of the promotion, get two of the items at the regular price of one dollar. However, the customer will get the third item at fifty percent off. Thus, the item._oadjust_adjustedprice for Item B will equal 2.50 cents.

In addition, because only one of the three Item B products will have been promotionally adjusted, the item._n_nadjusted name/value pair will be initialized to two. This initialization is critical, because once an item has had its price adjusted, the price cannot be adjusted again.

In this example, one of Item B had its price adjusted. The other two Item B items did not. Consequently, no matter how many of the three items qualify for a promotional adjustment under a later DBOrderPromoADO component, only the two previously unadjusted Item B items can be adjusted.

For detailed information about using this component, see Price Promotions.

The Promotions Table

Because the DBOrderPromoADO component expects the query that you supply to reference a specific group of table columns, the table in which you store promotions must have a given structure.

The database query must return at least the following columns:

cond_column. Contains the name of the item attribute against which the promotion condition is checked. For example, in the Volcano Coffee sample site’s vc30_promo_price table, this column contains the value _product_pfid, indicating that this name/value pair on the item Dictionary will be evaluated for each item in the items list.

cond_op. A comparison operator that compares cond_column to cond_value; for example = or <>.

cond_value. A value that identifies the item being promoted. For example, in the Volcano Coffee site, the cond_column is _product_pfid, the cond_op is “=” and the cond_value is 22. If an item in the items list has a _product_pfid that evaluates to 22, that item meets the condition set.

If this value is a number, it must be an integer value; floating point numbers (for example, 10.0) are not accepted.

cond_all. Optional field. If set to 1 (True), any product in the set of products to be purchased will trigger this promotion. Otherwise, this promotion will be triggered only by products that meet the criteria defined in cond_column, cond_op, and cond_value (the condition set). Products are removed from the condition and award sets after they have been involved in a promotion to prevent a single product from being a participant in multiple promotions.

award_column. The award_column, coupled with the award_op and award_value, define the award set for the promotion. The award column contains a value indicating the name/value pair that defines the award criteria.

For example, in the Volcano Coffee sample site’s vc30_promo_price table, this column contains the value _product_dept_id, the award_op column contains “=”, and the award_value column contains 2.

This means that if the condition set is met, then _product_dept_id is evaluated for each item in the items list. If a product in the items list contains a _product_dept_id name/value pair with a value of 2, then the promotion applies to that item.

award_op. Comparison operator that compares award_column with award_value; for example = or <>.

award_value. Indicates the value of the element referenced by award_column.

award_all. Optional field. If set to one (True), then the award can be applied to any product. Otherwise, this award will be applied only to products that meet the criteria defined in award_column, award_op, and award_value (the award set).

shopper_column. Value indicating the customer-specific information; can be @ (a wildcard value) indicating all customers are eligible for the promotion.

shopper_op. Should be set to = if a customer is specified; otherwise, it is @.

shopper_value. Value indicating the type of customer; if it is any customer, set it to @.

shopper_all. Optional field indicating whether this promotion is available to all customers. If this value is 0 (False), the promotion is available only to customers who meet the criteria defined in shopper_column, shopper_op, and shopper_value.

cond_min. A value, in cents (or other currency unit), or a number of units of the minimum purchase necessary to be eligible for the promotion. The interpretation of cond_min depends upon the value referenced in cond_basis. For example, if cond_basis contains “P”, cond_min is assumed to measure price. If cond_basis contains “Q”, cond_min is assumed to measure quantity.

cond_basis. Value indicating whether cond_min is measured in price or quantity (P or Q, respectively).

award_max. Size of the award set.

disjoint_cond_award. A number (1 or 0) indicating whether the award can be disjointed. If the value is 0, the award is disjointed; otherwise, it is not. The term disjointed, in this context, refers to whether or not an item can promote itself. Where the condition set and the award set do not refer to the same item, this value is ignored.

Suppose, for example, that you have a promotion that dictates that if you purchase one of Item A, you get one of Item A at fifty percent off.

If the award is not disjointed (disjoint_cond_award is equal to 0), then a customer needs only to purchase one of Item A to get that item at fifty percent off. If the award is disjointed (disjoint_cond_award is equal to 1), then a customer purchasing Item A will get a second Item A at fifty percent off, but will receive no discount until the second item is added to the basket.

disc_value. Number indicating the amount of the discount.

disc_type. Type of discount, either % or $.

date_start. Optional field. The date the promotion begins, at one second after midnight.

date_end. Optional field. The date the promotion ends, at one second after midnight. Because date_start and date_end are actually date/time pairs that specify midnight, date_end excludes the date specified.

Connection String. The data source name (DSN) connection string to be used to connect to the database.

An order promotion has three criteria: the customer criterion, a condition criterion, and an award criterion. If the customer does not match the customer criterion, the promotion is not applied. If the customer does match the customer criterion, then the other two criteria are applied to all the items in the order, producing two sets: the condition set (those matching the condition criterion) and the award set (those matching the award criterion).

Related Topics

  • υ Price Promotions
  • υ Commerce Server Connection Strings


DecodeMIME

The DecodeMIME component decodes a business data object that was encapsulated in the MIME format.

  • υRead From Field. Specifies the name of the field on the Transport Dictionary from which the encoded data is read.
  • υWrite To Field. Specifies the name of the field on the Transport Dictionary to which the decoded data is written.


DecodeSMIME

The DecodeSMIME component decodes a business data object that was encapsulated in the S/MIME (secure MIME) format.

  • υRead From Field. Specifies the name of the field on the Transport Dictionary from which the encoded data is read.
  • υWrite To Field. Specifies the name of the field on the Transport Dictionary to which the decoded data is written.
  • υWrite Signature Certificate To Field. Specifies the name of the field on the Transport Dictionary to which the name of the signature certificate is written.
  • υWrite Crypt Certificate To Field. Specifies the name of the field on the Transport Dictionary to which the name of the certificate used for decryption is written.


DecryptPKCS

The DecryptPKCS component decrypts a business data object that was encrypted using the Public Key Crypto System (PKCS) security standard.

  • υEncrypted Text Field. Specifies the name of the field on the Transport Dictionary from which the encrypted data is read.
  • υPlain Text Field (decrypted). Specifies the name of the field on the Transport Dictionary to which the decoded data is written.
    • υText Output. Specifies that the decrypted data should be saved as text (its original format) rather than binary data.
  • υWrite certificate used for decryption to field. Specifies the name of the field on the Transport Dictionary to which the component writes the name of the certificate that was used for decrypting the business data object.

The DecryptPKCS component decrypts the object, writes the result to the specified plain text field, and writes the status to the specified decryption status field.

By default, the encrypted text field is stored in the working_data name/value pair on the Transport Dictionary. The contents of this field, once decrypted, are used to overwrite the encrypted data in the working_data name/value pair.


DefaultHandling

The DefaultHandling component, which usually appears in the Handling stage of an order processing pipeline, sets _handling_total to zero (0).


DefaultItemPrice

The DefaultItemPrice component, which usually appears in the Item Price stage of an order processing pipeline, initializes the _iadjust_regularprice name/value pair for each item in the items list, provided this name/value pair is not already set.

The name/value pair is initialized to the value stored in _product_list_price. This name/value pair, initialized during the Product Info stage, contains the latest price information for the given item.

Note

If the product table does not contain a column named list_price, or if the Product Info stage’s QueryProdInfo or QueryProdInfoADO components do not retrieve the value of the list_price column in your product table, the item Dictionary will not contain _product_list_price name/value pair. In this case, you need to remove the DefaultItemPrice component from this stage, and include a component (a Scriptor, for example) that explicitly initializes the _iajdust_regularprice name/value pair. Stages that follow the Item Price stage in the pipeline contain components that depend upon _iadjust_regularprice having been set. If this name/value pair is not set, these components fail.


DefaultOrderSubtotal

The DefaultOrderSubtotal component, which usually appears in the Order Subtotal stage of an order processing pipeline, calculates the subtotal for an order and stores the resulting value in the order._oadjust_subtotal member of the OrderForm. This value represents the sum of the item._oadjust_adjustedprice name/value pair for every item in the OrderForm’s items SimpleList.


DefaultPayment

The default component, which usually appears in the Payment stage of an order processing pipeline, sets _payment_auth_code to FAITH.


DefaultShipping

The DefaultShipping component, which usually appears in the Shipping stage of an order processing pipeline, ensures the integrity of the shipping cost by setting order._shipping_total to zero (0).


DefaultShopperInfo

The DefaultShopperInfo component, which usually appears in the Shopper Information stage of an order processing pipeline, retrieves the values stored in the Pipe Context’s Shopper Dictionary, creates corresponding entries in the OrderForm’s order Dictionary, and initializes these new entries to contain the values read from the Shopper Dictionary. The OrderForm entries written by DefaultShopperInfo are prefixed with _shopper_, followed by the name of the entry in the Shopper Dictionary. Finally, the appropriate _shopper entry is initialized to contain the corresponding value from the source Dictionary.

The following example, from the Volcano Coffee sample site, illustrates this operation.

When a customer of the Volcano Coffee site adds an item to his or her basket, the OrderFormPurchase function is called. This function, which is defined in the xt_orderform_purchase.asp file, retrieves a DBStorage object that represents shopper storage, and then uses that object to retrieve information on the current shopper:

REM Create a Storage object for the shopper information
Set mscsShopperStorage = UtilGetShopperStorage()

REM Get the shopper from the shopper storage
on error resume next
set mscsShopper = UtilGetShopper(mscsShopperStorage)
on error goto 0

The DBStorage object returned by UtilGetShopperStorage has been configured to query vc30_shopper table. The vc30_shopper table has the following structure.

The vc30_shopper table

The call to UtilGetShopper returns a Dictionary that contains all of the columns in this table for the current customer. Finally, the function calls the UtilGetPipeContext function to retrieve the pipe context, and explicitly initializes the Pipe Context’s Shopper name/value pair to reference the Dictionary returned by UtilGetShopper:

REM Create the basic pipe context
set mscsPipeContext = UtilGetPipeContext()

REM Add necessary data to the pipe context
set mscsPipeContext.Shopper = mscsShopper

After the pipe has been executed, the OrderForm contains the following name/value pairs:

order._shopper_shopper_id
order._shopper_created
order._shopper_name
order._shopper_password
order._shopper_street
order._shopper_city
order._shopper_state
order._shopper_zip
order._shopper_country
order._shopper_phone
order._shopper_email


DefaultTax

This component, which usually appears in the Tax stage of an order processing pipeline, sets order._tax_total and order._tax_included to zero (0).

Related Topics

  • υUsing the Tax Components


DefaultTotal

This component, which usually appears in the Order Total Stage of an order processing pipeline, verifies that the _oadjust_subtotal, _shipping_total, _tax_total, and _handling_total values on the order have been set. If they have not been set, and error is raised. If they have, these four values are added together, and the sum is stored in the order._total_total name/value pair.


DigitalSig

The DigitalSig component, which usually appears in the Digitally Sign Stage of a Commerce Interchange Transmit pipeline, digitally signs the message. The component creates a message digest using the hash function and then encrypts the digest using a certificate. The component encodes both the signature and the message or only the signature, and then writes the encoded data to the Transport Dictionary.

  • υSignature and Message in XML Format. Specifies that both the digital signature and the original message will be formatted using XML before being written back to the Transport Dictionary.
  • υSignature and Message in PKCS7 Format. Specifies that both the digital signature and the original message will be formatted using the Public Key Crypto System (PKCS) before being written back to the Transport Dictionary.
  • υSignature Only in PKCS7 Format. Specifies that only the digital signature (and not the original message) will be formatted using the Public Key Crypto System (PKCS) before being written back to the Transport Dictionary.
  • υInput Field. Specifies the field in the Transport Dictionary from which the DigitalSig component reads the data that is to be digitally signed. The default value is working_data.
  • υSigned Output Field. Specifies the field in the Transport Dictionary to which the DigitalSig component writes the encoded, signed data.
  • υHash Algorithm. Specifies which hash algorithm the component is to use. This list displays the hash algorithms installed on your computer.
  • υHash Algorithm ID Field. Specifies the field in the Transport Dictionary to which the DigitalSig component writes the selected hash algorithm.
  • υSigner Certificates. Specifies which certificate the component is to use. This list displays the signature certificates installed on your computer using the Certificate Management Tool (see Importing a Certificate).

Related Topics

  • υVerifyDigitalSig


EncodeMIME

The EncodeMIME component, which usually appears in the Add Header Stage of a Commerce Interchange Transmit pipeline, encodes the business data object into Quoted printable or Base 64, wraps it in MIME, and then writes it back into the Transport Dictionary.

  • υContent Type. Specifies the content type of the source object prior to encoding by the component.
    • υUN/EDIFACT. Specifies that the source data is a UN/EDIFACT-formatted EDI object.
    • υANSIX12 (EDI-X12). Specifies that the source data is an ANSI X12 850-formatted EDI object.
    • υEDI-Consent. Specifies that the source data is an EDI-Consent-formatted object.
  • υContent Encoding. Specifies how the object is to be encoded.
    • υQuoted Printable. Specifies that the component should encode the object as Quoted Printable. This format is generally used when the object does not contain extended characters.
    • υBase64. Specifies that the component should encode the object as Base 64, which supports the extended character set.
  • υRead From Field. Specifies the name of the field on the Transport Dictionary from which the working data is read. The working data has already been converted to text by the Map stage.
  • υWrite To Field. Specifies the name of the field on the Transport Dictionary to which the encoded data is written.

Related Topic

  • υDecodeMIME
  • υEncodeSMIME


EncodeSMIME

The EncodeSMIME component, which usually appears in the Digitally Sign Stage or the Encrypt Stage of a Commerce Interchange Transmit pipeline, encapsulates the business data object in S/MIME (secure MIME) format for transmission in e-mail using an SMTP mail server. The EncodeSMIME component encodes the object using IETF EDIINT draft Internet standard encoding, and then writes it back into the Transport Dictionary.

  • υOperation. Specifies the type of operation that the component will perform on the business data object.
    • υPlain Text. Specifies that the business data object is to be left as plain text.
    • υSign. Specifies that the business data object is to be digitally signed.
    • υEncrypt. Specifies that the business data object is to be encrypted.
    • υSign and Encrypt. Specifies that the business data object is to be both digitally signed and encrypted.
  • υCharacter Set. Specifies the character set to be used to convert the body of the message.
  • υSignature Certificate. Specifies the signature certificate that is to be used to sign the object. This list displays the certificates currently installed on your computer.
  • υEncryption Certificate. Specifies the encryption certificate that is to be used to sign the object. This list displays the certificates currently installed on your computer.
  • υSignature Algorithm. Specifies the signature algorithm that is to be used to sign the object. This list displays the algorithms currently installed on your computer.
  • υEncryption Algorithm. Specifies the encryption algorithm that is to be used to sign the object. This list displays the algorithms currently installed on your computer.
  • υRead From Field. Specifies the name of the field on the Transport Dictionary from which the business data object is read.
  • υWrite To Field. Specifies the name of the field on the Transport Dictionary to which the encoded data is written.

Every time EncodeSMIME executes, it rewrites a file named C:\EncodeSMIME.log containing a copy of the message being generated.

For more information on S/MIME, locate a copy of The S/MIME Version 2 Message Specification on the World Wide Web.

Note

In order for EncodeSMIME to properly support character set conversion, the corresponding Windows NT code page must be installed on the computer. For example, the US version of Windows NT installation does not include the Japanese code page (code page 932), which must be present to convert Unicode to iso-2022-jp. For information on installing a code page, see Knowledge Base article Q164948.

Related Topic

  • υDecodeSMIME


EcryptPKCS

The EncryptPKCS component, which usually appears in the Encrypt Stage of a Commerce Interchange Transmit pipeline, encrypts a business data object using the Public Key Crypto System (PKCS) security standard.

If you want to use a trading partner’s certificate to encrypt a business data object, obtain a certificate chain (.chn) file for an exchange certificate from your trading partner, and import it onto your system. After importing the certificate, you can use it to configure the EncryptPKCS component.

  • υPlain Text Field. Specifies the name of the field on the Transport Dictionary whose value is to be encrypted.
  • υEncrypted Text Field. Specifies the name of the field on the Transport Dictionary to which the encrypted data is written.
  • υEncryption Algorithm. Specifies the encryption algorithm that is to be used to encrypt the object. This list displays the algorithms currently installed on your computer.
  • υReceiver Certificates. Specifies the trading partner certificate from your CA Store that is to be used to encrypt the data.

Related Topic

  • υDecryptPKCS


ExecuteProcess

The ExecuteProcess component runs an executable file.

  • υPath Name of the executable. Specifies the complete path to the executable file that is to be run by this component. To locate the file, click Browse (Win32 only).
  • υArguments to the executable. Specifies the arguments that are to be passed to the executable file. The argument may contain %1, which will be replaced by the name specified in the Field Name of substitutable parameter field.
  • υField Name of substitutable parameter. (Optional) Specifies the name of a field on the OrderForm that is to be substituted for the %1 in the argument that is passed to the executable file.


FixedHandling

The FixedHandling component, which usually appears in the Handling Stage of an order processing pipeline, charges a fixed amount to handle any order. The component sets the value of order._handling_total on the order form to the fixed amount specified in Cost.

  • υKey. (Read-only) The name of a property on the order form used to specify handling method. The value of this property is compared to the string specified in the Method field to determine whether to apply the handling charge to the order.
  • υApply when. Specifies when to apply the handling charge specified in the Cost field.
    • υEqual to Method. Specifies that the value of the Cost field will be applied only if the value of the property specified for Key is the same as the string specified in the Method field.
    • υHas any value. Specifies that the value of the Cost field will be applied when the value of the property specified for Key has any value on the order form. If you select this option, the Method field should be left blank.
    • υAlways. Specifies that the value of Cost is always applied to the order.
  • υMethod. If Equal to Method is selected, specifies a string that the component compares with the value of shipping_method on the order form to determine whether to apply the handling charge to the order. The value of the Cost field will be applied only if there is an exact match.
  • υCost. Specifies the charge that will be applied if the conditions are met. Type the value in the same currency unit in which prices are stored in the database.

Related Topics

  • υComponent Coordination


FixedShipping

The FixedShipping component, which usually appears in the Shipping Stage of an order processing pipeline, sets the value of order._shipping_total to the fixed amount specified in the Cost field.

  • υKey. (Read-only) The name of a property on the order form used to specify shipping method. The value of this property is compared to the string specified in the Method field to determine whether to apply the shipping charge to the order.
  • υApply when. Specifies when to apply the handling charge specified in the Cost field.
    • υEqual to Method. Specifies that the value of the Cost field will be applied only if the value of the name\value pair specified for Key is the same as the string specified in the Method field.
    • υHas any value. Specifies that the value of the Cost field will be applied when the value of the name\value pair specified for Key has any value on the OrderForm. If you select this option, the Method field should be left blank.
    • υAlways. Specifies that the value of Cost is always applied to the order.
  • υMethod. If Equal to Method is selected, specifies a string that the component compares with the value of shipping_method on the order form to determine whether to apply the shipping charge to the order. The value of the Cost field will be applied only if there is an exact match.
  • υCost. Specifies the charge that will be applied if the conditions are met. Type the value in the same currency unit in which prices are stored in the database.

Example

The following example sets the shipping cost to $9.95, shipped by Carrier1.

Field | Value
Apply when | Equal to Method
Method | Carrier1
Cost | 995

When configuring the components in this stage, make sure that the components are specified in the order in which you want them to be executed. For example, if two components specify Carrier2, only the last one will be valid, and will overwrite the first.

Note

You cannot specify more than one method per component; if you need to specify more than one shipping method, add a separate FixedShipping component for each method. For example, in the Pipeline Editor, include three FixedShipping icons to the Shipping stage, and then double-click each and enter the shipping information in each of the resulting properties dialog boxes.

Related Topics

  • υComponent Coordination


FlagInventory

The FlagInventory component, which usually appears in the Inventory Stage of an order processing pipeline, determines whether any items on the order form are out of stock.

  • υDisallow Backorder. If selected, specifies that backorders are not permitted. In this case, the component adds the _pur_out_of_stock message to the _Purchase_Errors SimpleList on the order form as soon as _inventory_backorder is set (is greater than zero). If this value is 0 (the default), or if it is omitted, _inventory_backorder can be set, and no error will be generated.

Remarks

This inventory component verifies that none of the order items have the _product_in_stock value, which corresponds to the in_stock column in the products database table, set to zero (0). If any item does have this field set to zero, FlagInventory sets _inventory_backorder to the quantity ordered (indicating the shortage). If such a shortage occurs and Disallow Backorder is set to one (1), FlagInventory will generate a pur_out_of_stock error in the _Purchase_Errors collection. This component interacts with a manual inventory control process; the product database must be updated to reflect the actual stock on hand.

Note

If you include the FlagInventory component in your pipeline, the product table in the database must contain a column named _in_stock , and the query that is executed in the Product Information stage must return the data from that column, otherwise, the component will fail.

When this component runs, it iterates through the items in the items SimpleList checking the value of the _product_in_stock field for each item. If the value for an item is zero (0), the component either writes an out of stock message to the order form’s _Purchase_Errors list, or sets the value for the _inventory_backorder field, depending on whether the Disallow Backorder check box is selected.


GenerateReceipt

The GenerateReceipt component reads values written to the Transport Dictionary by the OpenHeader component, creates a return receipt business data object, and then invokes a transmit pipeline to send a receipt back to the original sender.

  • υSend Receipt PCF filepath. Specifies the full path to the pipeline configuration file (.pcf) for the transmit pipeline that sends the receipt back to the original sender. To locate the .pcf file, click Browse (Win32 only). In the default configuration, a site’s .pcf file is located in the \Inetpub\wwwroot\sitename\Config\ folder.

The following table describes the values that the GenerateReceipt reads and writes. Values are written to the return receipt business data object.

Data Source Target in receipt
Object
The transaction ID. | The txid name/value pair written to the Transport Dictionary by OpenHeader (originally written by the transmitting pipeline’s AddHeader component). | txid
A digest of the business data object | The msg_digest name/value pair written to the Transport Dictionary by OpenHeader. | receive_msg_digest
Hashing algorithm used The <DIGESTALGORITHM> tag from the _return_receipt_request name/value pair written to the Transport Dictionary by OpenHeader. receive_digest_
algorithm
The return receipt request | The <DOCUMENTTYPE>tag from the _return_receipt_request name/value pair written to the Transport Dictionary by OpenHeader. | document_type
The date and time when the receipt was generated | The system time on the receiving system. | receive_datetime
Document type (Optional) | The Document_type name/value pair optionally written to the Transport Dictionary by OpenHeader (originally added to the Transport Dictionary before transmission, then written by the transmitting pipeline’s AddHeader component into the object header). | document_type
Document source (Optional) | The Document_source name/value pair optionally written to the Transport Dictionary by OpenHeader (originally added to the Transport Dictionary before transmission, then written by the transmitting pipeline’s AddHeader component into the object header). | document_source
Document destination (Optional) | The Document_destination name/value pair optionally written to the Transport Dictionary by OpenHeader (originally added to the Transport Dictionary before transmission, then written by the transmitting pipeline’s AddHeader component into the object header). | document_destination


ItemPromo

The ItemPromo component, which usually appears in the Item Adjust Price Stage of an order processing pipeline, applies a promotional price adjustment to an item on the order form’s items list. The ItemPromo component first determines whether the current date falls within the time period specified by the Start Date and End Date fields. If it does, then the component evaluates the item to determine if it meets the conditions of the promotion (specified by the combination of the Condition Order Key, Condition Operator, and Condition Value fields). If it does, then the ItemPromo component applies the specified discount and writes the new value to the item’s _iadjust_currentprice field on the order form, provided that _iadjust_currentprice has not been initialized by a previously run component.

  • υCondition Order Key. Specifies the name of the item attribute that identifies the condition that must be met before the promotion is applied (for example, _product_type).
  • υCondition Operator. Specifies an operator (<, <=, =, >=, >, or <>) that the ItemPromo component uses to compare the value of Condition Order Key with the value in the Condition Value box.
  • υCondition Value. Specifies what product or products must be purchased before the promotion is applied. The value in this field is compared with the value in the column whose name is specified in the Condition Order Key field. This value can be text, an integer or a floating-point number.
  • υDiscount Type. Specifies whether the discount is a percentage-off discount or a price discount.
  • υDiscount Value. Specifies amount of the discount. This must be an integer value; floating point numbers (for example, .10) are not accepted.
  • υStart Date. (Optional) Specifies the date the promotion begins, starting at 12:00:01 a.m.
  • υEnd Date. (Optional) Specifies the date the promotion ends, ending at 12:00:01 a.m. For example, if you want the last day of a promotion to be 3/31, you would specify an End Date of 4/1.

Example

To indicate that items manufactured by Tailspin Toys are at a 15% discount between two specified dates, double-click the ItemPromo icon in the Win32®-based Pipeline Editor, or click the Edit link for the component in the ASP-based Pipeline Editor, and then enter the following in the resulting property page.

Property page showing example configuration values for ItemPromo

Important

The promotional comparisons that you specify in Conditional Value are case-sensitive. For example, product ID AW13-200 will be interpreted differently than aw13-200.

In addition, because the Start Date and End Date for a promotion specify midnight, End Date excludes the day specified. For example, if you want the last day of a promotion to be 3/31, be sure to specify that the promotion ends on 4/1.

Related Topics

  • υ How To Implement Promotions


LinearHandling

The LinearHandling component, which usually appears in the Handling Stage of an order processing pipeline, sets order._handling_total on the order form by multiplying a rate times the sum of a specified field on the order form.

  • υKey. (Read-only) The name of a property on the order form used to specify handling method. The value of this property is compared to the string specified in the Method field to determine whether to apply the handling charge to the order.
  • υApply when. Specifies when to apply the handling charge.
    • υEqual to Method. Specifies that the handling charge if the value of the property specified for Key is the same as the string specified in the Method field.
    • υHas Any Value. Specifies that the handling charge will be applied when the value of the property specified for Key has any value on the order form. If you select this option, the Method field should be left blank.
    • υAlways. Specifies that the handling charge is always applied to the order.
  • υMethod. If Equal to Method is selected, specifies a string that the component compares with the value of shipping_method on the order form to determine whether to apply the handling charge to the order. The handling charge will be applied only if there is an exact match.
  • υBasis Item Key. Specifies the property of the item that is used to compute the handling charge. The LinearHandling component computes the charge by multiplying the value specified for Rate by the sum of the property specified for Basis Item Key. For example, you might base the linear handling charge on the quantity of the items, and the Basis Item Key might be sum.quantity. If the order contains two items, one item with a quantity of four and the other item with a quantity of two, then the basis sum is six. The component multiplies the value specified for Rate by six. See Specifying the Basis Item Key.
  • υRate. Specifies an integer value that the component multiplies by the value of the item property specified in Basis Item Key to obtain the handling charge to apply to the order.

Related Topics

  • υComponent Coordination
  • υSpecifying the Basis Item Key


LinearShipping

The LinearShipping component, which usually appears in the Shipping Stage of an order processing pipeline, sets order._shipping_total on the order form by multiplying a rate times the sum of a specified field on the order form.

  • υKey. (Read-only) The name of a property on the order form used to specify shipping method. The value of this property is compared to the string specified in the Method field to determine whether to apply the shipping charge to the order.
  • υApply when. Specifies when to apply the shipping charge.
    • υEqual to Method. Specifies that the shipping charge if the value of the property specified for Key is the same as the string specified in the Method field.
    • υHas Any Value. Specifies that the shipping charge will be applied when the value of the property specified for Key has any value on the order form. If you select this option, the Method field should be left blank.
    • υAlways. Specifies that the shipping charge is always applied to the order.
  • υMethod. If Equal to Method is selected, specifies a string that the component compares with the value of shipping_method on the order form to determine whether to apply the shipping charge to the order. The charge will be applied only if there is an exact match.
  • υBasis Item Key. Specifies the property of the item that is used to compute the shipping charge. The LinearShipping component computes the charge by multiplying the value specified for Rate by the sum of the property specifies for Basis Item Key. For example, you might base the linear shipping charge on the quantity of the items, and the Basis Item Key might be sum.quantity. If the order contains two items, one item with a quantity of four and the other item with a quantity of two, then the basis sum is six. The component multiplies the value specified for Rate by six. See Specifying the Basis Item Key.
  • υRate. Number to multiply by the Basis Item Key to obtain the shipping charge to apply to the order.

Example

To calculate the shipping charge for an order on the basis of quantity with a rate of 100, double-click the LinearShipping icon in the Win32®-based Pipeline Editor, or click the Edit link for the component in the ASP-based Pipeline Editor and type the following in the resulting property page.

Field | Value
Apply when | Always
Method | (blank)
Basis Item Key | sum.quantity
Rate | 100

Related Topics

  • υComponent Coordination
  • υTableShippingADO


LocalInventory

The LocalInventory component, which usually appears in the Inventory Stage of an order processing pipeline, sets the value of _inventory_backorder on the order form to the number of items backordered. The LocalInventory component takes the sum of the items for each SKU in the order, and then compares this number with the value of _product_local_inventory. If the value of _product_local_inventory is less than the number of items ordered, the component sets the value of _inventory_backorder to the difference.

  • υDisallow Backorder. If selected, specifies that backorders are not permitted. In this case, the component adds the _pur_out_of_stock message to the _Purchase_Errors SimpleList on the order form.

For information about managing inventory in Commerce Server 3.0 sites, see Using the Inventory Components.


MakePO

The MakePO component generates a purchase order (PO) by merging the information on the order form with a purchase order template.

  • υTemplate File Name. Specifies the name of the file that provides the template for the purchase order. The template is usually a Microsoft® Visual Basic Scripting (VBS) file with a .txt extension. Either type the full path to the file, or click Browse to locate the file (Win32 only). For example:
    C:\Inetpub\Wwwroot\Market\config\PoMailtemplate.txt
  • υScript language for the template. Specifies the programming language used in the template. The default is VBScript.
  • υOutput Property Name. The name of a field on the order form or Transport Dictionary to which the component writes the PO. The default is _po_text.
  • υChild Object Name. Applies only when Use Child Object is set. A child object is an object that is referenced by a name/value pair on the Transport Dictionary that is passed into the pipeline. The Child Object Name specifies the name of this name/value pair. In a CIP, the order form (business data object) from which MakePO generates the purchase order is a child object.
  • υUse Child Object. Specifies the source from which the component reads the purchase order information. Select this option when using a CIP, so that the component reads this information from the business data object specified by the Child Object Name field. Clear this check box when using an OPP, so that the component reads this information from the order form that is passed directly into the pipeline.

Remarks

MakePO can be used to dynamically generate a text entry on the OrderForm (usually a purchase order). The entry is generated from a template file similar to an ASP page. Like an ASP page, a MakePO template contains plain text interspersed with special tags containing script code. From within script, output can be achieved using PageGen.Print expression, or <%% = expression %%> similar to ASP's shortcut for Response.Write. The script language is configurable in the property page.

From within the MakePO template, the business object (OrderForm, dictionary, or child object) is exposed as an object with the name Items. The selected scripting language's library is also extended to include the members of this object as built-in properties, so referring to the business object's entries using the Items.xxx notation is optional. For this reason it is advisable to declare any temporary variables, so that they are not saved to the business object.

The following script is an example from the POMailTemplate.txt template, used by the MakePO component in the Purchase Order Submit stage of the SubmitViaMail.pcf pipeline for the Microsoft Market sample site:

Item Class:<%%= item.partclasscode %%>
#:<%%= item.partnumber %%>
Qty:<%%= item.quantity %%>
Cost:<%%= item.[_display_list_price] %%>
Unit Code:<%%= item.unitcode %%>

The PO generated by MakePO can be saved to a file using the POToFile component.

Note

MakePO can not output variant subtype VT_DECIMAL. Any usage of decimal or currency in MakePO must be wrapped with a call to CStr, which properly coerces the value to a string. For example:
Requisition # <%% = CStr(RequisitionID) %%>

Related Topic

  • υCreating EDI messages with MakePO
  • υUsing Mapping Components


MapFromXML

The MapFromXML component, which usually appears in the Map stage of a Commerce Interchange Receive pipeline, reconstitutes the original business data object from the XML stream.

  • XML Source Key. Specifies the name of a field on the Transport Dictionary from which the component reads the XML-encoded business data object. The default is working_data.
  • Result Object Key. Specifies the name of a field on the Transport Dictionary to which the component writes the business data object. The default is object.

Remarks

The MapFromXML component parses the XML data stored in the Transport Dictionary in the name/value pair specified by XML Source Key, creates a business data object to store the parsed data, and initializes a name/value pair specified by Result Object Key to reference this object.

The MapToXML component performs the initialization of the business data object using the object’s implementation of IPersistXML or IPersistStream.

Related Topics

  • υMapToXML
  • υUsing Mapping Components


MapToXML

The MapToXML component, which usually appears in the Map stage of a Commerce Interchange Transmit pipeline, reads the data stored in an object referenced by the name/value pair in the Transport Dictionary specified by the Object Source Key field. MapToXML converts this data to an XML stream or to an XML-enclosed binary stream. MapToXML then writes the resulting stream to the name/value pair in the Transport Dictionary specified by Results XML Key.

  • υObject Source Key. Specifies the name of a field on the Transport Dictionary from which the component reads the business data object.
  • υResults XML Key. Specifies the name of a field on the Transport Dictionary to which the component writes the XML-formatted business data object.
  • υPreferred Data Format. Specifies the preferred format into which the component translates the business data object.
    • υXML Tags. Specifies that the entire business data object is to be translated into a pure XML stream.
    • υEncoded Binary. Specifies that the binary version of the business data object is to be wrapped in XML tags.

If the object to be read implements IPersistXML or IPersistStreamInit, the output produced by MapToXML is as follows:

<MAPXML><VALUE dt:dt="object" dt:classid="classid:classid">
<ObjectTag>
Object Data
</ObjectTag>
</VALUE></MAPXML>

or, in the case of encoded binary format, in the following form:

<MAPXML><VALUE dt:dt="object" dt:classid="classid:classid" dt:binary="1">
Binary Object Data
</VALUE></MAPXML>

The value 1 (one) following binary indicates that the result was mapped using the object’s IPersistStream interface; a value of 2 (two) indicates that the result was mapped using the object’s IPersistStreamInit interface.

Example

Suppose a Dictionary object is created, as follows::

Set myObj = Server.CreateObject("Commerce.Dictionary")
myObj.Company = "Microsoft"

When this dictionary is passed to the MapToXML component, the component produces the following output, when the output is specified as XML tags:

<MAPXML><VALUE dt:dt="object" dt:classid="classid:B7990D09-45FD-11D0-8176-00A0C90A90C7">
<DICTIONARY>
<DICTITEM key="Company"><VALUE dt:dt="string" xml-space="preserve">Microsoft</VALUE></DICTITEM>
</DICTIONARY>
</VALUE></MAPXML>

A SimpleList object created as follows:

Set myObj = Server.CreateObject("Commerce.SimpleList")
Call myObj.Add("Microsoft")

produces the following result when mapped to XML tags:

<MAPXML><VALUE dt:dt="object" dt:classid="classid:B7990D0E-45FD-11D0-8176-00A0C90A90C7">
<SIMPLELIST>
<LISTITEM><VALUE dt:dt="string" xml-space="preserve">Microsoft</VALUE></LISTITEM>
</SIMPLELIST>
</VALUE></MAPXML>

The following example shows an order form that has been converted to XML by the MapToXML component. The example was produced by ordering a laser printer cartridge in the Microsoft Market sample site.

The XML output reveals the structure of the order form object (the classID of which is 713DD5B1-747C-11D0-BE8A-00A0C90DC855). It contains a dictionary, which in turn contains name value pairs associated with the order. One of these values, Items, contains a SimpleList object, which consists of a list of the items ordered (in this case, only one). The list item, in turn, contains another dictionary, which contains values describing the item ordered (SKU, Quantity, and so on).

<MAPXML><VALUE dt:dt="object" dt:classid="classid:713DD5B1-747C-11D0-BE8A-00A0C90DC855">
<DICTIONARY>
<DICTITEM key="Items"><VALUE dt:dt="object" dt:classid="classid:B7990D0E-45FD-11D0-8176-00A0C90A90C7">
<SIMPLELIST>
<LISTITEM><VALUE dt:dt="object" dt:classid="classid:B7990D09-45FD-11D0-8176-00A0C90A90C7">
<DICTIONARY>
<DICTITEM key="SKU"><VALUE dt:dt="string" xml-space="preserve">OPPRINTER1001605</VALUE></DICTITEM>
<DICTITEM key="Quantity"><VALUE dt:dt="i4">1</VALUE></DICTITEM>
<DICTITEM key="insertby"><VALUE dt:dt="string" xml-space="preserve">JoeStart</VALUE></DICTITEM>
<DICTITEM key="ReqClassCode"><VALUE dt:dt="string" xml-space="preserve">OP</VALUE></DICTITEM>
<DICTITEM key="ISOCurrencyCode"><VALUE dt:dt="string" xml-space="preserve">USD</VALUE></DICTITEM>
<DICTITEM key="RequisitionID"><VALUE dt:dt="i4">10004</VALUE></DICTITEM>
<DICTITEM key="PartNumber"><VALUE dt:dt="string" xml-space="preserve">1001605</VALUE></DICTITEM>
<DICTITEM key="PartClassCode"><VALUE dt:dt="string" xml-space="preserve">PRINTER</VALUE></DICTITEM>
<DICTITEM key="Partdescription"><VALUE dt:dt="string" xml-space="preserve">Print Cartridge GGG Printer Black</VALUE></DICTITEM>
<DICTITEM key="isstandardpart"><VALUE dt:dt="string" xml-space="preserve">Y</VALUE></DICTITEM>
<DICTITEM key="UnitCode"><VALUE dt:dt="string" xml-space="preserve">EA</VALUE></DICTITEM>
<DICTITEM key="list_price"><VALUE dt:dt="string" xml-space="preserve">2519</VALUE></DICTITEM>
<DICTITEM key="AccountCode"><VALUE dt:dt="string" xml-space="preserve">728002</VALUE></DICTITEM>
<DICTITEM key="InternalOrder"><VALUE dt:dt="string" xml-space="preserve">1</VALUE></DICTITEM>
<DICTITEM key="placed_price"><VALUE dt:dt="i4">2519</VALUE></DICTITEM>
</DICTIONARY>
</VALUE></LISTITEM>
</SIMPLELIST>
</VALUE></DICTITEM>
<DICTITEM key="RequisitionID"><VALUE dt:dt="i4">10004</VALUE></DICTITEM>
<DICTITEM key="ReqStatusID"><VALUE dt:dt="i2">2</VALUE></DICTITEM>
<DICTITEM key="insertby"><VALUE dt:dt="string" xml-space="preserve">JoeStart</VALUE></DICTITEM>
<DICTITEM key="DateCreated"><VALUE dt:dt="dateTime.iso8601">19980206T11:34:34000</VALUE></DICTITEM>
<DICTITEM key="DateChanged"><VALUE dt:dt="dateTime.iso8601">19980206T11:34:43000</VALUE></DICTITEM>
<DICTITEM key="ReqClassCode"><VALUE dt:dt="string" xml-space="preserve">OP</VALUE></DICTITEM>
<DICTITEM key="ISOCurrencyCode"><VALUE dt:dt="string" xml-space="preserve">USD</VALUE></DICTITEM>
<DICTITEM key="VendorNumber"><VALUE dt:dt="string" xml-space="preserve">0002001243</VALUE></DICTITEM>
<DICTITEM key="locale"><VALUE dt:dt="i4">1033</VALUE></DICTITEM>
<DICTITEM key="order_id"><VALUE dt:dt="string" xml-space="preserve">DJUH21SKKES12MHD00L1R0D8N7</VALUE></DICTITEM>
<DICTITEM key="ReqName"><VALUE dt:dt="string" xml-space="preserve">Joe Start</VALUE></DICTITEM>
<DICTITEM key="ReqEmailalias"><VALUE dt:dt="string" xml-space="preserve">JoeStart</VALUE></DICTITEM>
<DICTITEM key="ApprovalManagerAlias"><VALUE dt:dt="string" xml-space="preserve">MaryJJJ</VALUE></DICTITEM>
<DICTITEM key="ReqPhone"><VALUE dt:dt="string" xml-space="preserve">454-9894</VALUE></DICTITEM>
<DICTITEM key="TransmissionRoom"><VALUE dt:dt="string" xml-space="preserve">2343</VALUE></DICTITEM>
<DICTITEM key="TransmissionLocation"><VALUE dt:dt="string" xml-space="preserve">100</VALUE></DICTITEM>
<DICTITEM key="TransmissionLine1"><VALUE dt:dt="string" xml-space="preserve">Joe Start</VALUE></DICTITEM>
<DICTITEM key="TotalAtSubmit"><VALUE dt:dt="i4">2519</VALUE></DICTITEM>
<DICTITEM key="needapproval"><VALUE dt:dt="boolean">0</VALUE></DICTITEM>
</DICTIONARY>
</VALUE></MAPXML>

Related Topics

  • υMapFromXML
  • υUsing Mapping Components


OpenHeader

The OpenHeader component, which usually appears in the Open Header Stage of a Commerce Interchange Receive pipeline, reads the XML header tags appended to the data object by the transmit pipeline’s AddHeader component, and writes the XML-mapped business object, the transaction ID, the data and time of the transmission, a message digest, and other optional values to the Transport Dictionary as name/value pairs.

  • υInput Field. Specifies the name of the field on the Transport Dictionary from which the XML-formatted business data object is read.
  • υOutput Field. Specifies the name of the field on the Transport Dictionary to which the business data object is written.

The following table lists the XML values that are written as name/value pairs by the OpenHeader component.

Purpose | XML Tag read | Name/Value written
Return receipt information. Optional. This information is needed by the GenerateReceipt component later in the pipeline. <RETURNREQUEST>
<DIGESTALGORITHM>
algorithm
</DIGESTALGORITHM>
<DOCUMENTTYPE>
requestedDocumentType
</DOCUMENTTYPE>
</RETURNREQUEST> 		return_receipt_request
Message digest. Optional. A digest of the business data object. | None. | msg_digest.
Transaction ID. Unique identifier of the business transaction. <TRANSACTIONID>
</TRANSACTIONID> 		txid
Document type. Optional. Description of the type of business object being transmitted <DOCUMENTTYPE>
</DOCUMENTTYPE> 		Document_Type
Document source. Optional. Description of the source of the business object, usually the name or address of the company transmitting it. <DOCUMENTSOURCE>
</DOCUMENTSOURCE> 		Document_Source
Document destination. Optional. Description of the destination of the business object, usually the name or address of the company receiving it. <DOCUMENTDESTINATION>
</DOCUMENTDESTINATION> 		Document_Destination
The date and time of the OpenHeader operation, in Universal Coordinated Time (UTC). <UTCDATETIME>
</UTCDATETIME> 		send_datetime
Business data object. The data that appears between these tags represents an XML representation of the business data object written by the AddHeader component. <OBJECTDATA>
</OBJECTDATA> 		Name/value pair specified as Output Field (default is working_data)

The message digest represents a hash of the business data object, and is not intended to be human readable. This data is sent back to the original sender by the GenerateReceipt component.

Related Topic

  • υAddHeader


PipeToPipeTransfer

The PipeToPipeTransfer component initializes and executes a remote pipeline to receive the Transport Dictionary from the current pipeline. Control then returns to the initial pipeline.

  • υCalling Pipeline Object. Specifies the type of object that is to be passed to the remote pipeline.
    • υRoot Object. Specifies that the object that is to be transferred is a root object. This means that the object is either an order form (being transferred from an order processing pipeline) or a Transport Dictionary (being transferred from a Commerce Interchange Pipeline).
    • υChild Object. Specifies that the object being transferred is a child object. This means that the object is a Commerce Interchange Pipeline business data object, which is a child object of the Transport Dictionary.
  • υReceiving Pipeline Object. Specifies the type of object that the receiving pipeline will create to store the received data.
    • υRoot Object. Specifies that the object is a root object; either an order form (for use in an order processing pipeline) or a Transport Dictionary (for use in a Commerce Interchange Pipeline).
    • υChild Object. Specifies that the object is a child object; a business data object, which is a child object of the Transport Dictionary (for use in a Commerce Interchange Pipeline).
    • υChild’s Parent Data Type. Specifies whether the data type of the parent object is a Dictionary or an OrderForm.
  • υReceiving Pipeline Information. Specifies the pipeline configuration file and the type of pipeline object.
    • υPipeline Configuration Filename. Specifies the full path to the .pcf file used for initializing the receiving pipeline. To locate the .pcf file, click Browse.
    • υPipeline Type. Specifies the type of pipeline object used for the receiving pipeline.
    • υOrderPipeline. Specifies that the receiving pipeline is to be an OrderPipeline object, which is not registered under Microsoft® Transaction Server (MTS), and is generally used only for backward compatibility with sites created in Commerce Server 2.0.
    • υMtsPipeline. Specifies that the receiving pipeline is to be an MtsPipeline object, which is registered under MTS as transactions not supported. This pipeline is used in situations where transactions are not desired.
    • υMtsTxPipeline. Specifies that the receiving pipeline is to be an MtsTxPipeline object, which is registered under MTS as transactions required. This pipeline holds a transaction across all components in the pipeline configuration.

Example

Suppose that you want to pass an OrderForm from an OPP to a CIP, so that the Transport Dictionary that is passed through the CIP will have an Object name/value pair that references the OrderForm.

To do this, you would select Root Object as the Calling Pipeline Object (indicating that the entire OrderForm is to be transferred), Child Object as the Receiving Pipeline Object (indicating that the OrderForm will be the child of the object to which it is transferred. Next, you would type Object into the into the Child Object textbox, and select Dictionary as the Child’s Parent Data Type.

This combination of options results in the creation of a Dictionary with an Object name/value pair. This name/value pair references the OrderForm.


POtoFile

The POtoFile component sends a purchase order (usually the output of the MakePO component) to a file.

  • υSource Field Name. Specifies the name of the field on the order form from which the component reads the purchase order data (po_text by default).
  • υFile Name. Specifies the full path to the file to which the component writes the purchase order. To locate the file, click Browse (Win32 only).
  • υFile named in field. Specifies the name of the field on the order form whose value is the name of the file to which the component writes the purchase order; for example, save_filename.
  • υTemporary file, named saved in field. Specifies that the component should save the PO to a temporary file, and then save the name of the temporary file into the field identified here. For example, saved_filename.
Note

The File Name, File Named in field, and Temporary file fields are mutually exclusive; that is, you can select only one of the three.


QueryProdInfo

The QueryProdInfo component, which usually appears in the Product Info stage of an order processing pipeline, runs a database query to retrieve product information for all the items in the items list and adds the information to the order form.

Note

This component is used for compatibility with Commerce Server version 2.0 sites, in which the database connection is provided by the Content object in the Pipe Context. Commerce Server 3.0 sites should use the QueryProdInfoADO component.

  • υQuery. Specifies either the full SQL text of the query that is executed by this component or the name of a query whose full SQL text is stored in the Content object.

For each item in the items list, the component executes the query that you specify, passing the item’s SKU (stored in item[n].SKU) as a parameter to the query. After retrieving the item information, QueryProdInfo adds the information to the item Dictionary for that item.

If no data is found for a given SKU, QueryProdInfo writes a name/value pair named delete to the item Dictionary, initializes the delete item to 1 (marking it for deletion), then moves on to the next item. Additionally, QueryProdInfo adds a pur_badsku message to the _Basket_Errors collection. Items marked for deletion are removed from the OrderForm.

If data for the specified SKU is found, then for each column retrieved by the query, QueryProdInfo writes a name/value pair to the item Dictionary. The name part of the name/value pair consists of the prefix _product_, followed by the column name. Thus, for example, the data in a table column named col would be placed in the value of item[n]._product_col. Finally, QueryProdInfo initializes the name/value pair to contain the data stored in the appropriate column.

Related Topic

  • υRequiredProdInfo


QueryProdInfoADO

The QueryProdInfoADO component, which usually appears in the Product Info stage of an order processing pipeline, runs a database query to retrieve data about the products on the order form. If data for the specified SKU is found, then for each column retrieved by the query, the component then writes the data into the item._product_columnvalue fields on the item Dictionary of the order form, so that the product information is available to components that run subsequently.

  • υConnection string. Specifies the connection string used for connecting to the database. The connection string must include either the full connection string (the data source name (DSN), database login ID, and database password) or the name of a named connection stored in the connection map. If this field is blank, the default connection string is used.
  • υQuery. Specifies either the full SQL text of the query that is executed by this component or the name of a query whose full SQL text is defined in the site’s global.asa file.
  • υParameter List. Specifies the parameters that the component passes to the query. If multiple parameters are specified, each parameter is separated from the next by a single space.

Remarks

If you add new columns to the product database table, and if this information is needed by any component in the pipeline, then you must add the column to the query used by QueryProdInfoADO.

If data for the specified SKU is found, then for each column retrieved by the query, QueryProdInfoADO writes a name/value pair to the item Dictionary. The name part of the name/value pair consists of the prefix _product_, followed by the column name. Thus, for example, the data in a table column named col would be placed in the value of item[n]._product_col. Finally, QueryProdInfoADO initializes the name/value pair to contain the data stored in the appropriate column.

If no rows are returned by the query, QueryProdInfoADO writes a name/value pair named delete to the item Dictionary, initializes the delete item to 1 (marking it for deletion), adds a pur_badsku message to the _Basket_Errors list, then moves on to the next item. Items marked for deletion are removed from the OrderForm.

The primary difference between QueryProdInfoADO and the Commerce Server 2.0 QueryProdInfo component lies in the types of queries you can use.

  • υThe QueryProdInfo component attempts to retrieve the query that you specify from the Content object. QueryProdInfoADO attempts to retrieve the query from the QueryMap Dictionary.
  • υThe QueryProdInfo component uses the default datasource for the site to execute the query. QueryProdInfoADO uses any connection string that you specify.
  • υThe QueryProdInfo component always uses the SKU for a given item as a parameter to the query that retrieves information about that item. QueryProdInfoADO can use any parameters that you specify to retrieve information about an item. Consequently, QueryProdInfoADO can function with a wider variety of database schema than can QueryProdInfo.

Example

The QueryProdInfoADO component is included in the Plan pipeline (Plan.pcf) used by the Clocktower sample site. When you open the Clocktower’s Plan.pcf file in the Win32®-based Pipeline Editor, and double-click the QueryProdInfoADO component, the property page appears.

The Query field is specified as productpl, which identifies an entry in the Clocktower’s QueryMap Dictionary. This entry is created in the Clocktower’s Global.asa file as follows:

REM -- Create Query Map Dictionary
REM -- Each Query is a Dictionary with SQLCommand and parameters
Set MSCSQueryMap = Server.CreateObject("Commerce.Dictionary")

REM Later in global.asa

REM -- Query used by the QPI component
Set MSCSQueryMap.productpl = Server.CreateObject("Commerce.Dictionary")
    MSCSQueryMap.productpl.SQLCommand = "select sku, name, list_price     from clocktower_product where sku = ?"

When the order processing pipeline (OPP) is invoked, the QueryMap is passed in as part of the pipe context Dictionary to the MtsPipeline object’s Execute method.

The QueryProdInfoADO component retrieves the text of the productpl query from the QueryMap. Because the component has no configured connection string, the QueryProdInfoADO component uses the default connection string.

If the productpl query returns data for an item, QueryProdInfoADO adds the following name/value pairs to the Dictionary for that item.

_product_sku
_product_name
_product_list_price

Related Topic

  • υRequiredProdInfo


ReduceLocalInventory

The ReduceLocalInventory component, which usually appears in the Inventory stage of an order processing pipeline, deducts the quantity of an item being purchased from the column in the database that stores the total number of the item available in inventory.

Note

This component is used for compatibility with Commerce Server version 2.0 sites, in which the database connection is provided by the Content object in the Pipe Context. Commerce Server 3.0 sites should use the SQLItemADO component. The ReduceLocalInventory component does not support MTS transactions, therefore you should not include it in an MtsTxOrderPipeline object.

  • υQuery. Specifies either the full SQL text of the query that is executed by this component or the name of a query whose full SQL text is defined in the site’s global.asa file.


RequiredHandling

The RequiredHandling component, which appears in the Handling stage of an order processing pipeline, verifies that the order._handling_total name/value pair is present and is initialized to a value. If this name/value pair is not present, the RequiredHandling component adds a pur_badhandling message to the order._Purchase_Errors SimpleList.


RequiredItemAdjustPrice

The RequiredItemAdjustPrice component, which appears in the Item Adjust Price stage of an order processing pipeline, verifies that the _iadjust_currentprice name/value pair is set for each item in the items list. If this value is not set, RequiredItemAdjustPrice initializes it to the value stored in _iadjust_regularprice.

In addition, the component verifies that the item’s name/value pair is set. If it is not, RequiredItemAdjustPrice sets it to the value stored in _iadjust_currentprice. If it is set, but is not equal to _iadjust_currentprice for the item, RequiredItemAdjustPrice retrieves the error for pur_badplacedprice from the MessageManager, and writes this error to the OrderForm's _Basket_Errors collection. In addition, placed_price is initialized to the value in _iadjust_currentprice for the item.

Note

If you are not running the Pipeline Editor in expert mode, the RequiredItemAdjustPrice component is automatically inserted into the Item Price Adjust stage, but is not displayed in the Pipeline Editor user interface. This component appears in the user interface only if you run the Pipeline Editor in expert mode.


RequiredItemPrice

The RequiredItemPrice component, which appears in the Item Price stage of an order processing pipeline, verifies that the _iadjust_regularprice name/value pair has been set for each item in the items list.

Before the RequiredItemPrice component is run, it should have been initialized by the DefaultItemPrice component to contain the most current pricing information for the item.

If the _iadjust_regularprice name/value pair does not contain a value, an error is raised.

Note

If you are not running the Pipeline Editor in expert mode, the RequiredItemPrice component is automatically inserted into the Item Price stage, but is not displayed in the Pipeline Editor user interface. This component appears in the user interface only if you run the Pipeline Editor in expert mode.

Related Topic

  • υDefaultItemPrice


RequiredOrderAdjustPrice

The RequiredOrderAdjustPrice component, which appears in the Order Adjust Price stage of an order processing pipeline, calculates and initializes the _oadjust_adjustedprice and _oadjust_discount name/value pairs for each item in the items SimpleList. The following example illustrates how this component works.

A site is offering a discount on an item priced at $12.00, such that if a customer purchases two items at the regular price, the customer gets a third at half that price. Suppose further that you have chosen to purchase three of these items.

When the RequiredOrderAdjustPrice component is executed, the item Dictionary for this item already contains the following name/value pairs.

Name/ | Value
_iadjust_currentprice | Adjusted price of this item.
Quantity | Number of the items of this SKU being purchased.
_n_unadjusted | Number of the items identified by Quantity that do not need to have their prices adjusted.

In this example, the value of Quantity is 3, and the number of _n_unadjusted is also 3, because the default value of _n_unadjusted is always (the total number of items minus the number of items purchased at the regular price). By default, the _n_unadjusted name/value pair is equal to the total Quantity, unless it has been decremented by a previous component, such as DbOrderPromo.

To adjust the price for this item, RequiredOrderAdjust multiplies Quantity by _n_unadjusted, and writes the resulting value to the _oadjust_adjustedprice name/value pair. This value represents the total price for the items of this SKU.

Next, RequiredOrderAdjust multiplies Quantity by the value in _iadjust_adjustedprice, and subtracts the adjusted price of the total items (now stored in _oadjust_adjustedprice) from the result. The new result represents the total discount for this item, and is written to the _oadjust_discount name/value pair.

Note

If you are not running the Pipeline Editor in expert mode, the RequiredOrderAdjustPrice component is automatically inserted into the Order Adjust Price stage, but is not displayed in the Pipeline Editor user interface. This component appears in the user interface only if you run the Pipeline Editor in expert mode.


RequiredOrderCheck

The RequiredOrderCheck component, which appears in the Order Check stage of an order processing pipeline, ensures that the OrderForm's items list is not empty. If the list is empty, RequiredOrderCheck retrieves the message associated with the pur_noitems error from the MessageManager, and writes this message to the OrderForm’s _Purchase_Errors list.

Note

If you are not running the Pipeline Editor in expert mode, the RequiredOrderCheck component is automatically inserted into the Order Check stage, but is not displayed in the Pipeline Editor user interface. This component appears in the user interface only if you run the Pipeline Editor in expert mode.


RequiredOrderInit

The RequiredOrderInit component, which appears in the Order Initialization stage of an order processing pipeline, ensures order integrity by performing the following operations on an OrderForm.

First, RequiredOrderInit makes sure that the order.order_id name/value pair contains a value. If it does not, RequiredOrderInit generates a unique order ID and stores it in this name/value pair.

Additionally, for purposes of order integrity, this component sets the following name/value pairs to NULL:

order._total_total
order._oadjust_subtotal
order._shipping_total
order._tax_total
order._handling_total
order._tax_included
order._payment_auth_code

Finally, for each item in the items SimpleList, RequiredOrderInit initializes the _n_unadjusted name/value pair to the value stored in quantity, and initializes _oadjust_adjustedprice to zero (0).

Note

If you are not running the Pipeline Editor in expert mode, the RequiredOrderInit component is automatically inserted into the Order Initialization stage, but is not displayed in the Pipeline Editor user interface. This component appears in the user interface only if you run the Pipeline Editor in expert mode.

Related Topic

RequiredOrderCheck


RequiredOrderSubtotal

The RequiredOrderSubtotal component, which appears in the Order Subtotal stage of an order processing pipeline, checks the _oadjust_subtotal member in the OrderForm to ensure that this value is not NULL. If NULL, RequiredOrderSubtotal generates an error.

Note

If you are not running the Pipeline Editor in expert mode, the RequiredOrderSubtotal component is automatically inserted into the Order Subtotal stage, but is not displayed in the Pipeline Editor user interface. This component appears in the user interface only if you run the Pipeline Editor in expert mode.


RequiredPayment

This component, which appears in the Payment stage of an order processing pipeline, checks whether the value of _payment_auth_code is NULL. If this name/value pair is NULL, RequiredPayment generates a pur_bad_payment error in the MessageManager, and returns this error in the OrderForm’s _Purchase_Errors collection.


RequiredProdInfo

The RequiredProdInfo component, which appears in the Product Info stage of an order processing pipeline, iterates through the OrderForm’s items list, and deletes any items that have the delete field set to 1 (presumably by a previous Product Information stage component, such as QueryProdInfo or QueryProdInfoADO).

If the RequiredProdInfo component deletes any items from the items collection, it retrieves the value of the pur_badsku message from the MessageManager, and writes this value to the OrderForm's _Basket_Errors collection.

Note

If you are not running the Pipeline Editor in expert mode, the RequiredProdInfo component is automatically inserted into the Product Information stage, and is not visible through the Pipeline Editor user interface.


RequiredShipping

The RequiredShipping component, which appears in the Shipping stage of an order processing pipeline, verifies that the order._shipping_total RequiredTotaname/value pair has been set.


RequiredTax

The RequiredTax component, which appears in the Tax stage of an order processing pipeline, verifies that the order._tax_total and order._tax_included name/value pairs are not NULL. If they are NULL, the RequiredTax component adds a pur_badtax message to the order._Purchase_Errors SimpleList.


RequiredTotal

The RequiredTotal component, which appears in the Order Total stage of an order processing pipeline, performs a _VERIFY_WITH check on the OrderForm.

The stage always performs a _VERIFY_WITH check. Any fields in the post that appear as _VERIFY_WITH="value=key" will verify that the order has such a key and it is set to that value. This prevents a malicious resetting of addresses or contents. If _verify_with is not on the OrderForm, no check is performed.

For example, order._total_total should equal (order._VERIFY_WITH)._total_total if _total.total is in the _VERIFY_WITH clause.

Example

<INPUT TYPE="HIDDEN" NAME="_VERIFY_WITH" VALUE="<% = "ship_to_zip=" & CStr(mmsOrderForm.ship_to_zip) %>">

For more examples, see the \Clocktower\Purchase.asp file in the Commerce Server installation.


SaleAdjust

The SaleAdjust component, which appears in the Item Adjust Price stage of an order processing pipeline, allows you to apply the sale price of an item. If the item is on sale, and if its _iadjust_currentprice has not been initialized by a previously executed component, SaleAdjust initializes _iadjust_currentprice to the value stored in the item’s _product_sale_price name/value pair.

The SaleAdjust component determines if an item is on sale by comparing the current date to the dates specified in the item’s _product_sale_start and _product_sale_end name/value pair.

Note

The SaleAdjust component requires that the sale_* values in the product table of the site database be set. Otherwise, the OrderForm will be missing the data needed to calculate the _iadjust_currentprice name/value pair, and an error message will be generated. The _product_sale_* values are set by QueryProdInfo or QueryProdInfoADO in the Product Information stage.

Because _product_sale_start and _product_sale_end are actually date/time pairs that specify midnight, _product_sale_end excludes the date specified. Thus, if you want the last day of a promotion to be 3/31, be sure to specify that the promotion ends on 4/1.


SaveReceipt

The SaveReceipt component saves an order to a database table. The name of the database table is stored in the DBStorage object on the pipe context dictionary (must be named receiptstorage). The SaveReceipt component saves all fields on the order form that have a corresponding column name in the database table.

  • υNo Save Key Prefix. Specifies a prefix that identifies fields on the order form that are not to be saved to the database table. This prefix is used to identify sensitive information such as credit-card numbers that should not be saved.


Scriptor

This Scriptor component, which can be used in any stage of a pipeline, executes a script written in a Microsoft® ActiveX® scripting language such as JavaScript™ or Microsoft® Visual Basic® Scripting Edition (VBScript).

You can run the Scriptor component in any stage of a pipeline.

  • υScripting Engine. Specifies the scripting language in which the script is written.
  • υSource. Specifies whether the script is stored internally or externally.
    • υInternal. Indicates that the script is stored internally in the .pcf file. In the Win32 Pipeline Editor, click the Edit button to display the script for editing.
    • υExternal. Indicates that the script is stored in a file on disk. The script’s path and file name are displayed in the Filename box. You can import an external script and convert it to an internal script (see Configuring a Scriptor Component).
  • υConfig. Specifies the parameters that are passed to the script in the form name=value.

Remarks

Note

The MSCSExecute function must return a success code. If you write a Scriptor component in VBScript, the MSCSExecute routine must be a function, not a subroutine (see the following examples). This is because MSCSExecute must return a success value of 1, a warning value of 2, or a failure value of 3. Subroutines cannot return 1. If you write the function in JavaScript, be sure to return a value.

The script that is executed by the Scriptor component consists of a group of entry points. These include the following:

The MSCSOpen handler. This function is invoked first when the Scritpor component is run.

The MSCSExecute handler. This is the main Scriptor entry point. This handler is passed the OrderForm, the pipe context, and optional configuration parameters.

The MSCSClose handler. This handler is invoked after the MSCSExecute handler has returned.

If you include the Scriptor component in a pipeline that you run using the MtsTxPipeline, you should not call the ObjectContext object’s methods from within the MSCSOpen or MSCSClose handlers. Calls to ObjectContext methods can only occur from within the Scriptor’s MSCSExecute handler.

Note

The Microsoft Transaction Server (MTS) context is not available to a Scriptor component or to any components called by a Scriptor (that is, context.SetComplete() and context.SetAbort() are not available to scripts hosted by Scriptor).

Related Topics

υUsing the Scriptor Component

υThe Scriptor Methods

υConfiguring a Scriptor Component


Configuring a Scriptor Component

The script run by a Scriptor component can be stored internally, as part of the .pcf file, or externally, in a separate file that is called by the component when it runs.

You can write a general-purpose script that can behave differently depending on the parameters that are passed to it. Save the script itself in a file, and then configure the Scriptor component to pass the parameters.

Note

The Microsoft Transaction Server (MTS) context is not available to a Scriptor component or to any components called by a Scriptor (that is, context.SetComplete() and context.SetAbort() are not available to scripts hosted by Scriptor).

To configure a Scriptor component
  1. In the Pipeline Editor, open the pipeline.
  2. Do one of the following, depending on which version of the Pipeline Editor you are using:
    • υIn the Win32-based Pipeline Editor, right-click the Scriptor component you want to configure, click Properties on the shortcut menu, and then click the Scriptor tab.
    • υIn the ASP-based Pipeline Editor, locate the Scriptor component you want to configure, and then click its Edit link.
  3. For Scripting Engine, select the language in which the script is written.
  4. For Source, do one of the following:
    • υTo store the script in the .pcf file, click Internal. In the Win32-based Pipeline Editor, click Edit, and then either type or paste the script into the Source Code Edit dialog box. Click OK. In the ASP-based Pipeline Editor, either type or paste the script into the Script box.
    • υTo store the script in an external file, click External. Type the path and file name in the Filename box. (In the Win32-based Pipeline Editor, you can also click the Browse button to locate the file.)
  5. To pass parameters to the script, type the parameters in the Config box.

    Parameters must be in the form name=value.

  6. In the Win32-based Pipeline Editor, click OK. In the ASP-based Pipeline Editor, click Update.
To convert a Scriptor between external and internal in the Win32-based Pipeline Editor
  1. In the Win32-based Pipeline Editor, open the pipeline.
  2. Right-click the Scriptor component you want to configure, click Properties on the shortcut menu, and then click the Scriptor tab.
  3. For Source, do one of the following:
    • υTo convert to Internal storage if the Scriptor has already been configured for an External file, click Internal, and then click Yes to confirm that you want to import the external file.
    • υTo export an Internal script to an external file if the Scriptor has already been configured for Internal, click External, and then click Yes to confirm that you want to export the internal file. Specify a name for the external file, and then click Save.
  4. Click OK.

Related Topics

  • υStarting the Pipeline Editor


SendDCOM

The SendDCOM component uses Distributed Component Object Model (DCOM) to create an instance of a ReceiveDCOM.exe or ReceiveDCOM2.dll component on a remote Commerce Server computer. The remote DCOM component creates an MtsTxPipeline or MtsPipeline object, and then uses that object to load and execute the specified pipeline on the business data object.

  • υMachine Name. Specifies the name of the remote computer on which to create an instance of ReceiveDCOM.exe or ReceiveDCOM2.dll.
  • υFrom Field. Specifies the name of the field on the Transport Dictionary from which the SendDCOM component reads the data to be sent. The data stored in the field specified in From Field must be serialized data; it cannot be an object. When the receiving DCOM component is instantiated, it creates a Dictionary object and writes the data in the specified From Field to this remote Transport Dictionary.
  • υTo Field. Specifies the name of the field on the remote Transport Dictionary to which the component writes the data.
  • υPCF File Name. Specifies the name of the pipeline configuration file on the remote computer.
  • υTransacted Pipe. If this check box is selected, the remote component creates an instance of the MtsTxPipeline object, which is registered under Microsoft® Transaction Server (MTS) as transactions required. If this check box is not selected, the component creates an instance of the MtsPipeline object, which is registered under MTS as transactions not supported.
  • υMTS Hosted Receive Component. This check box determines whether the ReceiveDCOM component should run in its own address space (as an executable) or as an in-process server under MTS. If this check box is cleared, the SendDCOM component creates an instance of ReceiveDCOM.exe. If this check box is selected, the SendDCOM component loads the ReceiveDCOM2.dll into MTS, then each subsequent send from SendDCOM creates an instance of the ReceiveDCOM2 object.
Note

After being created, ReceiveDCOM.exe waits for input from the SendDCOM component. If the SendDCOM component is terminated on the sending computer, the ReceiveDCOM.exe times out after five minutes.


SendHTTP

The SendHTTP component uses an HTTP POST to transmit data from the specified field on a Transport Dictionary or order form to a Web page (cgi, ISAPI, ASP, and so on). Often the receiving Web page will invoke another pipeline to perform further processing on the received data. Optionally, SendHTTP can store the response returned from the Web page, and the component saves that response into the specified field on the Transport Dictionary or order form. SendHTTP can work with text, UNICODE, and binary data.

  • υURL. Specifies the URL for the Web page that the data is to be posted to. Do not include http:: in this URL. You can specify a port number.
  • υField to be posted. Specifies the name of the field on the Transport Dictionary or order form that contains the data to be sent in the HTTP POST.
    • υAs Type. Specifies the format in which the data should be sent (text, binary, or UNICODE).
  • υStore response in field (optional). Specifies the name of the field on the Transport Dictionary or order form into which the SendHTTP component will write the response received from the Web page in response to the POST. This field is optional; if you leave it blank, the response is not saved to the Transport Dictionary or order form.
    • υFrom Type. Specifies the format of the data that is to be received (text, binary, or UNICODE).

When you configure the SendHTTP component, you specify the format in which the component is to post the contents of the specified field. Binary data should be posted as Binary. Text data may be posted as Text (ASCII/Multi-Byte Character Set blob) or UNICODE. UNICODE provides the best support for multi-lingual environments, however many Web servers do not support it.

Optionally, SendHTTP can store the response of the post. If desired, specify a destination field and the type of the data that is expected in the response. Usually, Web pages return text (ASCII/MBCS) data, however SendHttp also lets you store UNICODE or binary responses.

The resource specified on the SendHTTP component’s URL parameter can be based on any server-side solution that can accept posts, including ISAPI, cgi, and ASP. When using ASP, use the following methods to read data posted in the following types:

Post type | ASP function
Text | Request.Form
UNICODE | CStr(Request.BinaryRead(Request.TotalBytes))
Binary | Request.BinaryRead(Request.TotalBytes)

Use the following ASP functions to send response data of the following types.

Response type | ASP function
Text | Response.Write
UNICODE | Response.BinaryWrite
Binary | Response.BinaryWrite

For an example of a receiving .asp page, see the recvHTTP.asp file, which is installed by default into \Microsoft Site Server\SiteServer\Commerce.


SendSMTP

The SendSMTP component sends an e-mail message to the specified recipient.

  • υFrom (required). Specifies the e-mail address from which the message is to be sent. This is the actual e-mail address (for example, someone@microsoft.com) rather than the name of a field that contains the e-mail address.
  • υSMTP Host (required). Specifies the name or IP address of the SMTP mail server that will be used to transmit the object. This is the actual name of the server rather than the name of a field that contains the name.
  • υDictionary fields for E-mail. These fields specify the locations on the order form or Transport Dictionary of the delivery information to be used for addressing the e-mail message.
    • υTo (required). Specifies the name of the field in the Transport Dictionary that contains the e-mail address to which the message is being sent.
    • υcc. Specifies the name of the field in the Transport Dictionary that contains the e-mail addresses to which copies of the message are to be sent.
    • υSubject. Specifies the name of the field in the Transport Dictionary that contains the text that is to be displayed in the Subject field of the e-mail message.
    • υCharacter Set for Subject. Specifies the character set that is to be used to encode the subject of this email message. This drop-down list displays the character sets currently installed on this computer.
    • υMessage Body. Specifies the name of the field in the Transport Dictionary that contains the message that is to be included in the body of the e-mail message.
  • υMessage Body contains. These options specify the format of the message that is to be sent.
    • υMIME header and body. Specifies that the business data object is already encapsulated in a MIME header. If you click this option, the component uses the character set and header already encapsulated with the message instead of generating its own MIME header and using the character set specified in the Character Set for Subject field. Use this option if you use the EncodeSMIME component with the Plain Text option to encode the business data object.
    • υText Body. Specifies that the business data object consists of straight ASCII text and no further processing is needed.
    • υBinary body. Specifies that the business data object is a binary blob. The SendSMTP component will base64-encode it before sending.

Remarks

The SendSMTP component sends a business data object as an e-mail message to an SMTP mail server. If you are using Microsoft® Exchange and Outlook, you can run a Visual Basic script to invoke an OrderPipeline object (but not an MtsPipeline or MtsTxPipeline) on the Exchange server to process the received messages. For an example, see the Recvsmtp.vbs script installed in the \Microsoft Site Server\SiteServer\Commerce folder (see Creating a Receiving Agent for SMTP Transport).

Note

In order for SendSMTP to properly support character set conversion, the corresponding Windows NT code page must be installed on the computer. For example, the US version of Windows NT installation does not include the Japanese code page (code page 932), which must be present to convert Unicode to iso-2022-jp. For information on installing a code page, see Knowledge Base article Q164948.


Test SendSMTP

Use this property page to send a test email message to check the configuration of the SendSMTP component.

  • υEmail address to send text message to. Specifies the complete e-mail address to which the message is to be sent.


SimpleCanadaTax

The SimpleCanadaTax component, which appears in the Tax stage of an order processing pipeline, calculates the Goods and Services Tax (GST) and Provincial Sales Tax (PST) used in Canada, and writes the computed values to the order._tax_total_pst, order._tax_total_gst, order._tax_total, and item._tax_total fields. SimpleCanadaTax always sets _tax_included name/value pairs to zero (0) for both the item and the order. The data used by the SimpleCanadaTax component is usually provided by the QueryProdInfoADO component.

  • υKey. (Read-only) The name of a property on the order form used to specify tax method. The value of this property is compared to the string specified in the Method field to determine whether to apply the tax to the order.
  • υApply when. Specifies when to apply the tax.
    • υEqual to Country. Specifies that the tax will be applied only if the value of the property specified for Key is the same as the string specified in the Country field.
    • υHas any value. Specifies that the tax will be applied when the value of the property specified for Key has any value on the order form. If you select this option, the Country field should be left blank.
    • υAlways. Specifies that the tax is always applied to the order.
  • υCountry. If Equal to Country is selected, specifies a string that the component compares with the value of ship_to_country on the order form to determine whether to apply the tax to the order. The tax will be applied only if there is an exact match.
  • υGST Item Key. Specifies the name of a field on the order form in which the GST tax rate is stored.
  • υPST Item Key Prefix. Specifies a prefix that the SimpleCanadaTax component appends to the name of the province to which the item is being shipped (from the ship_to_state field on the order form). The component then uses this concatenated string to look up the PST tax rate on the order form.
  • υProvince List. Specifies the list of provinces (separated by spaces) for which to compute the tax. This value is used to look up the tax rate in the database table column. Optionally, multiple provinces can be specified.

Remarks

Note

The SimpleCanadaTax component is a simple tool for you to use to calculate tax rates. Microsoft strongly recommends that you have an independent tax professional verify all applicable tax rates and data generated by this component before you use such information for personal or business purposes.

GST is common throughout Canada and almost all goods and services have a GST. If a product is taxed, the GST rate is the same throughout Canada. However, some products are not taxed and some service merchants (making less than a given amount) may elect to not charge GST. Each province has its own PST, usually a fixed rate for all products, but PST still depends on the product (although a province may elect to tax an item not taxed by another province).

When shipping from one province to another you do not pay any PST tax. Although not common, a product may have PST but not GST. The reverse is also true.

SimpleCanadaTax always sets _tax_included fields to zero (0) for both the item and the order (see Using the Tax Components). The component does not handle fractions of base currency units; all calculations are rounded to the nearest whole unit.

The combination of the Key, Apply when, and Country fields determine whether tax should be applied, but only if the order is being shipped to one of the provinces in the Province List.

The SimpleCanadaTax component first checks the Apply when value. If it is set to Always, the tax is always applied to the order. If Apply when is set to Has any value, the tax is applied to the order whenever the order form contains any value for ship_to_country. If Apply when is set to Equal to Country, the component does a comparison between the value of ship_to_country on the order form and the text string in the Country field on this property page. If there is a match, the tax is applied.

If the component determines that tax should be applied, it then compares the value of ship_to_state on the order form to the list of provinces specified in Province List. If there is a match, indicating that the order is being shipped to a province where tax should be collected, the component does two things. First, it retrieves the GST tax rate from the field on the order form identified by GST Item Key. Second, it appends the prefix specified in PST Item Key Prefix to the name of the province to which the item is being shipped (from the ship_to_state field on the order form). The component then uses this concatenated string to look up the PST tax rate on the order form.

Example

To specify that a 2% GST tax rate and a 4.5% Alberta PST tax rate is charged for an item shipped to Alberta, Canada, do the following:

  1. Add a column for the GST rate to your product table. The tax rate should be specified as a real number:
    can_prod_gst_tax_rate       real  NOT NULL
  2. Add a column for the Alberta PST rate to your product table. The tax rate should be specified as a real number:
    can_prod_pst_tax_rate_alb   real  NOT NULL
  3. Assign tax rates to each product in your product table using an SQL script. For this example, assign the 2% GST tax rate and the 4.5% Alberta PST tax rate to Product ABC. Type 2.0 into the can_prod_gst_tax_rate column and 4.5 into the can_prod_pst_tax_rate_alb column in the Product ABC row.
  4. Double-click the SimpleCanadaTax icon in the Win32®-based Pipeline Editor, or click the Edit link for the component in the ASP-based Pipeline Editor and enter the following in the resulting property page.
Field | Value
Apply when | Has any value
Country | CAN
GST Item Key | _product_can_prod_gst_tax_rate
PST Item Key Prefix | _product_can_prod_pst_tax_rate
Province List | alb

Note

If the customer types a country or province on the OrderForm that is not specified in the SimpleCanadaTax component configuration, the values of the _tax_total and _tax_included name/value pairs on the order and on the items will not be set.

Related Topics

  • υComponent Coordination


SimpleJapanTax

The SimpleJapanTax component, which appears in the Tax stage of an order processing pipeline, computes a tax rate for the Japanese tax model. It can be used for any country that uses a similar model. The component handles fractions of currency units only at the item level; order-level calculations (order._tax_total and order._tax_included) are rounded to the nearest whole unit.

  • υKey. (Read-only) The name of a property on the order form used to specify tax method. The value of this property is compared to the string specified in the Method field to determine whether to apply the tax to the order.
  • υApply when. Specifies when to apply the tax.
    • υEqual to Country. Specifies that the tax will be applied only if the value of the property specified for Key is the same as the string specified in the Country field.
    • υHas any value. Specifies that the tax will be applied when the value of the property specified for Key has any value on the order form. If you select this option, the Country field should be left blank.
    • υAlways. Specifies that the tax is always applied to the order.
  • υCountry. If Equal to Country is selected, specifies a string that the component compares with the value of ship_to_country on the order form to determine whether to apply the tax to the order. The tax will be applied only if there is an exact match.
  • υInclude Item Key. Specifies the name of the field in the item Dictionary that indicates whether the tax is already included in the item’s price. This field is assumed to contain a Boolean value that indicates whether or not the tax rate is to be added to the line item (in which case item._tax_total is set to the tax amount and item._tax_included is set to zero), or whether the tax rate is included in the price (in which case item._tax_included is set to the tax amount and item._tax_total is set to zero).
  • υRate Item Key. Specifies the name of the field in the item that contains the tax rate charged for the item.
Note

The SimpleJapanTax component is a simple tool for you to use to calculate tax rates. Microsoft strongly recommends that you have an independent tax professional verify all applicable tax rates and data generated by this component before you use such information for personal or business purposes.

Remarks

The combination of the Key, Apply when, and Country fields determine whether tax should be applied, but only if tax is not already included in the item’s price.

The SimpleJapanTax component first checks the Apply when value. If it is set to Always, the tax is always applied to the order. If Apply when is set to Has any value, the tax is applied to the order whenever the order form contains any value for ship_to_country. If Apply when is set to Equal to Country, the component does a comparison between the value of ship_to_country on the order form and the text string in the Country field on this property page. If there is a match, the component applies the tax whose value is stored in the field specified in Rate Item Key.

Example

To specify that a 9.54% tax rate is included within an item’s price and is not included in another item’s price for items in Japan, do the following:

  1. Add a column for the included tax rate to your product table. The tax rate should be specified as a smallint number:
    jpn_prod_tax_included   smallint  NOT NULL,
  2. Add a column for the tax rate to your product table. The tax rate should be specified as a real number:
    jpn_prod_tax_rate       real     NOT NULL,
  3. Assign tax rates and tax included values to each product in your product table using an SQL script. This example uses two products, Product Included and Product Excluded. Assign Product Included the 9.54% tax rate with the tax included in the product price. Type 9.54 into the jpn_prod_tax_rate column and 1 (True), in the jpn_prod_tax_included column in the Product Included row. Assign Product Excluded the 9.54% tax rate with the tax not included in the product price. Type 9.54 into the jpn_prod_tax_rate column and 0 (False), in the jpn_prod_tax_included column in the Product Excluded row.
  4. Double-click the SimpleJapanTax icon in the Win32®-based Pipeline Editor, or click the Edit link for the component in the ASP-based Pipeline Editor and enter the following in the resulting property page.
Field | Value
Apply when | Has any value
Country | JPN
Include Item Key | _product_jpn_prod_tax_included
Rate Item Key | _product_jpn_prod_tax_rate

Note

If the customer types a country in the OrderForm that is not specified in the SimpleJapanTax component configuration, the values of the _tax_total and _tax_included name/value pairs on the order and on the items will not be set.

Related Topics

  • υComponent Coordination


SimpleUSTax

The SimpleUSTax component, which appears in the Tax stage of an order processing pipeline, applies a given rate to any order sent to a specified state in the United States.

  • υKey. (Read-only) The name of a property on the order form used to specify tax method. The value of this property is compared to the string specified in the Method field to determine whether to apply the tax to the order.
  • υApply when. Specifies when to apply the tax.
    • υEqual to Country. Specifies that the tax will be applied only if the value of the property specified for Key is the same as the string specified in the Country field.
    • υHas any value. Specifies that the tax will be applied when the value of the property specified for Key has any value on the order form. If you select this option, the Country field should be left blank.
    • υAlways. Specifies that the tax is always applied to the order.
  • υCountry. If Equal to Country is selected, specifies a string that the component compares with the value of ship_to_country on the order form to determine whether to apply the tax to the order. The tax will be applied only if there is an exact match.
  • υState Rate List. Specifies each state for which tax is collected, and the tax rate for that state. These are listed as fields in the form state:rate, with state expressed as the two-character postal code abbreviation and rate expressed as a decimal value. For example, an 8.6% tax rate for the state of Washington is entered as WA:8.6. Multiple state/rate pairs are separated by a space. You can enter an at sign (@) (the wildcard character) to represent all states that are not explicitly listed (for example: @:0).
Note

The SimpleUSTax component is a simple tool for you to use to calculate tax rates. Microsoft strongly recommends that you have an independent tax professional verify all applicable tax rates and data generated by this component before you use such information for personal or business purposes.

Remarks

The combination of the Key, Apply when, and Country fields determine whether tax should be applied, but only if the state to which the order is being shipped is listed in the State Rate List.

The SimpleUSTax component first checks the Apply when value. If it is set to Always, the tax is always applied to the order. If Apply when is set to Has any value, the tax is applied to the order whenever the order form contains any value for ship_to_country. If Apply when is set to Equal to Country, the component does a comparison between the value of ship_to_country on the order form and the text string in the Country field on this property page. If there is a match, the component applies the tax.

If the component determines that tax should be applied, it then compares the value of ship_to_state on the order form to the list of states specified in State Rate List. If there is a match, indicating that the order is being shipped to a state where tax should be collected, the component applies the tax rate specified for that state, and sets the values for item._tax_total, item._tax_included, order._tax_total, order._tax_included.

SimpleUSTax always sets _tax_included name/value pairs to zero (0) for both the item and the order. The component does not handle fractions of base currency units; all calculations are rounded to the nearest whole unit.

If the customer types a country or state in the OrderForm that is not specified in the SimpleUSTax component configuration, the values of the _tax_total and _tax_included name/value pairs on the order and on the items will not be set.

Related Topics

  • υComponent Coordination


SimpleVATTax

The SimpleVATTax component, which appears in the Tax stage of an order processing pipeline, calculates the Value Added Tax (VAT).

  • υKey. (Read-only) The name of a property on the order form used to specify tax method. The value of this property is compared to the string specified in the Method field to determine whether to apply the tax to the order.
  • υApply when. Specifies when to apply the tax.
    • υEqual to Country. Specifies that the tax will be applied only if the value of the property specified for Key is the same as the string specified in the Country field.
    • υHas any value. Specifies that the tax will be applied when the value of the property specified for Key has any value on the order form. If you select this option, the Country field should be left blank.
    • υAlways. Specifies that the tax is always applied to the order.
  • υCountry. If Equal to Country is selected, specifies a string that the component compares with the value of ship_to_country on the order form to determine whether to apply the tax to the order. The tax will be applied only if there is an exact match.
  • υRate Item Key. Specifies the name of the field in the item Dictionary that contains the tax rate charged for the item.
Note

The SimpleVATTax component is a simple tool for you to use to calculate tax rates. Microsoft strongly recommends that you have an independent tax professional verify all applicable tax rates and data generated by this component before you use such information for personal or business purposes.

Remarks

SimpleVATTax always sets _tax_total name/value pairs to zero (0) for both the item and the order. The component does not handle fractions of currency units; all calculations are rounded to the nearest whole unit.

The combination of the Key, Apply when, and Country fields determine whether tax should be applied.

The SimpleVATTax component first checks the Apply when value. If it is set to Always, the tax is always applied to the order. If Apply when is set to Has any value, the tax is applied to the order whenever the order form contains any value for ship_to_country. If Apply when is set to Equal to Country, the component does a comparison between the value of ship_to_country on the order form and the text string in the Country field on this property page. If there is a match, the component applies the tax whose value is stored in the field specified in Rate Item Key.

Example

To specify that a VAT tax rate of 6.5% is charged for an item in Germany, do the following:

  1. Add a column for the VAT rate in Germany to your product table. The tax rate should be specified as a real number:
    ger_vat_tax_rate   real  NOT NULL
  2. Assign tax rates to each product in your product table using an SQL script. For this example, assign the 6.5% VAT rate to Product ABC. Type 6.5 into the ger_vat_tax_rate column in the Product ABC row.
    3. Double-click the SimpleVATTax icon in the Win32-based Pipeline Editor, or click the Edit link for the component in the ASP-based Pipeline Editor and enter the following in the resulting property page.
Field | Value
Apply when | Always
Country | GER
Rate Item Key | _product_get_vat_tax_rate

If the customer types a country on the OrderForm that is not specified in the SimpleVATTax component configuration, the values of the _tax_total and _tax_included name/value pairs on the order and on the items will not be set.

Related Topics

  • υComponent Coordination


SQLItem

The SQLItem component runs a SQL query for each item in the items list, passing the specified OrderForm fields as parameters to the query. These fields can include name/value pairs from either the order or the item Dictionary.

Note

The SQLItem component is included in Commerce Server 3.0 only for backward compatibility with sites created in Commerce Server 2.0, in which the database connection is provided by the Content object in the Pipe Context. Commerce Server 3.0 sites should use the SQLItemADO component.

  • υQuery. Specifies either the full SQL text of the query that is executed by this component or the name of a query whose full SQL text is stored in the Content object
  • υParameter List. Specifies the parameters that the component passes to the query. If multiple parameters are specified, each parameter is separated from the next by a single space. The parameter count passes the query the number of line items on the order. The parameter index passes the query the zero-based index number of this line item. The parameter order.fieldname passes the value of the specified field on the order form. The parameter item.fieldname passes the value of the specified field in the item Dictionary.

Remarks

You can pass name/value pairs from the order Dictionary as parameters to both the SQLItem and SQLOrder components. However, these components are not identical in the way that they use these name/value pairs.

The SQLOrder component executes the query that you specify once. This query cannot take parameter values from the items list.

The SQLItem component executes the query for each item in the items list. If you reference a name/value pair on the order Dictionary as a parameter to SQLItem, that name/value pair is passed as a parameter to each execution of the specified query. For example, if you use an INSERT query as the SQL command, and you specify order.order_id as a parameter, and the items list contains nine items, the value of order.order_id will be inserted nine times.


SQLItemADO

The SQLItemADO component runs a query for each item in the items list, passing the specified OrderForm fields as parameters to the query. These fields can include name/value pairs from either the order or the item Dictionary.

  • υConnection string. Specifies the connection string used for connecting to the database. The connection string must include either the full connection string (the data source name (DSN), database login ID, and database password) or the name of a named connection stored in the connection map. If this field is blank, the default connection string is used.
  • υQuery. Specifies either the full SQL text of the query that is executed by this component or the name of a query whose full SQL text is defined in the site’s global.asa file.
  • υParameter List. Specifies the parameters that the component passes to the query. If multiple parameters are specified, each parameter is separated from the next by a single space. The parameter count passes the query the number of line items on the order. The parameter index passes the query the zero-based index number of this line item. The parameter order.fieldname passes the value of the specified field on the order form. The parameter item.fieldname passes the value of the specified field in the item Dictionary.


SQLOrder

The SQLOrder component runs a SQL query once per order, passing the specified order parameters to the query.

Note

The SQLOrder component is included in Commerce Server 3.0 only for backward compatibility with sites created in Commerce Server 2.0, in which the database connection is provided by the Content object. Commerce Server 3.0 sites should use the SQLOrderADO component.

  • υQuery. Specifies either the full SQL text of the query that is executed by this component or the name of a query whose full SQL text is stored in the Content object.
  • υParameter List. Specifies the parameters that the component passes to the query. If multiple parameters are specified, each parameter is separated from the next by a single space. The parameter count passes the query the number of line items on the order. The parameter order.fieldname passes the value of the specified field on the order form.


SQLOrderADO

The SQLOrder component runs a SQL query once per order, passing the specified order parameters to the query. The SQLOrderADO component uses ActiveX™ Data Objects (ADO) to interface with the data source, and therefore supports Microsoft® Transaction Server (MTS) transactions.

  • υConnection string. Specifies the connection string used for connecting to the database. The connection string must include either the full connection string (the data source name (DSN), database login ID, and database password) or the name of a named connection stored in the connection map. If this field is blank, the default connection string is used.
  • υQuery. Specifies either the full SQL text of the query that is executed by this component or the name of a query whose full SQL text is defined in the site’s global.asa file.
  • υParameter List. Specifies the parameters that the component passes to the query. If multiple parameters are specified, each parameter is separated from the next by a single space. The parameter count passes the query the number of line items on the order. The parameter order.fieldname passes the value of the specified field on the order form. The parameter sum.fieldname passes the query the sum of a particular field on the order, while sumq.fieldname passes the sum times the respective quantities.
  • υChild Object Name. Specifies the name of a field to which the data is written. The component uses the specified field only if the Use Child Object check box is selected.
  • υUse Child Object. Specifies whether the component is to use the object specified in the Child Object Name field. If the check box is not selected, the component assumes that no child object exists.


TableHandling

The TableHandling component, which appears in the Handling stage of an order processing pipeline, sets the value of _handling_total on the order form by using values retrieved from the database.

Note

This component is used for compatibility with Commerce Server 2.0 sites, in which the database connection is provided by the Content object in the Pipe Context. Commerce Server 3.0 sites should use the TableHandlingADO component.

  • υKey. (Read-only) The name of a property on the order form used to specify handling method. The value of this property is compared to the string specified in the Method field to determine whether to apply the handling charge to the order.
  • υApply when. Specifies when to apply the handling charge.
    • υEqual to Method. Specifies that the handling charge should be applied if the value of the field specified for Key is the same as the string specified in the Method field.
    • υHas Any Value. Specifies that the handling charge should be applied when the value of the field specified for Key has any value on the order form. If you select this option, the Method field should be left blank.
    • υAlways. Specifies that the handling charge is always applied to the order.
  • υMethod. If Equal to Method is selected, specifies a string that the component compares with the value of shipping_method on the order form to determine whether to apply the handling charge to the order. The handling charge will be applied only if there is an exact match.
  • υBasis Item Key. Specifies the property of the item that is used to compute the handling charge. The component computes the charge by multiplying the value retrieved by the database query by the sum of the property specified for Basis Item Key. For example, you might base the handling charge on the quantity of the items, and the Basis Item Key might be sum.quantity. If the order contains two items, one item with a quantity of four and the other item with a quantity of two, then the basis sum is six. The component multiplies the handling charge by six. See Specifying the Basis Item Key.
  • υQuery. Specifies either the full SQL text of the query that is executed by this component or the name of a query whose full SQL text is stored in the Content object.
  • υOrder Key. Specifies the property of the order as a whole that is used to compute the handling charge. This key is the name of a column in a database table that specifies a per-order handling charge. This parameter is optional; if none is specified, it defaults to ship_to_zip.
  • υItem Key. Specifies the property of each item that is used to compute the handling charge. This key is the name of a column in a database table that specifies a per-item handling charge. This parameter is optional; if none is specified, it defaults to cost.

Remarks

The combination of the Key, Apply when, and Method fields determine whether the handling should be applied to the order.

The TableHandling component first checks the Apply when value. If it is set to Always, the handling charge is always applied to the order. If Apply when is set to Has any value, the handling charge is applied to the order whenever the order form contains any value for shipping_method. If Apply when is set to Equal to Method, the component does a comparison between the value of shipping_method on the order form and the text string in the Method field on this property page. If there is a match, the handling charge is applied.

If the component determines that the handling charge should be applied, it then executes the query specified in Query. This query retrieves the per-item and per-order handling charges from the database, and then uses the value of the Basis Item Key to compute the handling charge.

The Method name, the aggregated basis, and the value of the location are given as arguments to the query, which must return a single number as a result. With some databases, the query must refer to all three variables, even if it does not need them (see the following example):

select cost, :2, :3 from shipping_costs
where min_weight <= :1 and max_weight > :1

The :2 and :3 refer to the location and method, respectively. These are the database column number references. The component ignores the return fields after the first, but some databases will issue an error if you do not refer to them at all. The :1 refers to the product weight.

Related Topics

  • υComponent Coordination


TableHandlingADO

The TableHandlingADO component, which appears in the Handling stage of an order processing pipeline, sets the value of _handling_total on the order form by using values retrieved from the database.

  • υKey. (Read-only) The name of a property on the order form used to specify handling method. The value of this property is compared to the string specified in the Method field to determine whether to apply the handling charge to the order.
  • υApply when. Specifies when to apply the handling charge.
    • υEqual to Method. Specifies that the handling charge should be applied if the value of the field specified for Key is the same as the string specified in the Method field.
    • υHas Any Value. Specifies that the handling charge should be applied when the value of the field specified for Key has any value on the order form. If you select this option, the Method field should be left blank.
    • υAlways. Specifies that the handling charge is always applied to the order.
  • υMethod. If Equal to Method is selected, specifies a string that the component compares with the value of shipping_method on the order form to determine whether to apply the handling charge to the order. The handling charge will be applied only if there is an exact match.
  • υConnection string. Specifies the connection string used for connecting to the database. The connection string must include either the full connection string (the data source name (DSN), database login ID, and database password) or the name of a named connection stored in the connection map. If this field is blank, the default connection string is used.
  • υQuery. Specifies either the full SQL text of the query that is executed by this component or the name of a query whose full SQL text is defined in the site’s global.asa file.
  • υParameter List. Specifies the parameters that the component passes to the query. The parameter count passes the query the number of line items on the order. The parameter order.fieldname passes the value of the specified field on the order form. The parameter sum.fieldname passes the query the sum of a particular field on the order, while sumq.fieldname passes the sum times the respective quantities. If multiple parameters are specified, each parameter is separated from the next by a single space.
  • υColumn. Specifies the name of the column in the database that contains the handling charge.

Remarks

The combination of the Key, Apply when, and Method fields determine whether the handling charge should be applied to the order.

The TableHandlingADO component first checks the Apply when value. If it is set to Always, the handling charge is always applied to the order. If Apply when is set to Has any value, the handling charge is applied to the order whenever the order form contains any value for shipping_method. If Apply when is set to Equal to Method, the component does a comparison between the value of shipping_method on the order form and the text string in the Method field on this property page. If there is a match, the handling charge is applied.

If the component determines that the handling charge should be applied, it then executes the query specified in Query, which retrieves the handling charge from the database column specified in Column. The component then computes the handling charge.

Related Topics

  • υComponent Coordination


TableShipping

The TableShipping component, which appears in the Shipping stage of an order processing pipeline, sets the value of _shipping_total on the order form by using values retrieved from the database.

Note

The TableShipping component is included in Commerce Server 3.0 only for backward compatibility with sites created in Commerce Server 2.0. Commerce Server 3.0 sites should use TableShippingADO.

  • υKey. (Read-only) The name of a property on the order form used to specify shipping method. The value of this property is compared to the string specified in the Method field to determine whether to apply the shipping charge to the order.
  • υApply when. Specifies when to apply the shipping charge.
    • υEqual to Method. Specifies that the shipping charge should be applied if the value of the field specified for Key is the same as the string specified in the Method field.
    • υHas Any Value. Specifies that the shipping charge should be applied when the value of the field specified for Key has any value on the order form. If you select this option, the Method field should be left blank.
    • υAlways. Specifies that the shipping charge is always applied to the order.
  • υMethod. If Equal to Method is selected, specifies a string that the component compares with the value of shipping_method on the order form to determine whether to apply the shipping charge to the order. The shipping charge will be applied only if there is an exact match.
  • υBasis Item Key. Specifies the property of the item that is used to compute the shipping charge. The component computes the charge by multiplying the value retrieved by the database query by the sum of the property specified for Basis Item Key. For example, you might base the shipping charge on the quantity of the items, and the Basis Item Key might be sum.quantity. If the order contains two items, one item with a quantity of four and the other item with a quantity of two, then the basis sum is six. The component multiplies the shipping charge by six. See Specifying the Basis Item Key.
  • υQuery. Specifies either the full SQL text of the query that is executed by this component or the name of a query whose full SQL text is stored in the Content object.
  • υOrder Key. Specifies the property of the order as a whole that is used to compute the shipping charge. This key is the name of a column in a database table that specifies a per-order handling charge. This parameter is optional; if none is specified, it defaults to ship_to_zip.
  • υItem Key. Specifies the property of each item that is used to compute the shipping charge. This key is the name of a column in a database table that specifies a per-item handling charge. This parameter is optional; if none is specified, it defaults to cost.

Remarks

The combination of the Key, Apply when, and Method fields determine whether the handling should be applied to the order.

The TableHandling component first checks the Apply when value. If it is set to Always, the shipping charge is always applied to the order. If Apply when is set to Has any value, the shipping charge is applied to the order whenever the order form contains any value for shipping_method. If Apply when is set to Equal to Method, the component does a comparison between the value of shipping_method on the order form and the text string in the Method field on this property page. If there is a match, the shipping charge is applied.

If the component determines that the shipping charge should be applied, it then executes the query specified in Query. This query retrieves the per-item and per-order shipping charges from the database, and then uses the value of the Basis Item Key to compute the shipping charge.

Related Topics

  • υComponent Coordination


TableShippingADO

The TableShippingADO component, which appears in the Shipping stage of an order processing pipeline, sets the value of _shipping_total on the order form by using values retrieved from the database.

  • υKey. (Read-only) The name of a property on the order form used to specify shipping method. The value of this property is compared to the string specified in the Method field to determine whether to apply the shipping charge to the order.
  • υApply when. Specifies when to apply the shipping charge.
    • υEqual to Method. Specifies that the shipping charge should be applied if the value of the field specified for Key is the same as the string specified in the Method field.
    • υHas Any Value. Specifies that the shipping charge should be applied when the value of the field specified for Key has any value on the order form. If you select this option, the Method field should be left blank.
    • υAlways. Specifies that the shipping charge is always applied to the order.
  • υMethod. If Equal to Method is selected, specifies a string that the component compares with the value of shipping_method on the order form to determine whether to apply the shipping charge to the order. The shipping charge will be applied only if there is an exact match.
  • υConnection string. Specifies the connection string used for connecting to the database. The connection string must include either the full connection string (the data source name (DSN), database login ID, and database password) or the name of a named connection stored in the connection map. If this field is blank, the default connection string is used.
  • υQuery. Specifies either the full SQL text of the query that is executed by this component or the name of a query whose full SQL text is defined in the site’s global.asa file.
  • υParameter List. A space-delimited list of parameters for the query identified in the Query setting.
  • υColumn. Specifies the name of the column in the database that contains the shipping charge.

Remarks

The combination of the Key, Apply when, and Method fields determine whether the shipping charge should be applied to the order.

The TableShippingADO component first checks the Apply when value. If it is set to Always, the shipping charge is always applied to the order. If Apply when is set to Has any value, the shipping charge is applied to the order whenever the order form contains any value for shipping_method. If Apply when is set to Equal to Method, the component does a comparison between the value of shipping_method on the order form and the text string in the Method field on this property page. If there is a match, the shipping charge is applied.

If the component determines that the shipping charge should be applied, it then executes the query specified in Query, which retrieves the shipping charge from the database column specified in Column. The component then computes the shipping charge.

The Parameter List is used to specify parameters to the query, which usually include a basis for the table lookup. The basis can be total cost of the order, or a merchant-defined value such as weight.

For parameters, you can use any of the following values.

Basis Item Key prefix | Description
order.fieldname | The value of the specified field, where fieldname is a property on the order form.
sum.fieldname | The sum of value of the specified field for each item, where fieldname is a property in the item list.
sumq.fieldname | The sum of value of the specified field for each item, where fieldname is a property in the item list, times the quantity of that item.
count | The number of line items in the order form. (Does not depend on quantity of each item.)

The following table illustrates some useful values for Basis Item Key:

Example Basis Item Key | Result
order._oadjust_subtotal | Subtotal on the order form.
sum.quantity | Sum of all quantities (total number of items ordered).
sum._oadjust_adjustedprice | Sum of adjusted prices.
sumq._iadjust_currentprice | Sum of current price times quantity for all items in the order.
sumq._product_weight | Total weight of order. (Assumes that the weight column exists in the product table, and that the query used by QueryProdInfoADO includes this field.)

For example, if sumq._product_weight is specified, and if the order has two items, one item weighing 2 pounds with a quantity of 3 and the other item weighing 4 pounds with a quantity of 1, then the basis value is 10 pounds.

Related Topics

  • υHow to use Table Shipping


ValidateCCNumber

The ValidateCCNumber component, which appears in the Purchase Check stage of an order processing pipeline, performs a checksum test on the credit-card number (for the most widely used cards) to ensure that its format is correct. If it fails, a pur_badcc error is generated and sent to the MessageManager object, and the component returns error level 2.

  • υKey. (Read-only) The name of a property on the order form used to specify the payment method. The value of this property is compared to the string specified in the Method field to determine whether to verify the credit card.
  • υApply when. Specifies when to check the format of the credit-card number.
    • υEqual to Method. Specifies that the format of the number should be checked if the value of the field specified for Key is the same as the string specified in the Method field.
    • υHas Any Value. Specifies that the format of the number should be checked when the value of the field specified for Key has any value on the order form. If you select this option, the Method field should be left blank.
    • υAlways. Specifies that the format of the credit-card number is always checked.
  • υMethod. If Equal to Method is selected, specifies a string that the component compares with the value of _payment_method on the order form to determine whether to check the format of the credit-card number. The format of the number will be checked only if there is an exact match.

Remarks

ValidateCCNumber first determines whether the credit card type specified in order.cc_type is one of the types accepted by this component. Accepted types include Visa, MasterCard, American Express, and Discover.

If the specified card is one of these types, ValidateCCNumber checks the values stored in order._cc_expmonth and order._cc_expyear, to confirm that the credit card has not expired. If the credit card has expired, ValidateCCNumber retrieves the pur_cc_expired message from the MessageManager, and writes this message to the _Purchase_Errors collection.

Otherwise, the component runs a checksum on the number stored in order._cc_number to ensure that the number is properly formed. For example, if the specified credit card type is Discover, a well-formed number must begin with a 3 and must consist of 16 digits. If the credit card checksum fails, ValidateCCNumber writes a _pur_badcc message to the _Purchase_Errors collection.

Note

You are not required to specify a value in order.cc_type . If you do not, no checksum is performed on any value stored in order._cc_number, but the date passed in order._cc_expmonth and order._cc_expyear is performed.

ValidateCCNumber tests only for well-formed credit card numbers. It will work only on certain types of cards that use the standard credit card number format (such as Visa, MasterCard, American Express, and Discover).

Related Topics

  • υComponent Coordination


VerifyDigitalSig

The VerifyDigitalSig component, which usually appears in the Verify Digital Signature stage of a Commerce Interchange Receive pipeline, verifies the digital signature on the data stored in the working_data field on the Transport Dictionary.

  • υVerify Signature and Message XML Format. Specifies that both the digital signature and the original message have been formatted using XML.
  • υVerify Signature and Message PKCS7 Standard. Specifies that both the digital signature and the original message have been formatted using the Public Key Crypto System (PKCS).
  • υVerify Signature Only PKCS7 Standard. Specifies that only the digital signature (and not the original message) has been formatted using the Public Key Crypto System (PKCS).
  • υMessage Field. Specifies the field in the Transport Dictionary from which the VerifyDigitalSig component reads the message data.
  • υSignature. (Used only if you have selected Verify Signature Only PKCS7 Standard.) Specifies the field in the Transport Dictionary from which the VerifyDigitalSig component reads the digital signature.
  • υVerified Message Field. Specifies the field in the Transport Dictionary to which the VerifyDigitalSig component writes the verified message.
    • υText Output. Specifies that the message is to be written into the field on the Transport Dictionary in text format.
    • υBinary Output. Specifies that the message is to be written into the field on the Transport Dictionary in binary format.
  • υWrite Certificate used to verify signature to field. Specifies the name of the field on the Transport Dictionary to which the component writes the name of the certificate used to verify the digital signature. If the verification fails, the field contains NULL.

Remarks

If the digital signature is verified, the stream of bytes stored in working_data, minus the digital signature, is re-written to the working_data name/value pair, overwriting the original data stored in that name/value pair.

Related Topic

  • υDigitalSig


Commerce Server Object Reference__

The Commerce Server objects are instances of Microsoft® ActiveX® server components that provide the run-time environment for the presentation of Commerce Server sites. These components are registered on your system as ActiveX server components when you install Commerce Server. Like the objects included with Active Server Pages (ASP), Commerce Server objects support methods and properties that you call and set from within the Microsoft® Visual Basic® Scripting Edition (VBScript) or Microsoft® JScript™ server-side code that runs your Commerce Server site.

Commerce Server objects provide an extensive set of services that ASP does not provide; services that simplify and automate many of the tasks that you would have to perform manually to build a working site from ASP components alone. Such tasks include the reliable maintenance of state data across multiple sessions and the automated processing of order data through the order processing pipeline (OPP).

This section describes the Commerce Server objects, and includes definitions of the methods and properties that they support.

Commerce Server defines the following server objects.

Object | Description
AdminFile | Provides access to server-side files.
AdminSite | Localizes information about a Commerce Server site, including data source names (DSNs), queries, and the path to the pipeline configuration file, within a single object.
AdminWebServer | Provides access to read-only properties of the site.
ConfigurationCacheHelper | Caches a pipeline configuration in memory, helping to reduce the performance penalty associated with accessing a pipeline configuration (.pcf ) on disk.
DataFunctions | Supports a collection of functions that validate the format of data for database storage or for processing by the pipeline.
DBStorage | Supports mapping Dictionary and SimpleList objects to and from a database, primarily for the storage of receipt and order information.
Dictionary | Provides for the in-memory storage of name/value pairs.
FileDocument | Supports saving and restoring information contained in any persistable object to and from disk.
MessageManager | Stores error messages in multiple languages that the OPP components use to describe error conditions.
MicroPipe | Enables embedding and running a single pipeline component on an ASP page without requiring a pipeline and a .pcf file.
MtsPipeline | Loads and executes a pipeline configuration. This object is registered under Microsoft® Transaction Server (MTS)as transactions not supported.
MtsTxPipeline | Loads and executes a pipeline configuration. This object is registered under MTS as transactions required.
OrderForm | Supports the in-memory storage of customer and purchase information for the current shopping session.
Page | Simplifies the layout of HTML pages and the interaction between these pages and the data sources used by your site.
Predictor | Enables Intelligent Cross-Sell by suggesting other items that a customer might be interested in.
SimpleDBDS | Maps an Active Directory Service (ADS) to a standard database table, so that a Commerce Server site can maintain customer information using Personalization & Membership ( P&M) while retaining a pre-existing database.
SimpleList | General-purpose list of Variants.
StandardSManager | Facilitates the creation, deletion, and retrieval of shopper IDs.

The following implementations of the Dictionary object are used in typical Commerce Server sites.

Dictionary Implementation | Description
PipeContext | Passed through the pipeline as a holder of properties needed by pipeline components.
QueryMap | Contains query descriptions that may be used by various objects.
Site | Provides access to the Commerce Server site configuration stored in the Site.csc file.

The following objects are included to support applications developed for earlier versions of Commerce Server, but are not recommended for use in new applications.

Object | Description
Content | For backward compatibility only.
Datasource | For backward compatibility only.
OrderPipeline | For backward compatibility only.
TrafficLogFile | For backward compatibility only.
TrafficTable | For backward compatibility only.

This document does not include components that run within the pipeline. For information on the pipeline components, see The Order Processing Pipeline and The Commerce Interchange Pipeline.

This document assumes that you are familiar with Microsoft® Visual Basic® Scripting Edition (VBScript) or with Microsoft® JScript, and with the use of one of these languages within Active Server Pages (ASP).

For information about VBScript and ASP, see the Microsoft® Internet Information Server (IIS) 4.0 documentation.


Commerce Server Object Parameters in VBScript

As you script Commerce Server sites, you should be particularly aware of two features of Microsoft® Visual Basic® Scripting Edition (VBScript) that figure prominently in the use of the methods implemented by Commerce Server objects.

First, as with other Microsoft® ActiveX® server objects, all variables passed to Commerce Server objects appear to VBScript as a single data type: Variant. A Variant is a special kind of data type that can contain different kinds of information, depending on how it is used. Because Variant is the only data type in VBScript, it is also the data type returned by all functions in VBScript. If you call functions documented in this Object Reference from Visual Basic, you should declare the variables that you pass to these functions as Variants.

Second, many of the methods implemented in Commerce Server objects take optional parameters. This means that if you do not supply a value for these parameters, a default value is assumed. How you reference optional parameters depends upon a parameter’s position in the parameter list.

The following example uses the DataFunctions object’s ValidateNumber method to illustrate the various ways in which you use optional parameters. This method, which determines whether a value that you supply falls within a given numerical range, has the following syntax:

DataFunctions.ValidateNumber(Value, MinimumValue, MaximumValue)

The Value parameter references the number that you want to test against a set of range values. MinimumValue and MaximumValue designate the low and high ends of that range. If Value falls within the designated range, ValidateNumber returns True; otherwise, False.

However, because the MinimumValue and MaximumValue parameters are optional, you can call this method in several ways. For example, if you are interested only in determining whether the value that you have supplied exceeds a certain minimum, call ValidateNumber as follows:

bValid = datafunctions.ValidateNumber(Value, MinimumValue)

Because MaximumValue is not specified, its default value is assumed, which means that the parameter is ignored in the range evaluation.

If, however, you wanted to test a value against a maximum value, but not against a minimum value, you would call ValidateNumber as follows:

bValid = datafunctions.ValidateNumber(Value, Null, MaximumValue)

Note that you cannot simply eliminate the Null placeholder for MinimumValue in this case, because MinimumValue appears to the left, in the parameter list, of a value that you specify. This parameter’s value is specified as Null, which means that the parameter is ignored in the range valuation, and Value is tested only against MaximumValue.

Finally, you can call ValidateNumber as follows:

bValid = datafunctions.ValidateNumber(Value)

In this case, you do not have to specify Null for either optional argument, because this call uses no optional argument that appears to the left of another, specified optional argument. Because both MinimumValue and MaximumValue appear at the end of the argument list, and are not referenced, both default to Null, which means that both values are ignored in the valuation.


The AdminFile Object

The AdminFile object provides access to server-side files.

The AdminSite object supports the following methods.

Property | Description
ReadFromBinaryFile | Returns the contents of the specified binary file.
ReadFromFile | Returns the contents of the specified text file.


AdminFile.ReadFromBinaryFile Method

The ReadFromBinaryFile method returns the contents of the specified binary file. The file can contain any type of data, such as a numeric data or a bitmap.

The method returns the appropriate error when the file is not found, or cannot be accessed for reads.

Syntax

AdminFile.ReadFromFile(FileName)

Parameters

FileName
The path and filename to read.

Example

The following example opens the specified file and then uses the Response.BinaryWrite method to download the file to a browser.

Set oFile = Server.CreateObject("Commerce.AdminFiles")
bFileContents = oFile.ReadFromBinaryFile("c:\temp\postcard.jpg")
Response.ContentType = "image/pjpeg"
Response.BinaryWrite bFileContents


AdminFile.ReadFromFile Method

The ReadFromFile method returns the contents of the specified file. The contents of the file are returned as a text string.

The method returns the appropriate error when the file is not found, or cannot be accessed for reads.

Syntax

AdminFile.ReadFromFile(FileName)

Parameters

FileName
The path and filename to read.

Example

The following example opens the specified file and reads its contents into the variable strRet:

Dim strRet
strRet = objAdmin.ReadFromFile("C:\mscs\stores\newstore\newfile.asp")


The AdminSite Object

The AdminSite object provides centralized access to the Commerce Server site configuration, making it easier to configure and maintain a Commerce Server site. The AdminSite object is used by the Site Builder Wizard (which sets the configuration initially), Web-based Administration (WebAdmin), the Commerce Host Administration snap-in for the Microsoft® Management Console (MMC), and by batch files. The object provides read/write access to the configuration properties and has a number of administrative functions that allow administration of Commerce Server sites.

The AdminSite object supports the following properties.

Property | Description
Directory | Currently registered Commerce Server site physical directory.
Status | Read/write property that indicates/specifies whether the Commerce Server site is open or closed.
Version | Returns the version of Commerce Server as an integer (2 for Commerce Server 2.0, and 3 for Commerce Server 3.0).

The AdminSite object supports the following methods.

Method | Description
Create | Creates a Commerce Server site.
Delete | Deletes a Commerce Server site.
Initialize | Initializes the AdminSite object to load information related to the Commerce Server site.
InitializeFromMDPath | Initializes the AdminSite object from a metabase path.
IsValidName | Determines whether a given text string is a valid short name for a Commerce Server site.
ReadDefaultProperties | Reads the properties from the Site.csc file and returns a Dictionary object (the site dictionary) containing these properties.
ReadManagerProperties | Reads the properties from the Site\Manager\Config\Site.csc file and returns a Dictionary object (the site dictionary) containing these properties.
Reload | Resets all application and session objects for the Commerce Server site.
WriteDefaultProperties | Writes the properties from the specified site dictionary to the Site.csc file.
WriteManagerProperties | Writes the properties from the specified site dictionary to the Site\Manager\Config\Site.csc file.


AdminSite Object Overview

The AdminSite object provides methods for administering a site, such as specifying data sources and user accounts. The object keeps a number of properties related to the configuration in the site dictionary, an implementation of a Dictionary object called MSCSSite. These properties include the short and long names of the site, the secure host, the nonsecure host, and the names of other Dictionary objects such as lists of named connection strings and named queries.

All site-related configuration properties are accessed through the site dictionary, and saved in the Site.csc file.

For information about the relationship between the AdminSite object, the site dictionary, and the Site.csc file, see “Managing the Commerce Server Site” in Architecture of a Business-to-Consumer Site in the Commerce documentation..

The AdminSite object is not used in Commerce Server sites themselves. The site configuration properties can be accessed from within Commerce Server site scripting pages by using FileDocument to read the properties into an instance of the site dictionary.

An instance of the AdminSite object is usually created by WebAdmin, the Commerce Server Snap-in for the MMC, and by the Site Foundation Wizard.

To create an AdminSite object, use the Server.CreateObject method, specifying Commerce.AdminSite as follows:

Set AdminSite = Server.CreateObject("Commerce.AdminSite")
Note

Active Server Pages (ASP) scripts that access the Microsoft® Internet Information Server (IIS) metabase require administrator privileges on the computer on which IIS is running. When you execute these scripts from a remote computer, you must connect through a secure connection, such as the Microsoft® Windows NT® Challenge/Response Authentication method. It is suggested that you create a server or directory for your administrative .asp files and set the directory security authentication method to Windows NT Challenge/Response for the server or directory.


AdminSite.Create Method

The Create method creates a Commerce Server site and optionally creates an application and the Config\SQL\SqlSvr and Config\SQL\Oracle subdirectories.

Syntax

AdminSite.Create(ServerInstance, VirtualDirectory, Directory, IsApplication, IsCommerceSite)

Parameters

ServerInstance
Numeric value expressed as a string. Represents a Web site (an instance of the Web server). To obtain a list of server instances, use the GetWebSites method of the AdminWebServer object. For the default Web site, use "1".
VirtualDirectory
String. The Commerce Server site short name (virtual directory).
Directory
String. The physical directory where you want the site.
IsApplication
Boolean. If True, the application is created for the site (this is the same as launching Internet Service Manager, selecting a virtual directory, viewing its properties, and then in the Application Settings section on the Virtual Directory tab, clicking Create). This setting must be True for a Commerce Server site.
IsCommerceSite
Boolean. If True, the method marks the site for administration by Commerce Server and creates the Directory\Config\SQL\SqlSvr and Directory\Config\SQL\Oracle subdirectories. If False, creates the top level Directory only.

Example

The following example calls the AdminSite object's Create method to create an entry in the site object namespace. The SzSite argument contains the site short name, and szSiteRoot contains the physical directory.

AdminSite.Create "1", szSite, szSiteRoot, true, true


AdminSite.Delete Method

The Delete method deletes a Commerce Server site. Removes attributes of the site from the IIS metabase entries only (does not remove directories or databases).

Syntax

AdminSite.Delete()


AdminSite.Directory Property

The Directory property is a string Variant containing the currently registered Commerce Server site physical directory.

Remarks

The valid characters and length for a Web site name are determined by the restrictions on the file system.

Example

Invoked from Active Server Pages (ASP) as:

Response.Write MSCSSite.Directory


AdminSite.Initialize Method

The Initialize method initializes the AdminSite object to load information related to the Commerce Server site. The site is uniquely identified using the site short name and the server instance. The ReadDefaultProperties method uses this information to load the site properties.

Syntax

AdminSite.Initialize(ServerInstance, VirtualDirectory)

Parameters

ServerInstance
Numeric value expressed as a string. Represents a Web site (an instance of the Web server). To obtain a list of server instances, use the GetWebSites method of the AdminWebServer object. For the default Web site, use "1".
VirtualDirectory
String. The Commerce Server site short name (virtual directory).

Remarks

An object must be initialized before any of its other methods (except Create and IsValidName) can be used. An object that has been created by the Create method of the AdminSite object is automatically initialized and does not need an explicit call to its Initialize method.

Example

The following example creates and initializes an AdminSite object for the Clocktower site, which is in the default Web site:

Set AdminSite =Server.CreateObject("AdminSite")
Call AdminSite.Initialize("1", "Clocktower")


AdminSite.InitializeFromMDPath Method

The InitializeFromMDPath initializes the AdminSite object from a specified metabase path.

Syntax

AdminSite.InitializeFromMDPath(MetabasePath)

Parameters

MetabasePath
The metabase path.

Remarks

This method requires a specified metabase path, unlike the Initialize method, which requires a server instance and virtual directory specified separately.

Example

The following example initializes an AdminSite object for the application’s metabase path:

Call CurSite.InitializeFromMDPath(Request.ServerVariables(“APPL_MD_Path”))

The Request.ServerVariables(“APPL_MD_Path”) expression returns the metabase path in the form /LM/W3SVC/1/Clocktower , where LM refers to the Local Machine, W3SVC refers to the Internet Service, 1 is the server instance, and Clocktower is the root of the Web site. This method works only if the application is created at the virtual directory (not a sub-directory).


AdminSite.IsValidName Method

The IsValidName method returns True if the specified Commerce Server site short name is valid. The valid characters and length for a Web site name are determined by the restrictions on the names of Microsoft® SQL Server™ tables. In addition, a short name must not conflict with another short name on the server.

Before actually creating a site, this method is used to make sure the short name of the site is valid. The name must conform to a number of rules for forming valid names in a number of environments. For example, Commerce Server appends a site’s short name to database tables and to generated pages.

Syntax

AdminSite.IsValidName(Name, ServerInstance)

Parameters

Name
The short name being tested.
ServerInstance
The Web site (an instance of the Web server).

Remarks

An object’s IsValidName method can be called without its Initialize or Create methods being called.


AdminSite.ReadDefaultProperties Method

The ReadDefaultProperties method reads the properties from the Site.csc file and returns a site dictionary containing these properties. This method is usually used by the Commerce Host Administration snap-in for the MMC, and by batch files.

The Site.csc file for the Commerce Server site resides in the site\Config directory, and the Site.csc file for the manager site resides in the site\Manager\Config directory.

Syntax

Set Dict = AdminSite.ReadDefaultProperties()

Parameters

None.

Related Topics

  • υThe Site Dictionary


AdminSite.ReadManagerProperties Method

The ReadManagerProperties method reads the properties from the management page’s configuration file (site\Manager\Config\Site.csc) and returns a site dictionary containing these properties.

The manager site dictionary properties include only DefaultConnectionString and ConnectionStringMap. These properties are distinct from the corresponding properties in the main site configuration.

Syntax

Set Dict = AdminSite.ReadManagerProperties()

Parameters

None.

Related Topics

  • υThe Site Dictionary


AdminSite.Reload Method

The Reload method resets all application and session objects for the Commerce Server site. After a reload, the next browser request will load Global.asa.

Parameters

None.

Example

Invoked from ASP as:

call CurrSite.Reload


AdminSite.Status Property

The Status property is a Boolean indicating whether the Commerce Server site is open or closed. In addition, when its value is set, it either opens or closes the Commerce Server site. The function closes the site by writing the value of the Site.CloseRedirectURL property into the HttpRedirect property of the metabase, and opens the site by clearing the HttpRedirect property.

Examples

The following example opens a Commerce Server site:

Set CurSite = Server.CreateObject("Commerce.AdminSite")
Call CurSite.Initialize("1", "Clocktower")
CurSite.Status = True

The following example checks the status of the Commerce Server site and saves the text Open or Closed in a variable called statusMsg. (If the attempt to read the Status Boolean fails, as might happen if permission to a file were denied or a directory did not exist, then statusMsg will contain the text Invalid.)

REM -- check site status
On Error Resume Next
curStatus = CurrSite.status
if Err.Number = 0 then
    if curstatus = TRUE then
        statusMsg = "Open"
    else
        statusMsg = "Closed"
    End If
Else
    statusMsg = "Invalid"
    Err.Clear
End if


AdminSite.Version Property

The Version property returns the version of Commerce Server as an integer (2 for Commerce Server 2.0, and 3 for Commerce Server 3.0).

Syntax

AdminSite.Version

Example

The following example creates and initializes an AdminSite object for the Clocktower site, which is in the default Web site, then tests the version number of the site:

Set AdminSite = Server.CreateObject("Commerce.AdminSite")
Call AdminSite.Initialize("1", "Clocktower")
Call AdminSite.ReadDefaultProperties

If AdminSite.Version = 3 Then
    REM Special processing for Commerce 3.0 site
End If

Parameters

None.


AdminSite.WriteDefaultProperties Method

The WriteDefaultProperties method writes the properties from the specified site dictionary to the Site.csc file. This method is usually used by the Commerce Host Administration snap-in for the Microsoft Management Console (MMC) and by batch files.

Syntax

AdminSite.WriteDefaultProperties(Dictionary)

Parameters

Dictionary
The Dictionary object to be written.

Related Topics

  • υThe Site Dictionary


AdminSite.WriteManagerProperties Method

The WriteManagerProperties method writes the properties from the specified site dictionary to the management page’s configuration file (site\Manager\Config\Site.csc).

The manager site dictionary properties include only DefaultConnectionString and ConnectionStringMap. These properties are distinct from the corresponding properties in the main site configuration so that the password and user name information required to access site management pages can be different from those used in customer pages.

Syntax

AdminSite.WriteManagerProperties(Dictionary)

Parameters

Dictionary
The Dictionary object to be written.

Related Topics

  • υThe Site Dictionary


The AdminWebServer Object

The AdminWebServer object provides access to read-only properties of the site. These methods are used by the Site Foundation Wizard.

The AdminWebServer object supports the following methods.

Method | Description
GetWebSites | Enumerates all Web sites. Returns an array of numbers representing all Web sites (server instances).
GetWebSiteProperties | Given a server instance, returns the properties of the site as name/value pairs in a Dictionary object.
GetCommerceSites | Given a server instance, enumerates all Commerce sites under that Web site.


AdminWebServer Object Overview

The following example enumerates all the Web sites on a server and displays the number of each server instance. Then for each Web site, it obtains the site properties and displays the VrPath property. Finally, for each Web site, it enumerates all the Commerce Server sites within that Web site, and displays the virtual directory for each Commerce Server site:

<%
' Create AdminWebServer object
Set objWebServer = CreateObject("Commerce.AdminWebserver")

' Get Web sites
WebSites = objWebServer.GetWebSites
For WebInstance = LBound(WebSites, 1) To UBound(WebSites, 1)

    ' Print instance number of web site
    Response.Write "<h3>Server Instance " + WebSites(WebInstance) + "</h3>"

    ' Return its properties in a dictionary
    Set objDict = objWebServer.GetWebSiteProperties(WebSites(WebInstance))

    ' Enumerate and display the dictionary
   for each property in objDict
      response.write  property & " = " & objDict.value(property) & "<br>"
    next

   ' For each web site, get all Commerce sites in an array of instances
        CommerceSites = objWebServer.GetCommerceSites(WebSites(WebInstance))

   ' Enumerate all Commerce sites
      For CSite = LBound(CommerceSites, 1) To UBound(CommerceSites, 1)
         Response.Write "<br>" + CommerceSites(CSite)
      Next
 Next

' Destroy objects
Set objDict = Nothing
Set objWebServer = Nothing
%>
Note

Active Server Pages (ASP) scripts that access the Microsoft® Internet Information Server (IIS) metabase require administrator privileges on the computer on which IIS is running. When you execute these scripts from a remote computer, you must connect through a secure connection, such as the Microsoft® Windows NT® Challenge/Response Authentication method. It is suggested that you create a server or directory for your administrative .asp files and set the directory security authentication method to Windows NT Challenge/Response for the server or directory.


AdminWebServer.GetWebSites Method

The GetWebSites method enumerates all Web sites. The method returns an array of numbers representing all server instances.

Syntax

AdminWebServer.GetWebSites()

Parameters

None.

Example

The following example creates an AdminServer object called objWebServer, then calls the GetWebSites method on this object. The method returns an array of Web sites in the array WebSites. The array is then enumerated to display the server instance number for each Web site:

Set objWebServer = CreateObject("Commerce.AdminWebserver")

' Get Web sites
WebSites = objWebServer.GetWebSites
For Index1 = LBound(WebSites) To UBound(WebSites)
    ' Print instance number of web site
    Response.Write "<br>Web Site Instance " + WebSites(Index1)
next


AdminWebServer.GetWebSiteProperties Method

The GetWebSiteProperties method, given a site’s server instance, returns the properties of the site as name/value pairs in a Dictionary object.

Syntax

AdminWebServer.GetWebSiteProperties(ServerInstance)

Parameters

ServerInstance
A numeric value expressed as a string, representing a server instance of a Web site.

Example

The following example creates a Dictionary object containing properties for the default Web site (whose instance is 1), then displays the value of the VrPath property:

Set objDict = objWebServer.GetWebSiteProperties(1)
Response.Write objDict.VrPath


AdminWebServer.GetCommerceSites Method

The GetWebSiteProperties method, given a server instance of a Web site, enumerates all Commerce Server sites under that Web site. The method returns an array of numbers representing all Commerce Server site instances.

Syntax

AdminWebServer.GetCommerceSites(ServerInstance)

Parameters

ServerInstance
A numeric value expressed as a string, representing a site’s server instance.

Remarks

The GetCommerceSites method determines whether a site is a Commerce Server site by examining a reserved key in the metabase.

Example

For a complete example, see AdminWebServer Object Overview.


The ConfigurationCacheHelper Object

Each time a pipeline configuration is loaded, a pipeline configuration file (.pcf) is read from disk. The ConfigurationCacheHelper object enables the pipeline to cache the pipeline configuration file in memory for any subsequent load operation, helping to reduce the performance penalty associated with disk access.

The ConfigurationCacheHelper object supports the following methods.

Property | Description
DeleteCacheEntry | Deletes the configuration specified by the token from cache memory.
LoadFromCache | Retrieves a pipeline configuration previously saved in memory and loads this configuration into the specified pipeline.
SaveToCache | Saves in memory the configuration used by the specified pipeline, and returns a unique token that can be used later to retrieve the cached configuration.

Related Topics

  • υIConfigurationCache Interface


ConfigurationCacheHelper Object Overview

The ConfigurationCacheHelper object enables a pipeline configuration to be cached in memory for any subsequent load operation, helping to reduce the performance penalty associated with accessing a pipeline configuration (.pcf ) on disk.

Note

The actual performance benefits obtained by using the configuration cache helper depend on your specific configuration. To properly assess this benefit, measure the results in your production environment.

A pipeline configuration can be saved in cache from a loaded pipeline by using the SaveToCache method, and later retrieved into a new instance of a pipeline by using the LoadFromCache method.

The following example shows an ASP file creating, loading, and executing a pipeline, using the configuration cache helper. The script attempts to retrieve a cached configuration. If the requested configuration has not yet been cached, the script loads the configuration from the Plan.pcf configuration file, and then saves the configuration in the cache for future use.

REM  Create the pipeline
Set pipeline = Server.CreateObject("Commerce.MtsPipeline")
if VarType(pipeline) <> vbObject then
    Response.Write "Failed to create the pipeline<P>"
end if
REM Response.Write "Created the pipeline<BR>"

set cacheHelper = Server.CreateObject("Commerce.ConfigurationCacheHelper")
if VarType(cacheHelper) <> vbObject then
    Response.Write "Failed to create the ConfigurationCacheHelper<P>"
end if

on error resume next
cacheHelper.LoadFromCache pipeline, Application("PlanCache")
if Err.Number <> 0 then
    REM  likely that cache has not been initialized
    REM  so load the configuration from file
        pipeline.LoadPipe "c:\Inetpub\wwwroot\mysite\config\Plan.pcf"

    REM  Save the pipeline configuration into the cache for next time
    Application("PlanCache") = cacheHelper.SaveToCache(pipeline)
end if

REM  Execute the pipeline
pipeline.Execute 1, orderform, ordercontext, 1
if Err.Number <> 0 then
    errnum = Err.Number
    errdesc = Err.description
    Response.Write "Error " & errnum & " (" & errdesc & ") executing the pipeline<P>"
end if

pipeline = None

Alternatively, the configuration cache could be created in the Global.asa, so that each page could assume that the configuration is already present in the cache and would not need to have any code to load from the .pcf file.

If the configuration cache helper is used, the following script should be added to the site’s Global.asa to delete the configuration cache entry and reclaim the memory when the application ends:

Sub Application_OnEnd
   REM  ... other code
Set pipeline = Server.CreateObject("Commerce.MtsPipeline")
if VarType(pipeline) <> vbObject then
    goto ErrorRet
end if
set cacheHelper = Server.CreateObject("Commerce.ConfigurationCacheHelper")
if VarType(cacheHelper) <> vbObject then
    goto ErrorRet
end if

on error resume next
cacheHelper.DeleteCacheEntry pipeline, Application("PlanCache")

pipeline = None

End Sub


ConfigurationCacheHelper.DeleteCacheEntry Method

The DeleteCacheEntry method deletes the configuration specified by the token from cache memory.

Syntax

ConfigurationCacheHelper.DeleteCacheEntry(Pipeline, CacheToken)

Parameters

Pipeline
A pipeline object created as an instance of MtsPipeline or MtsTxPipeline.
CacheToken
The token generated by a previous call to SaveToCache, used to identify the pipeline configuration to be deleted from the cache.


ConfigurationCacheHelper.LoadFromCache Method

The LoadFromCache method retrieves a pipeline configuration previously saved in memory and loads this configuration into the specified pipeline. Once the configuration has been cached (with SaveToCache), the LoadFromCache method can be used instead of the pipeline’s LoadPipe method.

Syntax

ConfigurationCacheHelper.LoadFromCache(Pipeline, CacheToken)

Parameters

Pipeline
The pipeline object created as an instance of MtsPipeline or MtsTxPipeline, whose configuration is to be loaded.
CacheToken
The token generated by a previous call to SaveToCache, used to identify the desired pipeline configuration cached in memory.

Example

This example assumes that the following actions have occurred.

  • υA ConfigurationCacheHelper object named cacheHelper has been defined.
  • υA pipeline named pipeline has been defined.
  • υAn application variable named PlanCache has been defined. This variable contains the token identifying the pipeline configuration to be loaded into the pipeline.

Given these assumptions, the following script retrieves the pipeline configuration from cache memory and loads it into the pipeline:

cacheHelper.LoadFromCache pipeline, Application("PlanCache")

Related Topics

  • υConfigurationCacheHelper.SaveToCache Method
  • υConfigurationCacheHelper Object Overview


ConfigurationCacheHelper.SaveToCache Method

The SaveToCache method saves in memory the pipeline configuration used by the specified pipeline, and returns a unique token that can be used later by the LoadFromCache method to retrieve the cached configuration.

Syntax

ConfigurationCacheHelper.SaveToCache(Pipeline)

Parameters

Pipeline
An object created as an instance of MtsPipeline or MtsTxPipeline, whose pipeline configuration has already been loaded.

Example

This example assumes that the following actions have occurred.

  • υA ConfigurationCacheHelper object named cacheHelper has been defined.
  • υA pipeline named pipeline has been defined.
  • υThe pipeline’s LoadPipe method has been called to load a pipeline configuration into the pipeline from a .pcf file.

Given these assumptions, the following script saves the pipeline configuration used by the pipeline into cache memory. It also saves a token for later retrieval of the configuration into the application variable PlanCache:

Application("PlanCache") = cacheHelper.SaveToCache(pipeline)

Related Topics

  • υConfigurationCacheHelper.LoadFromCache Method
  • υConfigurationCacheHelper Object Overview


The DataFunctions Object

The DataFunctions object supports a group of methods that perform locale-based data type handling and value range checking on values that you submit to the database or that you pass in an OrderForm object to the order processing pipeline (OPP).

The DataFunctions object supports the following property.

Property | Description
Locale | Number that specifies the default locale value to be used to format date, time, money, and number values.

The DataFunctions object supports the following methods.

Method | Description
CleanString | Processes a string. This processing can include stripping out white spaces, modifying the case of the string, and validating that the length of the string falls within a specified range.
ConvertDateString | Converts a string representation of the date to a Date Variant, based on the specified locale.
ConvertDateTimeString | Converts a string representation of the date and time to a Date Variant, based on the specified locale.
ConvertFloatString | Converts a string representation of a floating-point number to a Double Variant, based on the specified locale.
ConvertMoneyStringToNumber | Converts a string representation of a monetary value to a Long Variant, based on the specified locale.
ConvertNumberString | Converts a string representation of a number to an Integer Variant, based on the specified locale.
ConvertTimeString | Converts a string expression of a time value to a Date Variant, based on the specified locale.
Date | Returns a string representation of the specified Date Variant, based on the specified locale.
DateTime | Returns a string representation of the specified Date Variant, based on the specified locale.
Float | Returns a string representation of a floating-point number, based on the specified locale.
Money | Returns a formatted currency string, based on the specified locale.
Number | Returns a string representation of a number based on the specified locale.
Time | Returns a string representation of the specified Date Variant, based on the specified locale.
ValidateDateTime | Checks whether a string contains a valid date and/or time, and optionally checks against a specified range.
ValidateFloat | Checks whether a string contains a valid floating-point number, and optionally checks the value of the number against a specified range.
ValidateNumber | Checks whether a string contains a valid number, and optionally checks the value of the number against a specified range.

Related Topics

  • υIDataFunctions Interface


DataFunctions Object Overview

The DataFunctions object is usually created in the Global.asa file. Use the Active Server Pages (ASP) Server object’s CreateObject method to create a DataFunctions object, as follows:

Set MSCSDataFunctions = Server.CreateObject("Commerce.DataFunctions")
MSCSDataFunctions.Locale     = &H0409

Also in Global.asa, store the new object in the Application object, as follows:

Set Application("MSCSDataFunctions") = MSCSDataFunctions

Because the Page object’s Request methods rely on the DataFunctions object for its implementation of these methods, you must create the DataFunctions object before you create a Page object.

The DataFunctions object supports methods that make it possible to perform locale-based data type conversions and value range validation on values submitted to your site, or submitted by your site to the OPP or the site’s database.

This object’s methods fall into two categories:

  • υThe conversion methods convert string expressions of date, currency, or number values to Variant expressions of those values, or from Variants to strings. Thus, a string expression of a date value is converted to a Date Variant that contains that value, and this conversion is performed based on the locale that you specify. Conversely, you can use DataFunctions methods to convert a Date value to a string expression of that value.
  • υThe validation methods ensure that the data you submit for storage in the database falls within the validation rules that you have prescribed for given fields. For example, if you create a field in a Microsoft® SQL Server™ database table that is of data type varchar and that can store a maximum of 50 characters, you can use the DataFunctions object’s CleanString method to ensure that the string is sized appropriately for storage in that field.


DataFunctions.CleanString Method

The CleanString method processes a string, based on the specified locale. This string processing can include stripping out leading and trailing white spaces, modifying the case of the string, and validating that the length of the string falls within a given range. If successful, CleanString returns the processed string; otherwise, Null.

Syntax

DataFunctions.CleanString(String, MinLength, MaxLength, StripWhiteSpaces, StripReturn, Case, Locale)

Parameters

String
The text of the string to process.
MinLength
Optional. This parameter indicates the minimum length against which the length of String must be validated. The default value for this parameter is zero (0).
MaxLength
Optional. This parameter indicates the maximum number against which the length of String must be validated. The default value for this parameter is no limit.
StripWhiteSpaces
Optional. This parameter is a Boolean value that indicates whether leading and trailing white spaces should be stripped from String. The default value is True.
StripReturn
Optional. This parameter is a Boolean value that indicates whether the carriage returns contained anywhere in String should be stripped. The default value is True.
Case
Optional. This parameter indicates the case to which the string should be converted. The default value for this parameter is zero (0), which results in no modification to the case of the string. If Case is 1, the string is converted to uppercase. If Case is 2, the string is converted to lowercase.
Locale
Optional. This number specifies the locale to use to process the string. If this parameter is not specified, the value of the DataFunctions object’s Locale property is used.

Example

The following represents a sample call to CleanString:

Set MSCSDataFunctions = Server.CreateObject("Commerce.DataFunctions")
MSCSDataFunctions.Locale = &H0409
Dim Result
Dim strData
strData = " Microsoft Press   "
Result = MSCSDataFunctions.CleanString(strData, 1, 20, True, True, 1)
Response.Write chr(34) & Result & chr(34)

The values passed to CleanString in this example indicate that the value in strData should be range-tested to ensure that it is at least one character and no more than 20 characters, that any leading or trailing white spaces should be removed, that any carriage returns in the string should be removed, and that the string should be converted to uppercase. Because the Locale parameter is not specified in the call to CleanString, the method defaults to the value specified in the DataFunctions object’s Locale property.

The preceding example produces the following text:

"MICROSOFT PRESS"

Related Topics

  • υPage.RequestString Method


DataFunctions.ConvertDateString Method

The ConvertDateString method converts the specified string to a Date Variant, based on the specified locale. If successful, ConvertDateString returns the Date Variant containing the converted value; otherwise, Null.

Syntax

Page.ConvertDateString(String, Locale)

Parameters

String
A string representation of the date to convert.
Locale
Optional. This number specifies the locale to use to process the string. For a list of valid locale IDs, see Hexadecimal Locale Identifiers. If this parameter is not specified, the value of the DataFunctions object’s Locale parameter is used.
Warning

In some cases, the DataFunctions.ConvertDateString method returns NULL when converting a string representation of the Date to the Date VARIANT type for Latvian and Bulgarian locales. To avoid this problem, remove the constant string added at the end of the Date Represantion String according to the Regional Settings.

Related Topics

  • υDataFunctions.ConvertTimeString Method
  • υDataFunctions.ConvertDateTimeString Method
  • υDataFunctions.Date Method
  • υDataFunctions.DateTime Method
  • υPage.RequestDate Method
  • υPage.RequestTime Method


DataFunctions.ConvertDateTimeString Method

The ConvertDateTimeString method converts the specified date/time value to a DateTime Variant, based on the specified locale. If successful, ConvertDateTimeString returns a DateTime Variant; otherwise, Null.

Syntax

DataFunctions.ConvertDateTimeString(DateTime, DateLocale, TimeLocale)

Parameters

DateTime
A string that specifies the date/time value to format.
DateLocale
Optional. This number specifies the locale to use to convert the date. For a list of valid locale values, see Hexadecimal Locale Identifiers. If this value is not specified, the value of the DataFunctions object’s Locale parameter is used.
TimeLocale
Optional. This number specifies the locale to use to convert the time. For a list of valid locale values, see Hexadecimal Locale Identifiers. If this parameter is not specified, the value of the DataFunctions object’s Locale parameter is used.
Warning

In some cases, the DataFunctions.ConvertDateTimeString method returns NULL when converting a string representation of the Date to the Date VARIANT type for Latvian and Bulgarian locales. To avoid this problem, remove the constant string added at the end of the Date Represantion String according to the Regional Settings.

Related Topics

  • υDataFunctions.ConvertDateString Method
  • υDataFunctions.ConvertDateTimeString Method
  • υDataFunctions.Date Method
  • υDataFunctions.DateTime Method
  • υPage.RequestDate Method
  • υPage.RequestTime Method


DataFunctions.ConvertFloatString Method

The ConvertFloatString method converts a string expression of a floating-point number to a Double Variant, based on the specified locale. If successful, ConvertFloatString returns the Double Variant; otherwise, Null.

Syntax

DataFunctions.ConvertFloatString(Float, Locale)

Parameters

Float
A string expression of the number to convert.
Locale
Optional. This number specifies the locale to use to convert the string. For a list of valid locale values, see Hexadecimal Locale Identifiers. If this parameter is not specified, the value of the DataFunctions object’s Locale parameter is used.

Related Topics

  • υDataFunctions.Float Method
  • υDataFunctions.ValidateFloat Method


DataFunctions.ConvertMoneyStringToNumber Method

The ConvertMoneyStringToNumber method converts the specified string as money, based on the specified locale. If successful, ConvertMoneyStringToNumber returns a number that represents the value of the specified string in the base monetary unit of the specified locale; otherwise, Null.

Syntax

DataFunctions.ConvertMoneyStringToNumber(Money, Locale)

Parameters

Money
A string representation of the money to convert.
Locale
Optional. This number specifies the locale to use to convert the string. For a list of valid locale values, see Hexadecimal Locale Identifiers. If this parameter is not specified, the value of the DataFunctions object’s Locale parameter is used.

Remarks

The ConvertMoneyStringToNumber method returns the value in the base monetary unit for a given locale. Thus, given a value in dollars, ConvertMoneyStringToNumber returns the number of cents in the dollar value.

Additionally, ConvertMoneyStringToNumber does not round values. For example, if you pass this method “123.009” the method returns 12300, not 12301.

This method returns a Variant of type Long, not an OLE currency type.

Warning

In some cases, the DataFunctions.ConvertMoneyStringToNumber method returns NULL when converting a string representation of monetary value to the Currency VARIANT type for Swedish and Portuguese Standard locales. To avoid this problem, use the Microsoft® Visual Basic® Scripting Edition (VBScript) function Replace(MoneyString, CurrencyDigitGroupingSymbol,"") to remove the currency digit grouping symbol from the money string prior to call to ConvertMoneyStringToNumber.

Related Topics

  • υDataFunctions.ConvertFloatString Method
  • υDataFunctions.ConvertNumberString Method


DataFunctions.ConvertNumberString Method

The ConvertNumberString method converts a string expression of a number to an Integer Variant, based on the specified locale. If successful, ConvertNumberString returns an Integer Variant containing the converted value; otherwise, Null.

Syntax

DataFunctions.ConvertNumberString(Number, Locale)

Parameters

Number
A string representation of the number to convert.
Locale
Optional. This number specifies the locale to use to convert the string. For a list of valid locale values, see Hexadecimal Locale Identifiers. If this parameter is not specified, the value of the DataFunctions object’s Locale parameter is used.

Remarks

The ConvertNumberString method is designed to accept only integers. Passing a floating-point number as the Number parameter results in an error. To convert floating-point numbers, use ConvertFloatString.

Example

The following example uses ConvertNumberString to convert 123,000 from a string to a number:

StrNum = "123,000"
NNum = DataFunctions.ConvertNumberString(StrNum, &H0409)

In this example, the call to ConvertNumberString returns the following value:

123000

Related Topics

  • υDataFunctions.Number Method
  • υDataFunctions.ValidateNumber Method


DataFunctions.ConvertTimeString Method

The ConvertTimeString method converts a string expression of a time value to a Date Variant, based on the specified locale. If successful, ConvertTimeString returns a Date Variant that contains the time; otherwise, Null. Additionally, if the string expression contains a date, ConvertTimeString returns Null.

Syntax

DataFunctions.ConvertTimeString(Time, Locale)

Parameters

Time
A string that specifies the time to convert.
Locale
Optional. This number specifies the locale to use to convert the string. For a list of valid locale values, see Hexadecimal Locale Identifiers. If this parameter is not specified, the value of the DataFunctions object’s Locale parameter is used.

Example

The following example converts the provided time value, and outputs the value to the page:

<% Time = DataFunctions.ConvertTimeString("3:30PM", &H0409) %>
<% =Hour(Time)%>
<% =Minute(Time)%>
<% =Second(Time)%>

The Time variable that is returned by ConvertTimeString in this example is actually a Date Variant in which the date part has been set to Null. Therefore, you should not use the VBScript Date function to attempt to extract the date from this value.

Related Topics

  • υDataFunctions.Time Method
  • υDataFunctions.ValidateDateTime Method


DataFunctions.Date Method

The Date method converts a Date Variant to a string expression of the specified date, based on the specified locale. If successful, Date returns a string expression of the specified date value; otherwise, Null.

Syntax

DataFunctions.Date(Date, Locale)

Parameters

Date
Date Variant. The date to format.
Locale
Optional. This number specifies the locale to use to convert the date to a string. For a list of valid locale values, see Hexadecimal Locale Identifiers. If this parameter is not specified, the value of the DataFunctions object’s Locale parameter is used.

Related Topics

  • υDataFunctions.ConvertDateString Method


DataFunctions.DateTime Method

The DateTime method converts a Date Variant to a string expression of the Date value, based on the specified locale. If successful, DateTime returns a string expression of the specified date/time value; otherwise, Null.

Syntax

DataFunctions.DateTime(DateTime, Locale)

Parameters

DateTime
Date Variant. The date/time value to convert.
Locale
Optional. This number specifies the locale to use to convert the Date Variant to a string. For a list of valid locale values, see Hexadecimal Locale Identifiers. If this parameter is not specified, the value of the DataFunctions object’s Locale parameter is used.

Related Topics

  • υDataFunctions.Date Method
  • υDataFunctions.Time Method
  • υDataFunctions.ConvertDateTimeString Method


DataFunctions.Float Method

The Float method converts the floating-point number that you specify to a string expression of that number, based on the specified locale. If successful, Float returns a string expression of the specified number; otherwise, Null.

Syntax

DataFunctions.Float(Float, Locale)

Parameters

Float
The floating-point number to convert.
Locale
Optional. This number specifies the locale to use to convert the floating-point number to a string. For a list of valid locale values, see Hexadecimal Locale Identifiers. If this parameter is not specified, the value of the DataFunctions object’s Locale parameter is used.

Related Topics

  • υDataFunctions.ConvertFloatString Method


DataFunctions.Locale Property

The Locale property stores a number value that indicates the default locale to be used by DataFunctions methods to format date, time, money, and number information. Where DataFunctions methods or Page Request methods take a locale value for a parameter, if that value is not supplied, the value to which you initialize this property is used.

For a list of the numbers that you can store in this property, see Hexadecimal Locale Identifiers.

The following initializes the Locale property to the locale identifier for the United States:

DataFunctions.Locale = &H0409


DataFunctions.Money Method

The Money method converts a Currency Variant to a string, based on the specified locale. If successful, Money returns a string expression of the specified monetary value; otherwise, Null.

Syntax

DataFunctions.Money(Money, Locale)

Parameters

Money
The money value to convert to a string, specified in the base monetary unit of the locale used to perform the conversion.(This value is not an OLE currency type.)
Locale
Optional. This number specifies the locale to use to convert the Currency Variant to a string. For a list of valid locale values, see Hexadecimal Locale Identifiers. If this parameter is not specified, the value of the DataFunctions object’s Locale parameter is used.

Related Topics

  • υDataFunctions.ConvertMoneyStringToNumber Method


DataFunctions.Number Method

The Number method converts an Integer Variant to a string, based on the default or specified locale. If successful, Number returns the string expression of the specified number; otherwise, Null.

Syntax

Page.Number(Number, Locale)

Parameters

Number
The number to convert to a string.
Locale
Optional. This number specifies the locale to use to convert the number to a string. For a list of valid locale values, see Hexadecimal Locale Identifiers. If this parameter is not specified, the value of the DataFunctions object’s Locale parameter is used.

Example

Given the number 123, the following call to Number returns a string expression of that number:

strNumber = Page.Number(123)

Related Topics

  • υDataFunctions.ConvertNumberString Method


DataFunctions.Time Method

The Time method converts a Date Variant to a string expression of the time. If successful, Time returns the string expression of the specified time value; otherwise, Null.

Syntax

DataFunctions.Time(Time, Locale)

Parameters

Time
Date Variant. The time value to convert.
Locale
Optional. This number specifies the locale to use to convert the time to a string. For a list of valid locale values, see Hexadecimal Locale Identifiers. If this parameter is not specified, the value of the DataFunctions object’s Locale parameter is used.

Related Topics

  • υDataFunctions.ConvertTimeString Method


DataFunctions.ValidateDateTime Method

The ValidateDateTime method checks whether a string contains a valid date and/or time, and optionally checks against a specified range. If the value is a valid date or time and falls within the given range if specified, ValidateDateTime returns True; otherwise, False.

Syntax

DataFunctions.ValidateDateTime(DateTime, LowDateTime, HighDateTime)

Parameters

DateTime
The value to validate. This value can be a date, a time, or both.
LowDateTime
Optional. This value designates the low end of the range. The default value for this parameter is Null, which means that LowDateTime is ignored in the range validation.
HighDateTime
Optional. This value designates the high end of the range. The default value for this parameter is Null, which means that HighDateTime is ignored in the range validation.


DataFunctions.ValidateFloat Method

The ValidateFloat method checks whether a string contains a valid floating-point number, and optionally checks the value of the number against a specified numerical range. If the value is a valid number and falls within the given range, ValidateFloat returns True; otherwise, False.

Syntax

DataFunctions.ValidateFloat(Value, MinimumValue, MaximumValue)

Parameters

Value
The floating-point number to validate.
MinimumValue
Optional. This value designates the low end of the range. The default value for this parameter is Null, which means that MinimumValue is ignored in the range validation.
MaximumValue
Optional. This value designates the high end of the range. The default value for this parameter is Null, which means that MaximumValue is ignored in the range validation.


DataFunctions.ValidateNumber Method

The ValidateNumber method checks whether a string contains a valid number, and optionally checks the value of the number against a specified numerical range. If the value is a valid number and falls within the given range, ValidateNumber returns True; otherwise, False.

Syntax

DataFunctions.ValidateNumber(Value, MinimumValue, MaximumValue)

Parameters

Value
The number to validate.
MinimumValue
Optional. This value designates the low end of the range. The default value for this parameter is Null, which means that MinimumValue is ignored in the range validation.
MaximumValue
Optional. This value designates the high end of the range. The default value for this parameter is Null, which means that MaximumValue is ignored in the range validation.


The DBStorage Object

The DBStorage object supports mapping Dictionary and SimpleList objects to and from a database, primarily for the storage of receipt and order information.

The DBStorage object supports the following property.

Property | Description
Mapping | Maps a database column to an entry in the OrderForm or Dictionary object that DBStorage uses to insert and retrieve data.

The DBStorage object supports the following methods.

Method | Description
CommitData | Updates a record in the data source to new values.
DeleteData | Deletes specified data from the data source.
DeleteDataKey | Deletes one or more elements based upon the specified key value.
GetData | Returns the data that you specify.
InitStorage | Initializes the DBStorage object.
InsertData | Inserts the data that you specify.
LookupData | Returns a single record based upon keys and values that you specify.
LookupMultipleData | Retrieves multiple results from the database table.

Related Topics

  • υIDBStorage Interface


DBStorage Object Overview

The DBStorage object is created as needed on each page. Use the Active Server Pages (ASP) Server object’s CreateObject method to create a DBStorage object, as follows:

Set mscsOrderFormStorage = Server.CreateObject("Commerce.DBStorage")

This function call returns an uninitialized instance of a DBStorage object. Use the InitStorage method to initialize the returned object instance. Attempting to call any other DBStorage method prior to calling InitStorage results in an error.

The DBStorage object serves as an interface between the site database and Dictionary, SimpleList, and OrderForm objects. A DBStorage object contains methods for transferring data between the database and the data object.

For information about the relationships between the OrderForm object, the DBStorage object, and the site database, see “The Order Form Table and the DBStorage Object” in Architecture of a Business-to-Consumer Site in the Commerce documentation.

When the DBStorage object retrieves data from the database, it creates the appropriate type of data object (an OrderForm or Dictionary), stores the requested data into the object, and returns the data object. When the DBStorage object is used to save data in the database, you pass it the OrderForm or Dictionary object containing the data, and the DBStorage method copies the data from the data object into the database.

The following example is from the Clocktower’s Basket.asp file. This code creates a DBStorage object, assigning it the name mscsOrderFormStorage. It then invokes the object’s InitStorage method to establish a link to the data source and to identify the type of object to be read or written as an OrderForm object. Next, the DBStorage object’s GetData method is called to retrieve OrderForm data corresponding to the current shopper ID. If no such data already exists, the GetData method returns Null; in that case, the application creates and initializes a new OrderForm object. Otherwise, the OrderForm object is used to process and display the items in the customer’s basket:

REM -- Create a storage object for the order forms (shopper's basket)
Set mscsOrderFormStorage = Server.CreateObject("Commerce.DBStorage")
Call mscsOrderFormStorage.InitStorage(MSCSSite.DefaultConnectionString, "Clocktower_basket", "shopper_id", "Commerce.OrderForm", "marshalled_order", "date_changed")

on error resume next
set mscsOrderForm = mscsOrderFormStorage.GetData(null, ShopperID)
on error goto 0
if IsNull(mscsOrderForm) then
    Set mscsOrderForm = Server.CreateObject("Commerce.OrderForm")
    orderFormItems = null
    nOrderFormItems = 0
else
REM ( load and run pipeline)
end if
Note

The DBStorage object’s CommitData method does not support tables containing fields of type TimeStamp. Instead, use the DateChanged argument to the DBStorage.InitStorage method, which provides the same functionality as using TimeStamp fields.


Retrieving Records with DBStorage

DBStorage provides three ways to retrieve data from the database:

  • υSingle row, using key
  • υSingle row, using arbitrary column(s)
  • υMultiple rows

Single Row, Using Key

To retrieve a row based on the value stored in the column that you designated as the table’s key in your initial call to InitStorage, you can use the GetData method to retrieve the column.

For example, assume the following call to InitStorage:

REM -- Create a storage object for the order forms (shopper's basket)
Set  mscsOrderFormStorage = Server.CreateObject("Commerce.DBStorage")
Call mscsOrderFormStorage.InitStorage(MSCSSite.DefaultConnectionString, "Clocktower_basket", "shopper_id", "Commerce.OrderForm", "marshalled_order", "date_changed")

This call to InitStorage specifies the shopper_id column as the key. The following call to GetData returns the row that contains the order form being used by the specified customer:

set mscsOrderForm = mscsOrderFormStorage.GetData(null, ShopperID)

In this example, the GetData method searches the Shopper_id column of the Clocktower_basket table for the specified shopper ID.

Single Row, Using Arbitrary Column(s)

To retrieve a single row of data, where an arbitrary column or group of columns contain a specified set of values, use the LookupData method. To use this method, first initialize two arrays to contain the column names and sought values, respectively.

The following example looks for the record in which the product_color column contains green. Two arrays are created, each containing a single item only, to store column names and values:

Column(0) = "product_color"
Value(0) = "green"

Set Obj = Storage.LookupData(Null, Column, Value)

In the preceding example, the Column parameter designates the table column in which to look for the color green. If the arrays contain more than one element, LookupData searches for a row in which all of the column/value pairs match.

If the LookupData method finds the row containing the column/value pair that you specify, then it returns a Dictionary object initialized with the contents of that row. Otherwise, it returns Null.

Multiple Rows

If LookupData finds more than one row containing the data that you specified, then it still returns Null. Consequently, unless you are searching for a column value that is sure to be unique for the column you are searching, you should use the LookupMultipleData method instead. LookupMultipleData returns a SimpleList object containing a list of Dictionary objects. Each Dictionary object lists the rows in which the specified column contains the specified data.

You would use LookupMultipleData to search for all previous receipts saved for a particular customer, for example.

Related Topics

  • υDBStorage.GetData Method
  • υDBStorage.LookupData Method
  • υDBStorage.LookupMultipleData Method


Modifying and Inserting Records with DBStorage

To modify records using DBStorage, read a record into a Dictionary or OrderForm object (using GetData, LookupData, or LookupMultipleData), modify the contents of the object, and then pass the object to CommitData to update the row.

To insert a new record into the database, initialize the appropriate data object, and then pass the object to InsertData to insert the row.

The following example adds an item to a shopping basket. First, a DBStorage object is created to access the database of active shopping baskets. Next, the GetData method is used to retrieve the basket for the current customer. Assuming the basket already exists, it is returned as an OrderForm object called mscsOrderForm. It the basket does not already exist in the database, then an empty OrderForm object is created.

Next, the item is added to the OrderForm using the OrderForm object’s AddItem method. Finally, the OrderForm is written to storage. If the OrderForm is new, the data is inserted using the InsertData method; if the order form already existed in the basket database, the revised data is committed using the CommitData method:

REM  Create and initialize the OrderForm storage object
set mscsOrderFormStorage = Server.CreateObject("Commerce.DBStorage")
call mscsOrderFormStorage.InitStorage(MSCSSite.DefaultConnectionString, "Clocktower_basket", "shopper_id", "Commerce.OrderForm", "marshalled_order", "date_changed")

REM  Create an OrderForm for the shopper’s basket
created = 0
on error resume next
set mscsOrderForm = mscsOrderFormStorage.GetData(null, mscsShopperID)
on error goto 0
if IsEmpty(mscsOrderForm) then
   set mscsOrderForm = Server.CreateObject("Commerce.OrderForm")
   mscsOrderForm.shopper_id = mscsShopperID
   created = 1
end if

REM  Add the item to the basket
call mscsOrderForm.AddItem(product_sku, product_qty, 0)

REM  Update the database
if created = 0 then
   call mscsOrderFormStorage.CommitData(NULL, mscsOrderForm)
else
   call mscsOrderFormStorage.InsertData(NULL, mscsOrderForm)
end if

Response.Redirect mscsPage.URL("basket.asp")

The CommitData and InsertData methods can store the data from the specified object into the database in two ways.

  • υFirst, if the InitStorage method specifies a MarshallColumn parameter, then CommitData and InsertData serialize all the data in the object into binary form and store it into the database column specified by this parameter. (If this argument is not supplied, then no data is stored in serialized form.)
  • υSecond, if the names of any items in the object exactly match the names of columns in the database, then the data in these items is stored into the corresponding columns. For example, if the order form contains a value called ship_to_name, and if your database table contains a column named ship_to_name, the DBStorage object saves the value in the ship_to_name entry of the order form into that column.

If the MarshallColumn parameter is specified and matching columns exist, then the corresponding data is stored both ways.


Deleting Rows with DBStorage

You delete a row from a DBStorage object’s underlying storage in one of the following ways:

  • υYou can initialize an OrderForm or Dictionary object to describe the data you want to delete, and then pass the initialized object to the DBStorage object’s DeleteData method. In the following example, MSCSOrderFormStorage is a DBStorage object and mscsOrderForm is the customer’s basket. The DeleteData method deletes the contents of the customer’s order form storage by passing in the customer’s basket:
    REM Purchase was successful. Delete the orderform from storage
call MSCSOrderFormStorage.DeleteData(null, mscsOrderForm)
  • υAlternately, to delete an entire row based on the value stored in the column designated as the table’s key, pass the value for that column to DeleteDataKey. In the following example, MSCSShopperStorage is a DBStorage object in which the column shopper_id has been specified as the key. The example deletes the information for a given customer from the table:
    shopper_id = Page.GetShopperID
call MSCSShopperStorage.DeleteDataKey(Null, shopper_id)


DBStorage.CommitData Method

The CommitData method updates one or more records in the database storage.

Syntax

DBStorage.CommitData(Null, Data)

Parameters

Null
This parameter is required for compatibility with Commerce Server 2.0, but is not used.
Data
An object initialized with the updated data. This object can be either an OrderForm or a Dictionary, but must correspond to the object type specified as the programmatic identifier in the initial call to InitStorage.

Example

The following example is used after the contents of the OrderForm have been updated to save the data in the order form table in the application database:

REM -- commit order form back to storage:
call orderFormStorage.CommitData(Null, orderForm)
Note

The CommitData method does not support database tables containing fields of type TimeStamp. Instead, use the DateChanged argument to the DBStorage.InitStorage method, which provides the same functionality as using TimeStamp fields.

Related Topics

  • υDBStorage.InitStorage Method
  • υDBStorage.InsertData Method
  • υModifying and Inserting Records with DBStorage


DBStorage.DeleteData Method

The DeleteData method deletes data from a DBStorage object.

Syntax

DBStorage.DeleteData(Null, Data)

Parameters

Null
This parameter is required for compatibility with Commerce Server 2.0, but is not used.
Data
An object initialized with the data to delete. This object can be either an OrderForm or a Dictionary, but must correspond in type to the object type specified as the program identifier in the initial call to InitStorage.

Example

The following example is from The Clocktower's xt_orderform_purchase.asp file. This example is called after the purchasing pipeline is processed successfully:

REM -- clear out basket:
   call orderFormStorage.DeleteData(null, orderForm)

Related Topics

  • υDBStorage.DeleteDataKey Method
  • υDBStorage.InsertData Method


DBStorage.DeleteDataKey Method

The DeleteDataKey method deletes the data corresponding to the specified key.

Syntax

DBStorage.DeleteDataKey(Null, Value)

Parameters

Null
This parameter is required for compatibility with Commerce Server 2.0, but is not used.
Value
The key value for the row to be deleted.

Remarks

The DeleteDataKey method differs from the DeleteData method in that the former requires only the value stored in the underlying table’s key column. This is the column specified as the key to the underlying table through a previous call to InitStorage.

Thus, if you specify an IDENTITY field in an SQL table as the key into the data source, you can delete all the columns for a specified row by simply providing the appropriate counter value. Alternatively, you can initialize a Dictionary object to the values stored in one or more columns, and pass this initialized object to DeleteData.

Related Topics

  • υDBStorage.DeleteData Method


DBStorage.GetData Method

The GetData method retrieves the specified data from a DBStorage object. If the data is found, this method creates and returns an OrderForm or Dictionary object (depending on the ProgID parameter passed to the InitStorage method) containing the requested data.

The GetData method is preferred over LookupData when the column being searched is the key.

Syntax

DBStorage.GetData(Null, Value)

Parameters

Null
This parameter is required for compatibility with Commerce Server 2.0, but is not used.
Value
The value of the key field for which to get data.

Related Topics

  • υDBStorage.InitStorage Method
  • υDBStorage.LookupData Method
  • υDBStorage.LookupMultipleData Method


DBStorage.InitStorage Method

The InitStorage method initializes a DBStorage object. You must call this method immediately after object creation and before calling any other DBStorage object methods. Attempting to call any other DBStorage method prior to calling InitStorage results in an error.

Syntax

DBStorage.InitStorage(ConnectionString, Table, Key, ProgID, MarshalColumn, DateChanged)

Parameters

ConnectionString
A connection string for the data source, specified as a text string variant.
Note

For compatibility with sites built with Commerce 2.0, the Datasource parameter may also be a Datasource object retrieved through a previous call to the Content object’s AddDatasource method. However, new sites should not rely on this feature, as it will be discontinued in future releases of Commerce Server.

Table
The table within the data source in which to maintain the data.
Key
The column name that the DBStorage object uses as a key into the database table. This column should be marked to contain unique values.
ProgID
The object in which data passed to or retrieved by DBStorage methods will be stored. This parameter can be Commerce.Dictionary for storing Dictionary objects or Commerce.OrderForm for storing OrderForm objects. Methods (such as GetData) that return data from the database create an instance of the specified class with the requested data stored within it.
MarshalColumn
Optional. Text string which, if specified, indicates the name of a column in the database into which the CommitData or InsertData method will store all the data from the specified data object, serialized into an encoded binary format. (Objects in the stored item that have corresponding column names in the database are also stored in those columns in the database.) If this argument is specified, the database must contain a column by that name, or else an error will be produced. If this argument is not specified here, then no data from the object is serialized and saved in the database in binary format, and items in the object that do not have corresponding columns in the database are discarded. When using a Microsoft® SQL Server™ database, the maximum size of the data in this column is the same as the maximum size for the SQL Server text/image datatype (2,147,483,647 bytes).
DateChanged
Optional. The name of a key or attribute in the database into which to write the date when the data is changed. (If you do not specify a column name that exists in the database, the change date will be included in the marshalled data.)

Example

The following sample, from the Clocktower’s Basket.asp file, initializes the DBStorage object called mscsOrderFormStorage as an OrderForm storage object:

Call mscsOrderFormStorage.InitStorage(MSCSSite.DefaultConnectionString, "Clocktower_basket", "shopper_id", "Commerce.OrderForm", "marshalled_order", "date_changed")

In this example:

  • υMSCSSite.DefaultConnectionString returns a connection string representing the data source.
  • υ"Clocktower_basket" is the name of the table in the referenced data source.
  • υ"shopper_id" identifies the primary key into that table. This is the column name that the DBStorage object will use to key into the table to perform routine tasks such as data insertion and retrieval.
  • υ"Commerce.OrderForm" is the programmatic identifier of the object that you will use to pass data to and retrieve data from DBStorage methods, in this case an OrderForm object.
  • υ"marshalled_order" is the name of a column for this DBStorage object instance to use for marshaling data.
  • υ"date_changed" is the name of the column in the database that will contain the date of the most recent change.

Related Topics

  • υIDBStorage:InitStorage


DBStorage.InsertData Method

The InsertData method inserts data into the database storage.

Syntax

DBStorage.InsertData(Null, Data)

Parameters

Null
This parameter is required for compatibility with Commerce Server 2.0, but is not used.
Data
An object that contains the data to insert. The type of this object corresponds to the object type specified as the programmatic identifier in the initial call to InitStorage.

Example

The following example creates and initializes a Dictionary object to a set of values, and then inserts the object’s data into a database table:

<% Set Dictionary = Server.CreateObject("Commerce.Dictionary")
Dictionary.order_id = orderID
Dictionary.shopper_id = shopperID
Dictionary.status = 5
call MSCSReceiptStorage.InsertData(Null, Dictionary)
%>

Related Topics

  • υDBStorage.InitStorage Method
  • υDBStorage.CommitData Method
  • υModifying and Inserting Records with DBStorage


DBStorage.LookupData Method

The LookupData method retrieves a single row from the data source based upon column names and values that you specify. If the data is found, this method creates and returns an OrderForm or Dictionary object (depending on the ProgID parameter passed to the InitStorage method) containing the requested data.

Syntax

DBStorage.LookupData(Null, Column, Value)

Parameters

Null
This parameter is required for compatibility with Commerce Server 2.0, but is not used.
Column
An array containing the column names that you want to query.
Value
An array containing the values that you want to query.

Remarks

The Column and Value arrays that you pass to LookupData share an index-to-index relationship. This means that they must contain an identical number of members and that the value stored in Value(N) will be searched for in the column specified by Column(N).

If the arrays contain more than one element, LookupData searches for a row in which all of the column/value pairs match.

Because the LookupData method returns only a single row of data, specifying column and value information that would result in the retrieval of more than one row results in an error.

Example

In the following sample, LookupData searches for a row in which both the shopper_id column contains the value returned by the shopper_id variable and the shopper_name column contains the customer name returned by the Page.Request method:

REM Attempt to determine if this shopper is already registered.
shopper_id = Page.GetShopperID

On Error Resume Next
Dim keys(1)
Dim values(1)
keys(0) = "shopper_id"
keys(1) = "shopper_name"
values(0) = shopper_id
values(1) = Page.Request("shopper_name", Null, 1, 60)

exists=NULL
set exists = MSCSStorage.LookupData(Null, keys, values)
If IsNull(exists) Then
REM This shopper id and name does not exist in the specified columns

Related Topics

  • υDBStorage.GetData Method
  • υDBStorage.LookupMultipleData Method
  • υRetrieving Records with DBStorage


DBStorage.LookupMultipleData Method

The LookupMultipleData method retrieves multiple results from the database table. If the data is found, this method creates a SimpleList object that contains OrderForm or Dictionary objects, depending on the ProgID parameter passed to the InitStorage method.

Syntax

DBStorage.LookupMultipleData(Null, Column, Value)

Parameters

Null
This parameter is required for compatibility with Commerce Server 2.0, but is not used.
Column
An array containing the columns to query for the specified values.
Value
An array containing the values that correspond to the column names to use as the basis for the lookup.

Remarks

The Column and Value arrays that you pass to LookupMultipleData share an index-to-index relationship. This means that they must contain an identical number of members, and that the value stored in Value(N) will be searched for in the column specified by Column(N). If the number of elements in Column does not equal the number of values in Value, LookupMultipleData returns Null.

Related Topics

  • υDBStorage.GetData Method
  • υDBStorage.LookupData Method
  • υRetrieving Records with DBStorage


DBStorage.Mapping Property

The DBStorage.Mapping property maps a database column to an entry in the OrderForm or Dictionary object that DBStorage uses to insert and retrieve data.

Syntax

receiptStorage.Mapping.Value(DataObjectProperty) = "DatabaseTableColumn"

Example

The following example, from Volcano Coffee’s Include\Util.asp file, creates a storage object for receipts. The property of the order form called _total_total is mapped to a database column called total.

Set receiptStorage = Server.CreateObject("Commerce.DBStorage")
Call receiptStorage.InitStorage(MSCSSite.DefaultConnectionString, "vc30_receipt", "order_id", "Commerce.OrderForm" , "marshalled_receipt", "date_entered")
receiptStorage.Mapping.Value("_total_total") = "total"


The Dictionary Object

A Commerce Server Dictionary object is a collection object that supports the creation, storage, and retrieval of name/value pairs in memory. Every element in a Dictionary object is a Variant, which means you can create a Dictionary object that consists of almost any kind of values (including other Dictionary objects), and that you can store any combination of Variant types in the same Dictionary object.

The Commerce Server architecture uses the Dictionary object for a number of specialized purposes, including the Site and PipeContext objects. However, because a Dictionary object is designed to be a general purpose collection, you can use it for almost anything that its internal structure supports.

When you need to create a Dictionary object explicitly (that is, when the object is not created for you by some other Commerce Server object), use the Active Server Pages (ASP) Server object’s CreateObject method, as follows:

set my_dictionary = Server.CreateObject("Commerce.Dictionary")

After creating the object, you can add elements to it, as follows:

my_dictionary.first_name = "Steve"
my_dictionary.last_name = "DeBroux"

In this example, first_name and last_name are Dictionary keys, and "Steve" and "DeBroux" become the assigned values of these keys. Each statement actually accomplishes three functions: declaring the Dictionary key, adding that key to the Dictionary object, and setting the key to a value.

You can extract values from a Dictionary object in several ways. You can simply place the object.key identifier on the right side of the assignment statement. Such an assignment returns the referenced key’s value:

my_first_name = my_dictionary.first_name

Or you can use the Value method to get the value of a given key:

my_last_name = my_dictionary.value("last_name")

You can also use the Microsoft® Visual Basic® Scripting Edition (VBScript) For Each statement to enumerate through either the keys or the values of a Dictionary object as follows (this example assumes that every value in the dictionary contains text):

REM   Get the key names
for each element in my_dictionary
   response.write element
next

REM Get the values
for each element in my_dictionary
   response.write my_dictionary.Value(element)
next

The data in a Dictionary object can be saved in a database table by using the DBStorage object, or it can be saved in a structured storage file by using the FileDocument object.

Commerce Server sites use implementations of the Dictionary object to store sets of data that are required by various other objects and pipeline components.

For information about the implementations of the Dictionary object, see Dictionary Implementations.

The Dictionary object supports the following properties.

Property | Description
Count | Read-only number that identifies the number of elements in the Dictionary object.
Prefix | String used as a filter when the contents of the Dictionary object are saved.

The Dictionary object supports the following method.

Property | Description
Value | Returns the value associated with a given Dictionary key.

Related Topics

  • υIDictionary Interface


Dictionary.Count Property

The Count property returns the number of elements in the Dictionary object. (Read-only)

Example

The following example displays the number of items in the my_dictionary object:

Response.Write my_dictionary.Count


Dictionary.Prefix Property

The Prefix property contains a string that acts as a filter when the contents of the Dictionary object are saved (usually to a database). When the name of a name/value pair begins with the specified prefix, that name/value pair is not saved. By default, the prefix is "_", so that any keywords beginning with an underscore character are excluded.

The pipeline component that saves receipts usually sets the prefix to "_cc_", so that all credit-card information is not saved in the database. (The actual string used by the pipeline component is configurable.)

Related Topics

  • υThe Dictionary Object


Dictionary.Value Method

The Value method returns the value of a given Dictionary key.

Syntax

Dictionary.Value(Key)

Parameters

Key
The name of the key.

Example

The following example returns the value associated with the key “last_name” in the my_dictionary Dictionary object, and assigns the value to the variable result:

result = my_dictionary.value("last_name")


The FileDocument Object

The FileDocument object provides methods that support saving and restoring information contained in any persistable object to and from disk.

A persistable object is an object that supports structured storage, a technique used by Component Object Model (COM) objects to save information on disk for later retrieval. A structured storage file contains collections of data that are organized hierarchically into streams and storages. Streams are analogous to conventional files in that they can contain arbitrary data, but many streams can be contained within one structured storage file. (Storages are analogous to directories in a file system, and may contain streams or other storages. The FileDocument object does not make use of storages other than the root storage, which is analogous to the root directory in a file system.)

When you read from or write to structured storage using the FileDocument object, you specify both the name of the structured storage file and the name of the stream. The FileDocument object assumes that the stream is in the root storage of the structured storage file.

For example code, see ReadDictionaryFromFile Method.

The FileDocument object supports the following methods.

Method | Description
ReadDictionaryFromFile | Retrieves data that has been saved in a structured storage file into a specified instance of the Dictionary object.
ReadFromFile | Retrieves data that has been saved in a structured storage file and returns a new data object.
WriteToFile | Writes data from a data object (such as a Dictionary object) to a specified stream in a structured storage data file.


FileDocument Object Overview

Use the Active Server Pages (ASP) Server object’s CreateObject method to create a FileDocument object, as follows:

Set FD = Server.CreateObject("Commerce.FileDocument")

A persistable object is an object that supports structured storage, a technique used by COM objects to save information on disk for later retrieval. A structured storage file contains collections of data that are organized hierarchically into streams and storages. Streams are analogous to conventional files in that they can contain arbitrary data, but many streams can be contained within one structured storage file. (Storages are analogous to directories in a file system, and may contain streams or other storages. The FileDocument object does not make use of storages other than the root storage, which is analogous to the root directory in a file system.)

When you read from or write to structured storage using the FileDocument object, you specify both the name of the structured storage file and the name of the stream. The FileDocument object assumes that the stream is in the root storage of the structured storage file.


FileDocument.ReadDictionaryFromFile Method

The ReadDictionaryFromFile method retrieves data that has been saved in a structured storage file into a specified instance of the Dictionary object.

Syntax

FileDocument.ReadDictionaryFromFile(FileName, Stream, Dictionary)

Parameters

FileName
A string containing the name of the structured storage file to read.
Stream
A string containing the name of the stream to read within the file. Thirty-one characters maximum.
Dictionary
A pointer to a Dictionary object into which to copy the stream data.

Remarks

The ReadDictionaryFromFile method requires that the destination Dictionary object already be created. Using ReadDictionaryFromFile in this way enables you to save the site dictionary in the Application object.

The ReadDictionaryFromFile method adds values from the file to the Dictionary object; it does not clear the object first.

The specified stream must be in the root storage of the structured storage file.

Example

The following sample is from the Clocktower’s Global.asa file, which initializes the Commerce Server site application:

REM -- Create Store Dictionary
   Set MSCSSite = Server.CreateObject("Commerce.Dictionary")

   REM -- Read Store Dictionary
   Set FD = Server.CreateObject("Commerce.FileDocument")
   Call FD.ReadDictionaryFromFile( Request(“APPL_PHYSICAL_PATH”) + "/config/site.csc",
       "IISProperties", MSCSSite)

To retrieve the Commerce Server site information, the sample first creates a FileDocument object ("FD") to enable use of the ReadDictionaryFromFile method. The call to ReadDictionaryFromFile takes three arguments:

  • υThe file path and name, which is produced by concatenating the path and the file name.
  • υThe name of the stream that saves the site information within the Site.csc file.
  • υThe Dictionary object just created, into which the site information is to be copied.

Related Topics

  • υThe Site Dictionary
  • υFileDocument.ReadFromFile Method
  • υFileDocument.WriteToFile Method


FileDocument.ReadFromFile Method

The ReadFromFile method retrieves data that has been saved in a structured storage file, creates an appropriate data object, and returns the new object containing the saved data.

Syntax

FileDocument.ReadFromFile(FileName, Stream)

Parameters

FileName
A string containing the name of the structured storage file to read.
Stream
A string containing the name of the stream to read within the file. Thirty-one characters maximum.

Example

The following sample creates a Dictionary object named myDict, reads the values from the stream named IISProperties in the structured storage file named Site.csc, then copies these values to the Dictionary object, and returns the object:

Set myDict = FD.ReadFromFile(“Site.csc”, “IISProperties”)

Remarks

The object must support the IPersistStream interface.

The ReadFromFile method, unlike ReadDictionaryFromFile, creates the object into which the stream data is copied, then returns this object to the calling statement. An object created in this way cannot be saved in the Application object. To create a site dictionary that can be saved in the Application object, create the Dictionary object with Application scope, and then use ReadDictionaryFromFile.

The specified stream must be in the root storage of the structured storage file.

Related Topics

  • υThe Site Dictionary
  • υFileDocument.ReadDictionaryFromFile Method
  • υFileDocument.WriteToFile Method


FileDocument.WriteToFile Method

The WriteToFile method writes data from a data object (such as a Dictionary object) into a specified stream in a structured storage file.

Syntax

FileDocument.WriteToFile(FileName, Stream, Object)

Parameters

FileName
A string variant containing the name of the structured storage file to write.
Stream
A string variant containing the name of the stream to write within the file. Thirty-one characters maximum.
Object
A variant specifying the data object containing the information to be saved in the file.

Remarks

The object must support the IPersistStream interface.

The specified stream must be in the root storage of the structured storage file.

Example

The following Microsoft® Visual Basic® Scripting Edition (VBScript) example saves the contents of the Dictionary object called Dict to the stream called myStream of the specified file:

Set Dict = Server.CreateObject(“Commerce.Dictionary”)
Set FileDoc = Server.CreateObject(“Commerce.FileDocument”)
Dict(“MyOrder”) = “My Data”
Call fileDocument.WriteToFile(“C:\temp\test.txt”, "myStream", Dict)

Related Topics

  • υThe Site Dictionary
  • υFileDocument.ReadDictionaryFromFile Method
  • υFileDocument.ReadFromFile Method


The MessageManager Object

The MessageManager object stores error messages in multiple languages that the order processing pipeline (OPP) components use to describe error conditions generated during OrderForm processing.

The MessageManager object supports the following property.

Property | Description
DefaultLanguage | Specifies the default message set for the MessageManager.

The MessageManager object supports the following methods.

Method | Description
AddLanguage | Adds a new message set to the MessageManager object.
AddMessage | Adds a new message to the Message Manager object.
GetLocale | Returns the locale for the specified message set.
GetMessage | Returns the message associated with the specified message name constant.

Related Topics

  • υIMSCSMessageManager_3_0 Interface


MessageManager Object Overview

The MessageManager object is usually created in the Global.asa file. Use the Active Server Pages (ASP) Server object’s CreateObject method to create a MessageManager object, as follows:

Set MSCSMessageManager = Server.CreateObject("Commerce.MessageManager")

Also in Global.asa, store the new object in the Application object, as follows:

Set Application("MSCSMessageManager") = MSCSMessageManager

The MessageManager object is used to associate sets of error messages with user languages or dialects. The MessageManager separates the text of these messages from the components that detect the errors, making it easy to support many languages while using the same code, site configuration, pipeline components and pipeline configuration.

For information about how the MessageManager is used in an application, see “Managing Languages and Error Messages” in Architecture of a Business-to-Consumer Site in the Commerce documentation.

The following example, from the Global.asa file for the Microsoft Press® sample site, illustrates the creation and initialization of a MessageManager object:

REM -- Create a message manager for use by the pipeline stages
Dim MSCSMessageManager
Set  MSCSMessageManager = Server.CreateObject("Commerce.MessageManager")
Call MSCSMessageManager.AddLanguage("usa", &H0409)
Call MSCSMessageManager.AddLanguage("FRA", &H040c)
Call MSCSMessageManager.AddLanguage("ENC", &H1009)
MSCSMessageManager.defaultLanguage = "usa"
Call MSCSMessageManager.AddMessage("pur_out_of_stock", "At least one item is out of stock.")
Call MSCSMessageManager.AddMessage("pur_badsku", "Products in your basket were deleted because they don't exist in this store.")
Call MSCSMessageManager.AddMessage("pur_badplacedprice", "Prices of products in your basket have been updated.")
Call MSCSMessageManager.AddMessage("pur_noitems", "An order must have at least one item.")
Call MSCSMessageManager.AddMessage("pur_badshipping", "Unable to complete order. Cannot compute shipping cost.")
Call MSCSMessageManager.AddMessage("pur_badtax", "Unable to complete order. Cannot compute tax.")
Call MSCSMessageManager.AddMessage("pur_badhandling", "Unable to complete order. Cannot compute handling cost.")
Call MSCSMessageManager.AddMessage("pur_badverify", "Changes to the data require your review. Please review and resubmit.")
Call MSCSMessageManager.AddMessage("pur_badpayment", "There was a problem authorizing your credit.  Please verify your payment information or use a different card.")
Call MSCSMessageManager.AddMessage("pur_badcc", "Bad Credit Card Number.")

In the preceding example, the MessageManager’s DefaultLanguage property is initialized to reference the message set called "usa", which has been added to the MessageManager through the call to AddLanguage. Because subsequent calls to AddMessage do not specify the message set with which each message is associated, the added messages are automatically associated with the default message set.


MessageManager Messages

The following table lists the messages that are used by the default implementation of the OPP, showing the message name constant expected by the OPP components that use these messages.

Message name constant | Used by OPP component | Added to this collection under this condition
pur_badplacedprice | RequiredItemAdjustPrice | _Basket_Errors when the price of an item does not correspond to the price contained in the OrderForm.
pur_badhandling | RequiredHandling | _Purchase_Errors when the handling cost for an order cannot be computed.
pur_badpayment | RequiredPayment | _Purchase_Errors when authentication code (_payment_auth_code) is not set.
pur_badshipping | RequiredShipping | _Purchase_Errors when the shipping for an order cannot be computed.
pur_badsku | RequiredProdInfo | _Basket_Errors when a SKU in the OrderForm references an item that is not contained in the site’s inventory.
pur_badtax | RequiredTax | _Purchase_Errors when the tax on a purchase cannot be computed.
pur_badverify | RequiredTotal | _Purchase_Errors when the data stored by the ProcessVerifyWith method does not match the original data in the order form.
pur_noitems | RequiredOrderCheck | _Purchase_Errors when there are no items in the OrderForm.
pur_out_of_stock | FlagInventory, LocalInventory | _Purchase_Errors when an item referenced in the OrderForm is out of stock.


MessageManager.AddLanguage Method

The AddLanguage method adds a new message set to the MessageManager.

Syntax

MessageManager.AddLanguage(MessageSet, LocaleID)

Parameters

MessageSet
A string supplied as the name for the message set to add to the MessageManager.
LocaleID
A number that uniquely identifies the locale to associate with the added message set. For a list of possible values for this parameter, see Hexadecimal Locale Identifiers.

Remarks

The AddLanguage method adds a message set to the MessageManager, and associates that message set with a locale. In subsequent calls to MessageManager object methods, the caller needs to identify the message set name, not the locale.

Any number of message sets can be associated with a single locale.

Example

The following example adds a message set called "usa" to the MessageManager, and uses the MessageManager’s DefaultLanguage property to make the added message set the default message set for the site:

Call MSCSMessageManager.AddLanguage("usa", &H0409)
MessageManager.defaultLanguage = "usa"

Related Topics

  • υMessageManager.AddMessage Method
  • υMessageManager.DefaultLanguage Property
  • υMessageManager.GetMessage Method


MessageManager.AddMessage Method

The AddMessage method adds a message to the MessageManager object.

Syntax

MessageManager.AddMessage(MessageConstant, Text, MessageSet)

Parameters

MessageConstant
The message name constant, which is a string that identifies the message to add. This name must be a name that is known to the OPP component that will use the message to identify an error condition. For a list of messages and their constant names, see MessageManager Messages.
Text
The text of the message to add.
MessageSet
Optional. Designates the language name with which to associate the message. This value, if specified, must be a language name added through a previous call to AddLanguage. If this parameter is not supplied, the language specified in the MessageManager object’s DefaultLanguage property is used.

Example

The following example adds the pur_badpayment message to the MessageManager. The message associated with pur_badpayment is inserted into the _Purchase_Errors_ collection in the OrderForm if a customer has provided invalid credit card information:

Call MSCSMessageManager.AddMessage("pur_badpayment", "There was a
problem authorizing your credit.  Please verify your payment information
or use a different card.", "usa")

Related Topics

  • υMessageManager.GetMessage Method


MessageManager.DefaultLanguage Property

Use the DefaultLanguage property to specify the default message set for the MessageManager. When you use AddMessage to add messages to the MessageManager, and do not specify a message set for those messages, they are associated with the message set specified in this property.

The DefaultLanguage property is initialized in the Global.asa file as follows, where "usa" references a message set that has been added to the MessageManager using the AddLanguage method:

MessageManager.DefaultLanguage = "usa"

Remarks

Do not use this property to switch to different message sets inside an application. Instead, specify the MessageSet parameter for each desired call.


MessageManager.GetLocale Method

The GetLocale method returns a number that identifies the locale for the specified message set.

Syntax

MessageManager.GetLocale(MessageSet)

Parameters

MessageSet
Optional. The name of the message set for which you want to retrieve the locale. This message set must have been added to the MessageManager through a previous call to AddLanguage.

If this parameter is not specified, GetLocale returns the locale for the message set to which you have initialized the MessageManager’s DefaultLanguage property.

Remarks

Like GetMessage, GetLocale is usually not called from within a site. Instead, it is used by the OPP to retrieve the locale for a message that describes an error that the OPP has encountered during a purchase.

Related Topics

  • υMessageManager.AddLanguage Method
  • υMessageManager.DefaultLanguage Property
  • υMessageManager.GetMessage Method


MessageManager.GetMessage Method

The GetMessage method returns the text of the specified error message.

Syntax

MessageManager.GetMessage(MessageConstant, MessageSet)

Parameters

MessageConstant
The message constant name of the message to return. This is the name associated with this message when it was added to the MessageManager through a call to AddMessage.
MessageSet
Optional. The name of the message set to which the desired message text belongs. This string specifies a message set that was added to the MessageManager through a previous call to AddLanguage. If this parameter is not specified, the message is returned for the message set identified by the MessageManager’s DefaultLanguage property.

Remarks

The GetMessage method is seldom called from within a site. Instead, it is used by order OPP components to retrieve the messages that describe errors occurring in the purchase process.

Related Topics

  • υMessageManager.GetLocale Method


The MicroPipe Object

The MicroPipe object enables embedding and running a single pipeline component on an Active Server Pages (ASP) page without requiring a pipeline and a .pcf file.

The MicroPipe object supports the following methods:

Method | Description
SetComponent | Specifies the pipeline component to load and execute in the micropipe.
Execute | Executes the component.
SetLogFile | Identifies the file to which pipeline events are logged.

Related Topics

  • υMtsTxPipeline and MtsPipeline Overview


MicroPipe Object Overview

MicroPipe implements the Component Object Model (COM) interface IMicroPipeline, which is derived from IDispatch, as the default interface. The MicroPipe also implements the COM interface ISupportErrorInfo.

The MicroPipe object does not explicitly use the Microsoft® Transaction Server (MTS). SetComplete/SetAbort is not explicitly used. If transaction semantics are desired, the page can be marked as transacted or the standard MtsTxPipeline can be used. Distributed transactions have no meaning in the scope of the MicroPipe because it contains only one component.

The way in which you call the MicroPipe object from a page depends on the pipeline component. Each pipeline component has a private way to set its component configuration from the component’s administrative property pages. Two common ways are:

  • υTo create a dictionary and pass that dictionary to the component.
  • υTo set individual or multiple properties directly.

Other pipeline components may have different methods for providing input to the component. The MicroPipe supports all methods of setting the configuration of a pipeline component.

Components Configured with a Dictionary

The following example demonstrates how to use the MicroPipe with an order processing pipeline (OPP) component that is configured with a dictionary. This example is written in Microsoft® Visual Basic® Scripting Edition (VBScript). This example executes the component MyPipelineComponent from the page:

REM  Create orderform and pipecontext objects
set orderForm = Server.CreateObject("Commerce.OrderForm")

Set pipeContext = Server.CreateObject("Commerce.Dictionary")
Set pipeContext("MessageManager")      = MSCSMessageManager
Set pipeContext("DataFunctions")       = MSCSDataFunctions
Set pipeContext("QueryMap")            = MSCSQueryMap

REM  Create a dictionary for input values
config_dictionary = Server.CreateObject(Commerce.Dictionary)
config_dictionary.componentsize = 17
config_dictionary.componentcolor = blue
config_dictionary.componentpattern = striped

REM  Create the object to be executed
component = Server.CreateObject(MyPipelineComponent)

REM  Set its values using the dictionary
Call component.SetConfig(config_dictionary)

REM  Create the Micropipe and specify the component to execute
MicroPipe = Server.CreateObject("Commerce.MicroPipe")
Call MicroPipe.SetComponent(component)

REM  Run the component
ErrorLevel = MicroPipe.Execute(orderForm, pipeContext, 0)

REM  Clean up objects
set MicroPipe = nothing
set component = nothing
set config_dictionary = nothing
set pipeContext = nothing

Components Configured by Setting Properties

The following example demonstrates how to use the MicroPipe from an ASP page with a pipeline component that is configured by setting properties. This example is written in Visual Basic Scripting Edition:

REM  Create the object to be executed
component = Server.CreateObject( MyPipelineComponent )

REM  Configure its values
component.componentsize = 17
component.componentcolor = blue
component.componentpattern = striped

REM  Create the Micropipe and specify the component to execute
MicroPipe = Server.CreateObject("Commerce.MicroPipe")
Call MicroPipe.SetComponent(component)

REM  Run the component
ErrorLevel = MicroPipe.Execute(orderForm, pipeContext, 0)

REM  Clean up objects
set MicroPipe = nothing
set component = nothing


MicroPipe.SetComponent Method

The SetComponent method specifies the pipeline component to load and execute in the micropipe.

Syntax

MicroPipe.SetComponent(Component)

Parameters

Component
The pipeline component to execute.

Remarks

A single MicroPipe object can be used to execute multiple components. Calling the SetComponent method on the MicroPipe object after setting and executing a different component earlier is permitted. In this case, the MicroPipe object releases the earlier component, and sets up the new component in its place.

After executing the component, the calling script must release the pipeline component, using script such as the following:

set component = nothing


MicroPipe.Execute Method

The Execute method runs the pipeline component specified by the SetComponent method, applying its actions to the specified object.

Execute returns a Long result containing one of the following values:

  • υA result of 1 indicates the pipeline executed successfully.
  • υA result of 2 indicates errors raised by pipeline components in the basket or purchase error collections. These are typically customer errors, such as a mis-typed credit-card number. An error message is displayed to the customers so that they can submit the information again.
  • υA result of 3 indicates failure of the pipeline, such as the inability to access the database. This type of error cannot be corrected by the customer.

Syntax

MicroPipe.Execute(Object, PipeContext, Reserved)

Parameters

Object
The data object to be processed by the components in the pipeline. For an OPP, Object is usually an initialized OrderForm. For a Commerce Interchange Pipeline (CIP), Object is a transport dictionary used to store various properties during the execution of the pipeline.
PipeContext
The PipeContext object is a Dictionary object that references a group of initialized objects containing information needed by the pipeline.
Reserved
This value is not used and must be set to zero (0).

Remarks

The way in which you call the MicroPipe object from a page depends on the pipeline component. Each pipeline component has a private way to set its component configuration from the component’s administrative property pages. The two most common ways are:

  • υTo create a dictionary and pass that dictionary to the component.
  • υTo set individual or multiple properties directly.

Other pipeline components may have different methods for providing input to the component. The MicroPipe supports all methods of setting the configuration of a pipeline component.

After the script has used the MicroPipe object, it must release the object, using the following script:

set MicroPipe = nothing


MicroPipe.SetLogFile Method

The MicroPipe object returns component error messages in the same manner as standard pipelines by writing the error message to the standard pipeline log file if any and returning them through ISupportErrorInfo as appropriate. The MicroPipe object also reports component errors to the event log, exactly like standard pipelines. Unlike standard pipelines, the MicroPipe does not persist any data.

The SetLogFile method identifies the file to which the pipeline logs operations that occur when the pipeline is run.

This method is intended for use by developers who want to analyze the operations of a pipeline configuration. With this feature, the pipeline logs all Dictionary and SimpleList object read/write operations.

Syntax

MicroPipe.SetLogFile(Filename)

Parameters

Filename
The name of the file to which pipeline events are logged. When set to an empty string (""), logging is disabled.


The MtsPipeline Object

The MtsPipeline object creates and executes a pipeline configuration. This pipeline may be used as an order processing pipeline (OPP) or as a Commerce Interchange Pipeline (CIP).

The MtsPipeline object is registered under Microsoft® Transaction Server (MTS) as transactions not supported. Commerce Server 3.0 stores should use this pipeline in situations in which transactions are not desired.

Commerce Server 3.0 provides three similar objects that execute pipeline configurations. These objects differ in the way in which they are registered with MTS (see MtsTxPipeline and MtsPipeline Overview).

The MtsPipeline object supports the following methods:

Method | Description
LoadPipe | Loads a pipeline configuration (.pcf) file to the pipeline.
Execute | Runs the components in the pipeline.
SetLogFile | Identifies the file to which pipeline events are logged.

Related Topics

  • υIPipeline Interface


MtsTxPipeline and MtsPipeline Overview

Commerce Server 3.0 provides three similar objects that execute pipeline configurations. These objects differ in the way in which they are registered with MTS.

Object | Description
MtsTxPipeline | Pipeline registered under MTS as transactions required. Holds a transaction across all components in the pipeline configuration.
MtsPipeline | Pipeline with the same methods as the MtsPipeline object, but registered under MTS as transactions not supported. Commerce Server 3.0 sites should use this pipeline in situations where transactions are not desired.
OrderPipeline | Pipeline not registered under MTS. It is included for backward compatibility with sites created in Commerce Server 2.0.

The pipeline is a container for the pipeline components. The pipeline components are specified by a pipeline configuration, which is stored in the pipeline configuration (.pcf) file and configured using the Pipeline Editor.

A pipeline configuration can be designated to require that the configuration is run within a specific type of pipeline. The configuration may be designated for transaction compatibility in one of these ways:

  • υAny pipeline. May be loaded into any pipeline.
  • υRequires transacted pipeline. Must be loaded into an MtsTxPipeline pipeline.
  • υRequires non-transacted pipeline. Must be loaded into an MtsPipeline pipeline.

This designation in the .pcf file ensures that the configuration is run in the correct type of pipeline. This is particularly important when the components are marked as requires a transaction. If such components were to be loaded in a non-transacted pipeline, each component would run under its own independent transaction, so that a failure in one component would not roll back the actions of the other components. By using the Pipeline Editor to designate the configuration file as requiring a transacted pipeline, any attempt to execute this configuration file in a non-transacted pipeline is trapped as an error as soon as the configuration is loaded into a pipeline. (The LoadPipe method checks that the designation required by the configuration matches the pipeline. If the configuration does not match, the load fails.)

To create a pipeline object, use the Server.CreateObject method, specifying Commerce.MtsPipeline¸ Commerce.MtsTxPipeline, or Commerce.OrderPipeline as the object’s programmatic identifier.

The following example (from Clocktower’s Basket.asp file) creates an MtsPipeline object ("mscsMtsPipeline"), loads a pipeline configuration file (Plan.pcf), and executes the pipeline components without using transactions. The pipeline components process the order through the Plan stages of the pipeline:

REM -- Create the Order Process Pipeline
Set  mscsMtsPipeline = Server.CreateObject("Commerce.MtsPipeline")

Call mscsMtsPipeline.LoadPipe(Server.MapPath("\Clocktower") + "\config\plan.pcf")

errorLevel = mscsMtsPipeline.OrderExecute(1,  mscsOrderForm,  mscsPipeContext, 0)

The MtsPipeline object is usually created on each page in which it is used. The MtsTxPipeline object must be created on the page in which it is used because transactions cannot span multiple pages.

In Commerce Server 2.0 sites, the OrderPipeline object is usually created in Global.asa.


MtsPipeline.LoadPipe Method

The LoadPipe method loads a configuration (.pcf) file into the pipeline. The LoadPipe method must be called to initialize every pipeline.

Syntax

MtsPipeline.LoadPipe(Path)

Parameters

Path
The path and file name of the configuration file.

Remarks

The MtsPipeline.LoadPipe method fails if you attempt to load a configuration designated for MtsTxPipeline only.

Related Topics

  • υMtsTxPipeline and MtsPipeline Overview
  • υMtsPipeline.Execute Method
  • υMtsPipeline.SetLogFile Method
  • υThe ConfigurationCacheHelper Object


MtsPipeline.Execute Method

The Execute method runs the specified set of stages in the pipeline, applying their actions to the specified object. Before invoking Execute, you must load the pipeline configuration using the LoadPipe method.

Execute returns a Long result containing one of the following values:

  • υA result of 1 indicates the pipeline executed successfully.
  • υA result of 2 indicates errors raised by pipeline components in the basket or purchase error collections. These are typically customer errors, such as a mis-typed credit-card number. An error message is displayed to the customers so that they can submit the information again.
  • υA result of 3 indicates failure of the pipeline, such as the inability to access the database. This type of error cannot be corrected by the customer. (If calling the Execute method from within Microsoft® Visual Basic or Visual Basic Scripting Edition, the return value is not set in the case of failure. If you are using On Error Resume Next, check the Err object for errors, and check the return value for warnings. Do not call On Error Goto 0 before checking the status of the Err object, because this call clears it.)

Syntax

MtsPipeline.Execute(Mode, Object, PipeContext, Reserved)

Parameters

Mode
Specifies the mode in which to execute the stages in the pipeline. This parameter may be set to one of the following:
1    Runs the product verification stages (OPPMODE_PRODUCT).
2    Runs all stages except payment and accept (OPPMODE_PLAN).
4    Runs the complete pipeline (OPPMODE_PURCHASE).
Note

The Mode parameter is included only for backward compatibility with sites created in Commerce Server 2.0, and will be discontinued in future releases. In Commerce Server 3.0 and later, the selection of pipeline stages is made by loading an appropriate pipeline configuration file with the LoadPipe method. Commerce Server 3.0 applications should use the value one (1) for this parameter (zero (0) will cause no stages to run).

Object
The data object to be processed by the components in the pipeline. For an OPP, Object is usually an initialized OrderForm. For a CIP, Object is a transport dictionary used to store various properties during the execution of the pipeline.
PipeContext
The PipeContext object is a Dictionary object that references a group of initialized objects containing information needed by the pipeline.
Reserved
This value is not used and must be set to zero (0).

Remarks

The Execute method should be used instead of the RunProduct, RunPlan, and RunPurchase methods on the Page object, as used in Commerce Server 2.0.

Example

For an example of this method, see MtsTxPipeline and MtsPipeline Overview.

Related Topics

  • υMtsPipeline.LoadPipe Method
  • υThe PipeContext Dictionary


MtsPipeline.SetLogFile Method

The SetLogFile method identifies the file to which the pipeline logs operations that occur when the pipeline is run.

With this feature, the pipeline logs which pipeline components are called and what error values each component returns. The pipeline also logs all Dictionary and SimpleList object read/write operations.

Note

This method is intended for use by developers who want to analyze the operations of a pipeline configuration. Logging should never be enabled in a production environment, both because it degrades performance and because it can compromise the security of credit card numbers in non-set transactions.

Syntax

MtsPipeline.SetLogFile(Filename)

Parameters

Filename
The name of the file to which pipeline events are logged. When set to an empty string (""), logging is disabled.

Related Topics

  • υMtsPipeline.LoadPipe Method


The MtsTxPipeline Object

The MtsTxPipeline object creates and executes a pipeline. This pipeline may be used as an order processing pipeline (OPP) or as a Commerce Interchange Pipeline (CIP).

Commerce Server 3.0 provides three similar objects that execute pipeline configurations. These objects differ in the way in which they are registered with Microsoft® Transaction Server (MTS) (see MtsTxPipeline and MtsPipeline Overview).

The MtsTxPipeline object is registered under MTS as transactions required. This object holds a transaction that spans all components in the pipeline configuration.

Note

When used with a database, the MtsTxPipeline object requires an ODBC-compliant database that supports Microsoft Transaction Server.

The MSDTC service must be running in order to use the MtsTxPipeline object. (To verify this, on the Start menu point to Settings, and then click Control Panel. Double-click Services. Check that the status of MSDTC is shown as Started.) A failure of MTS appears in the Windows NT Application Event Log as a Transaction Server error.

The MtsTxPipeline object supports the following methods.

Method | Description
LoadPipe | Loads a configuration (.pcf) file into the pipeline.
Execute | Runs the components in the pipeline.
SetLogFile | Identifies the file to which pipeline events are logged.

Related Topics

  • υIPipeline Interface


MtsTxPipeline.LoadPipe Method

The LoadPipe method loads a configuration (.pcf) file into the pipeline. The LoadPipe method must be called to initialize every pipeline.

Syntax

MtsTxPipeline.LoadPipe(Path)

Parameters

Path
The path and file name of the configuration file.

Remarks

The MtsTxPipeline.LoadPipe method fails if you attempt to load a configuration designated for MtsPipeline only.)

Related Topics

  • υMtsTxPipeline and MtsPipeline Overview
  • υMtsTxPipeline.Execute Method
  • υThe ConfigurationCacheHelper Object


MtsTxPipeline.Execute Method

The Execute method runs the specified set of stages in the pipeline, applying their actions to the specified object. All operations performed by components in this pipeline are spanned within a single transaction by MTS.

Before invoking Execute, you must load the pipeline configuration using the LoadPipe method.

Execute returns a Long result containing one of the following values:

  • υA result of 1 indicates the pipeline executed successfully.
  • υA result of 2 indicates errors raised by pipeline components in the basket or purchase error collections. These are typically customer errors, such as a mis-typed credit card number. An error message is displayed to the customers so that they can submit the information again.
  • υA result of 3 indicates failure of the pipeline, such as the inability to access the database. This type of error cannot be corrected by the customer. (If calling the Execute method from within Microsoft® Visual Basic or Visual Basic Scripting Edition, the return value is not set in the case of failure. If you are using On Error Resume Next, check the Err object for errors, and check the return value for warnings. Do not call On Error Goto 0 before checking the status of the Err object, because this call clears it.)

Syntax

MtsTxPipeline.Execute(Mode, Object, PipeContext, Reserved)

Parameters

Mode
Specifies the mode in which to execute the stages in the pipeline. This parameter may be set to one of the following:
1    Runs the product verification stages (OPPMODE_PRODUCT).
2    Runs all stages except payment and accept (OPPMODE_PLAN).
4    Runs the complete pipeline (OPPMODE_PURCHASE).
Note

The Mode parameter is included only for backward compatibility with sites created in Commerce Server 2.0, and will be discontinued in future releases. In Commerce Server 3.0 and later, the selection of pipeline stages is made by loading an appropriate pipeline configuration file with the LoadPipe method. Commerce Server 3.0 applications should use the value one (1) for this parameter (zero (0) will cause no stages to run).

Object
The data object to be processed by the components in the pipeline. For an OPP, Object is usually an initialized OrderForm. For a CIP, Object is a transport dictionary used to store various properties during the execution of the pipeline.
PipeContext
The PipeContext object is a Dictionary object that references a group of initialized objects containing information needed by the pipeline.
Reserved
This value is not used and must be set to zero (0).

Remarks

The Execute method should be used instead of the RunProduct, RunPlan, and RunPurchase methods on the Page object, as used in Commerce Server 2.0.

Example

For an example, see MtsPipeline.Execute Method, which uses the same syntax as the MtsPipeline.Execute method.

Related Topics

  • υMtsTxPipeline.LoadPipe Method
  • υThe PipeContext Dictionary


MtsTxPipeline.SetLogFile Method

The SetLogFile method identifies the file to which the pipeline logs operations that occur when the pipeline is run.

Note

This method is intended for use by developers who want to analyze the operations of a pipeline configuration. Logging should never be enabled in a production environment, both because it degrades performance and because it can compromise the security of credit card numbers in non-set transactions.

Syntax

MtsTxPipeline.SetLogFile(Filename)

Parameters

Filename
The name of the file in which to log pipeline events. When set to an empty string (""), logging is disabled.

Related Topics

  • υMtsTxPipeline.Execute Method


The OrderForm Object

The OrderForm object provides for the in-memory storage of customer and purchase information. Commerce Server sites use the OrderForm object to store the items that a customer has chosen to purchase, and to store receipt information that reflects a given customer’s purchase history.

The OrderForm object supports the following methods.

Method | Description
AddItem | Adds an item to the OrderForm.
ClearOrderForm | Empties the OrderForm.
ClearItems | Clears the items collection from the OrderForm.

Related Topics

  • υIOrderForm Interface


OrderForm Object Overview

This object is created for the first time in the xt_orderform_additem.asp file when the customer adds an item to the basket. Subsequently, an instance of the OrderForm object is created whenever necessary by either the DBStorage.LookupData or the DBStorage.GetData method, and the order form data is read into it.

Use the Active Server Pages (ASP) Server object’s CreateObject method to create a OrderForm object, as follows:

REM -- create a new orderform:
set orderForm = Server.CreateObject("Commerce.OrderForm")

The OrderForm object is defined internally as a structured group of SimpleList and Dictionary objects, and includes the methods required to add items, clear items, and clear the entire OrderForm itself.

The following illustration represents a typical structure for this object. Individual sites may delete or add properties as needed.

Structure of a typical OrderForm object

The base of the OrderForm object is a Dictionary object that contains information that describes the entire order. This includes customer information, such as the shopper ID, name, and address, as well as order cost information, such as purchase subtotal, tax, shipping, and total.

The order form does not directly support storage of its data on disk. The DBStorage object enables persistent storage of order form data.

A number of the elements of the OrderForm’s base Dictionary object include underscore (_) characters. The appearance of an underscore character in an element name indicates that these items are not saved to the site’s order form storage. These elements are saved instead to the site’s receipt storage when the purchase is finalized.


OrderForm.AddItem Method

The AddItem method adds an item to the items collection of an OrderForm object. The items collection is a SimpleList object containing Dictionary objects.

If successful, AddItem returns a Dictionary object that contains the added item; otherwise Null.

Syntax

OrderForm.AddItem(SKU, Quantity, Price)

Parameters

SKU
The SKU of the item to add.
Quantity
A number indicating the quantity of the item to add.
Price
The placed price of the item.

Related Topics

  • υOrderForm.ClearOrderForm Method
  • υOrderForm.ClearItems Method


OrderForm.ClearItems Method

Empties the items collection on the OrderForm.

Syntax

OrderForm.ClearItems()

Parameters

None.

Remarks

A site uses the ClearItems method to respond to a customer’s having opted to cancel a purchase. This method affects only the information in the items collection. Other OrderForm information, such as _oadjust_subtotal and _total_total, is modified only if you run the order processing pipeline (OPP) on this OrderForm.

To empty the entire contents of the OrderForm, call the ClearOrderForm method.

Related Topics

  • υOrderForm.ClearOrderForm Method


OrderForm.ClearOrderForm Method

The ClearOrderForm method empties the entire OrderForm object.

Syntax

OrderForm.ClearOrderForm()

Parameters

None.

Related Topics

  • υOrderForm.ClearItems Method


The Page Object

The Page object supports methods that simplify the creation and layout of Active Server Pages (ASP) HTML pages.

Page object methods fall into the following categories:

  • υThe formatting methods include Encode, Option and Check, and are intended to make it possible for you to easily format HTML page items, and where applicable, to determine HTML item values based upon a run-time evaluation of other variables used in your page.
  • υThe validation methods are those that begin with Request, and are intended to retrieve values from a URL query string, convert the values to given data types based on a locale value, and validate these values against a specified range.

The Page object supports the following property.

Property | Description
Context | A read-only value that contains the Microsoft® Internet Information Server (IIS) scripting context.
VirtualDirectory | Name of the virtual directory for the site.

The Page object supports the following methods.

Method | Description
Check | Generates the word CHECKED based upon a supplied value.
Encode | Encodes text in HTML
GetShopperID | Returns the unique shopper ID for the current shopper.
HTMLEncode | Encodes text in HTML.
Option | Generates an option button on a page.
ProcessVerifyWith | Copies the contents of hidden fields created using the VerifyWith method into an OrderForm object’s _verify_with Dictionary object.
PutShopperID | Writes the specified shopper ID for use in a URL or SURL (or as a cookie).
RequestDate | Retrieves a value from a URL query string or form post variable and converts it to a date value (Date Variant) based on the specified or default locale
RequestDateTime | Retrieves a value from a URL query string or form post variable and converts the it to a date/time value (Date Variant), based on the specified or default locale.
RequestDefault | Retrieves a value from a URL query string or form post variable and returns the value as a string.
RequestFloat | Retrieves a value from a URL query string or form post variable and converts it to a floating-point value based on the specified or default locale, checks the value against a specified range, and then validates the value, based on the specified locale.
RequestMoneyAsNumber | Retrieves a value from a URL query string or form post variable and converts it to a number in the base monetary units of the specified or default locale.
RequestNumber | Retrieves a value from a URL query string or form post variable and converts it to a number based on the specified or default locale.
RequestString | Retrieves a value from a URL query string or form post variable and performs string processing on it, based on the specified locale.
RequestTime | Retrieves a value from a URL query string or form post variable and converts the string to a Date Variant, based on the specified or default locale.
SiteRoot | Returns the physical directory that contains the Commerce Server site.
SURL | Generates a secure URL based on the local path to a file. This URL includes the shopper ID, where applicable.
SURLPrefix | Returns the secure root domain, which can be used as the prefix of a complete URL
URL | Generates a full URL based on the local path to a file. This URL can include arguments and the shopper ID, where applicable.
URLArgs | Generates a series of query string arguments appropriate for passing in a URL.
URLEncode | Applies URL encoding rules to a specified string.
URLPrefix | Returns the non-secure root domain, which can be used as the prefix to a complete URL.
URLShopperArgs | Generates a series of query string arguments appropriate for passing in a URL, and includes in the arguments the shopper ID if the StandardSManager has been initialized to URL mode.
VerifyWith | Outputs to the page hidden fields that contain verification values.

The following methods are included only for backward compatibility with sites created in Commerce Server 2.0, and will be discontinued in future releases.

Method | Description
IncrShopperPerfCtrs | For backward compatibility only.
Messages | For backward compatibility only. Use the Language property of the PipeContext object.
RunPlan | For backward compatibility only.
RunProduct | For backward compatibility only.
RunPurchase | For backward compatibility only.


Page Object Overview

The Page object is usually created on each page. (In the Clocktower sample site, this object is created in Include\Shop.asp, which is included on every page in the site.) Use the ASP Server object’s CreateObject method to create a Page object, as follows:

Set mscsPage   = Server.CreateObject("Commerce.Page")

The Page object depends on the site dictionary, which must be named MSCSSite.


The Page Object's Request Methods

The Page Object’s Request Methods

The Page object supports a group of methods whose names begin with Request. These methods apply locale-based data type conversion and value range-checking to values retrieved from the client browser, either from a URL query string or form. Performing these operations on user input ensures that values retrieved through a page can be inserted without error into the site’s database storage or passed to the order processing pipeline (OPP) in an OrderForm object without generating pipeline or page syntax errors.

The following example illustrates how to use one of these methods, RequestDate, to perform locale-based data type conversion and range validation on a URL query string.

This example assumes that the date value is entered using the following form:

<FORM METHOD ="POST" ACTION="PROCESS.ASP">
<INPUT TYPE="Text" NAME="Date">
<INPUT TYPE="SUBMIT" NAME="ACTION" VALUE="Send Info">
</FORM>

If the user enters the date into the form and clicks the Send Info button, the value of this form field can be retrieved by the RequestDate method as follows:

StrDate = Page.RequestDate("Date", "2/27/98", "1/1/98", "12/31/98")
If IsNull(StrDate)
    REM    RequestDate failed.

The first parameter to RequestDate specifies, in this case, the name of the form field from which the data was submitted. If this text field is empty, the second parameter to RequestDate, "2/27/98" becomes the date that RequestDate processes. First, the string expression of the date is converted to a date value based on a specified locale, and then the value is checked against the specified date range specified by the third and fourth parameters. In the previous example , this locale is not specified, so RequestDate uses the value of the DataFunctions object’s Locale property as the basis of the conversion.

The following table shows the value returned under different conditions.

Condition | Method returns
Value is present in requested data and is valid. | Value returned from the URL query string or form post variable.
Value returned is empty or Null (for example, the customer did not type a value in the field), or variable does not exist in requested data. | Default value (Null, or the value specified by the Default parameter if specified).
Value returned is out of specified range. | Null.
Value returned is invalid according to rules for locale. | Null.


Page.Check Method

The Check method generates the word CHECKED into a page if the value specified in the Value parameter is a nonzero value. CHECKED is a parameter to an HTML <INPUT> tag, which sets a check box or radio button to selected when the form first loads.

Syntax

Page.Check(Value)

Parameters

Value
An expression that is evaluated to determine whether the word CHECKED should be inserted at the place in a page where the call to Check appears.

Example

The following example could be used in an ASP file to generate three radio buttons in an HTML form:

<% my_color="Green" %>
<INPUT TYPE="RADIO" NAME="CONTROL1" VALUE="0"<% = mscsPage.Check(my_color="Red")%>>Red
<INPUT TYPE="RADIO" NAME="CONTROL1" VALUE="1"<% = mscsPage.Check(my_color="Green")%>>Green
<INPUT TYPE="RADIO" NAME="CONTROL1" VALUE="2"<% = mscsPage.Check(my_color="Blue")%>>Blue

Assuming that my_color contains "Green" this produces the following HTML output:

<INPUT TYPE="RADIO" NAME="CONTROL1" VALUE="0">Red
<INPUT TYPE="RADIO" NAME="CONTROL1" VALUE="1"CHECKED>Green
<INPUT TYPE="RADIO" NAME="CONTROL1" VALUE="2">Blue

This HTML output produces three radio buttons labeled Red, Green, and Blue, with the Green option selected.

Related Topics

  • υPage.Option Method


Page.Context Property

The Context property is a read-only property that contains the ASP scripting context.

A site builder usually does not need to retrieve the contents of the Context property, and uses the Context property only as a parameter to other Commerce Server methods that need access to the ASP context.


Page.Encode Method_

The Encode method applies HTML encoding to the specified text string.

Note

This method is identical to Page.HTMLEncode, which is the preferred name for this function.

Syntax

Page.Encode(String)

Parameters

String
The text string to encode.


Page.GetShopperID Method

The GetShopperID method returns the unique shopper ID for the current customer. (The shopper ID is returned from a URL query string or a cookie, depending on the initialization mode of the StandardSManager for the site.)

Syntax

Page.GetShopperID()

Parameters

None.

Remarks

If the current customer does not have a shopper ID, GetShopperID returns Null.

Related Topics

  • υPage.PutShopperID Method


Page.HTMLEncode Method

The HTMLEncode method applies HTML encoding to the specified text string. Its typical use is to display the contents of text fields contained in the database in HTML. Characters in the string such as “<” and “&” that have special meanings in HTML are converted into their HTML equivalents, such as &lt; and &amp; so that they will be displayed correctly by the client browser.

Syntax

Page.HTMLEncode(String)

Parameters

String
The text string to encode.

Examples

The following example displays the contents of the company_name field as an <H1> tag:

<H1><% = mscsPage.HTMLEncode(companyinfo.company_name) %></H1>

Assuming that the field contains the name Lakes & Sons, the previous example returns the following HTML string:

<H1>Lakes &amp; Sons</H1>

The following example creates a text field in a form, using as the initial value the contents of the query string argument myString. Because this string might contain a character such as double-quote ("), which would be interpreted incorrectly on the page, the string is first encoded with the HTMLEncode method.

<INPUT TYPE="TEXT" NAME="myString" VALUE="<% = mscsPage.HTMLEncode(Request("myString")) %>">

The following example, from Clocktower’s Default.asp, displays the name of a department, where rsDeptlist is a recordset resulting from a query. Note the use of the Value property:

<% = mscsPage.HTMLEncode(rsDeptlist("dept_name").Value) %>

Remarks

If the text field to be displayed already contains HTML encoding, do not use the HTMLEncode method. For example, suppose your product_descr field contains HTML-encoded text such as “The <I>Classic Diner Clock</I> brings the age of the &quot;Golden Oldies&quot; to your kitchen.” This string uses the <I> tag to format italic text and the &quot; sequence to display quotation marks when displayed by the client browser. Because the string is already coded in HTML, you do not need to encode it again. Double-encoding the string would produce incorrect results.

Page.HTMLEncode is identical to Page.Encode, but HTMLEncode is the preferred name. The method is similar to Server.HTMLEncode except that the Page.HTMLEncode method handles Null values by returning an empty string (Server.HTMLEncode fails when the String parameter is Null). This distinction is important because a database queries can return Null.

Related Topics

  • υPage.URLEncode Method


Page.Option Method

The Option method generates an OPTION item in an HTML form selection list, and assigns it the value and selection state that you specify.

Syntax

Page.Option(Value, State)

Parameters

Value
The value of the option in the selection list.
State
A value that indicates whether the list option is the selected option. If State is equal to Value, then the HTML keyword SELECTED is inserted in the definition of the option list.

Example

The following example generates a selection field in an HTML form to enable the customer to select the expiration year of the credit card. The Option method generates <OPTION VALUE="> tags and marks the current year as selected:

iyear = Year(date) %>

<SELECT NAME="_cc_expyear">
    <% = mscsPage.Option(1997, iyear) %> 1997
    <% = mscsPage.Option(1998, iyear) %> 1998
    <% = mscsPage.Option(1999, iyear) %> 1999
    <% = mscsPage.Option(2000, iyear) %> 2000
    <% = mscsPage.Option(2001, iyear) %> 2001
    <% = mscsPage.Option(2002, iyear) %> 2002
    <% = mscsPage.Option(2003, iyear) %> 2003
</SELECT>

Following is the HTML output that is produced by the ASP script shown previously, assuming that the current year is 1998:

<SELECT NAME="_cc_expyear">
    <OPTION VALUE="1997"> 1997
    <OPTION VALUE="1998" SELECTED> 1998
    <OPTION VALUE="1999"> 1999
    <OPTION VALUE="2000"> 2000
    <OPTION VALUE="2001"> 2001
    <OPTION VALUE="2002"> 2002
    <OPTION VALUE="2003"> 2003
</SELECT>

Related Topics

  • υPage.Check Method


Page.ProcessVerifyWith Method

The ProcessVerifyWith method is used in an ASP file that is activated when the customer submits an HTML form containing an order. ProcessVerifyWith reads the posted contents of hidden fields in the HTML form that were created using the VerifyWith method, and writes these values into a Dictionary object, called _verify_with, which is stored in the OrderForm object.

When the pipeline processes the OrderForm, the contents of the _verify_with Dictionary object are compared to the original values of the fields in the OrderForm object, to ensure that a page has not been altered between presentation and final purchase.

If the fields do not match, the RequiredTotal pipeline component generates an error, using the MessageManager message name constant pur_badverify.

Syntax

Page.ProcessVerifyWith(OrderForm)

Parameters

OrderForm
An OrderForm object that contains the basket for the current customer.

Example

call page.ProcessVerifyWith(orderForm)

Related Topics

  • υPage.VerifyWith Method
  • υThe MessageManager Object


Page.PutShopperID Method

The PutShopperID method writes the specified shopper ID to a cookie, and/or stores it for use in a URL or SURL, depending on the initialization mode of the StandardSManager for the site.

Syntax

Page.PutShopperID(ShopperID)

Parameters

ShopperID
An ID that uniquely identifies this customer.

Remarks

Where the PutShopperID method stores the specified shopper ID depends upon the StandardSManager initialization mode. In URL mode, this method writes the shopper ID to the request, so that the URL and SURL methods add the shopper ID to a query string in the URL from this page.

If the shopper ID is stored in a URL query string, you can retrieve it by passing the value you set for the application-level MSCSSIDURLKey to the IIS Request object.

If you initialize the StandardSManager in URL mode, you cannot use the StandardSManager’s implementation of PutShopperID to store the shopper ID on the client system. Instead, you must use the Page object’s implementation.

Related Topics

  • υPage.GetShopperID Method
  • υPage.SURL Method
  • υPage.URL Method


Page.RequestDate Method

The RequestDate method retrieves a value from a URL query string or form post variable and converts it to a date value (Date Variant) based on the specified or default locale.

Optionally, RequestDate also checks the date against a specified date range.

Syntax

Page.RequestDate(Name, Default, LowDate, HighDate, Locale)

Parameters

Name
The name of the URL query string or form post variable to retrieve.
Default
Optional. The date to return if the requested URL query string or form post variable does not exist or contains no value. If this parameter is not supplied, the method returns Null in this case.
LowDate
Optional. A date value that specifies the low end of the range against which to validate Name. The default value is Null, which means that this parameter is ignored.
HighDate
Optional. A date value that specifies the high end of the range against which to validate Name. The default value is Null; this parameter is ignored.
Locale
Optional. A number that specifies the locale to use to convert the date. If this value is not specified, RequestDate uses the value of the DataFunctions object’s Locale property.

Related Topics

  • υThe Page Object’s Request Methods
  • υDataFunctions.ConvertDateString Method
  • υDataFunctions.Date Method
  • υPage.RequestDateTime Method


Page.RequestDateTime Method

The RequestDateTime method retrieves a value from a URL query string or form post variable and converts the it to a date/time value (Date Variant), based on the specified or default locale.

Optionally, RequestDateTime validates the date/time value against a minimum and maximum value that you specify.

Syntax

Page.RequestDateTime(Name, Default, LowDateTime, HighDateTime, Locale)

Parameters

Name
The name of the URL query string or form post variable to retrieve.
Default
Optional. The value to return if the requested URL query string or form post variable does not exist or contains no value. If this parameter is not supplied, the method returns Null in this case.
LowDateTime
Optional. A value that specifies the low end of the range.
HighDateTime
Optional. A value that specifies the high end of the range.
Locale
Optional. A number that identifies the locale to be used to convert the date/time string. If this parameter is not specified, RequestDateTime uses the value of the DataFunctions object’s Locale property.

Related Topics

  • υThe Page Object’s Request Methods
  • υDataFunctions.ConvertDateTimeString Method
  • υDataFunctions.DateTime Method
  • υPage.RequestDate Method
  • υPage.RequestTime Method


Page.RequestDefault Method

The RequestDefault method retrieves a value from a URL query string or form post variable and returns the value as a string.

Syntax

Page.RequestDefault(Name, Default)

Parameters

Name
The name of the URL query string variable to retrieve.
Default
Optional. The value to return if the requested URL query string or form post variable contains an empty string or a Null, or is not present in the request string. If this parameter is not supplied, the method returns Null in this case.

Remarks

This method is designed so that if a field on a form is blank, or the form does not contain the field, the value returned by default is Null. Null is generally the appropriate value to store to a database when a value is not present. If you need the result to be an empty string in the case of a missing value, supply an empty string as the Default parameter, as in the following example:

Page.RequestDefault("shopper_phone", "")

Example

The following example attempts to retrieve the value for the URL query string variable shopper_phone. Because no Default argument is supplied, if this URL query string variable has no value, the call to RequestDefault returns Null:

shopper_phone = Page.RequestDefault("shopper_phone")

Related Topics

  • υThe Page Object’s Request Methods
  • υPage.RequestString Method


Page.RequestFloat Method

The RequestFloat method retrieves a value from a URL query string or form post variable and converts it to a floating-point value based on the specified or default locale. Optionally, RequestFloat also checks the converted number against the specified range.

Syntax

Page.RequestFloat( Name, Default, LowFloat, HighFloat, Locale)

Parameters

Name
The name of the URL query string or form post variable to retrieve.
Default
Optional. The value to return if the requested URL query string or form post variable is not present or contains no value. If this parameter is not supplied, the method returns Null in this case.
LowFloat
Optional. A number that specifies the low end of the range of values against which to validate the converted value. The default value for this parameter is zero (0), which means that this parameter is ignored.
HighFloat
Optional. A number that specifies the high end of the range of values against which to validate the converted value. The default value for this parameter is zero (0), which means that this parameter is ignored.
Locale
Optional. A number that identifies the locale to use to convert the value. If this value is not specified, RequestFloat uses the value of the DataFunctions object’s Locale property.

Related Topics

  • υThe Page Object’s Request Methods
  • υDataFunctions.ConvertFloatString Method
  • υDataFunctions.Float Method
  • υDataFunctions.ValidateFloat Method
  • υPage.RequestNumber Method


Page.RequestMoneyAsNumber Method

The RequestMoneyAsNumber method retrieves a value from a URL query string or form post variable and converts it to a number in the base monetary units of the specified or default locale.

Syntax

Page.RequestMoneyAsNumber(Name, Default, LowMoney, HighMoney, Locale)

Parameters

Name
The name of the URL query string or form post variable to retrieve.
Default
Optional. The value to return if the requested URL query string or form post variable is not present or contains no value. If this parameter is not supplied, the method returns Null in this case.
LowMoney
Optional. A monetary value that specifies the low end of the range against which to validate the converted value.
HighMoney
Optional. A monetary value that specifies the high end of the range against which to validate the converted value.
Locale
Optional. A number that specifies the locale to use to convert Name. If this parameter is not used, RequestMoneyAsNumber uses the value of the DataFunctions object’s Locale property.

Example

In the following example, the value of a field on the purchase form (filled out by the customer) is read into the variable cc_expmonth. The HighMoney argument is the upper limit of a Long variable. Using this value as the upper limit and zero (0) as the lower limit of the range check ensures that the value is not negative:

list_price = mscsPage.RequestMoneyAsNumber("list_price", 0, 0, 2147483647)

Related Topics

  • υThe Page Object’s Request Methods
  • υDataFunctions.ConvertMoneyStringToNumber Method
  • υDataFunctions.Money Method
  • υPage.RequestFloat Method
  • υPage.RequestNumber Method


Page.RequestNumber Method

The RequestNumber method retrieves a value from a URL query string or form post variable and converts it to a number based on the specified or default locale.

Optionally, RequestNumber checks the converted number against the specified range, and validates it based on the specified locale.

Syntax

Page.RequestNumber( Name, Default, LowNumber, HighNumber, Locale)

Parameters

Name
The name of the URL query string or form post variable to retrieve.
Default
Optional. The value to return if the requested URL query string or form post variable is not present or contains no value. If this parameter is not supplied, the method returns Null in this case.
LowNumber
Optional. A number value that specifies the low end of the range against which to validate the converted value.
HighNumber
Optional. A number value that specifies the high end of the range against which to validate the converted value.
Locale
Optional. A number that specifies the locale to use to convert Name. If this parameter is not used, RequestNumber uses the value of the DataFunctions object’s Locale property.

Example

In the following example, the value of a field on the purchase form (filled out by the customer) is read into the variable cc_expmonth. Because the Default parameter is specified as null, RequestNumber will return Null if the field is empty or missing, or if the month typed in the field is outside of the range of 1 to 12:

cc_expmonth = page.RequestNumber("_cc_expmonth", null, 1, 12)

Related Topics

  • υThe Page Object’s Request Methods
  • υDataFunctions.ConvertNumberString Method
  • υDataFunctions.Number Method
  • υDataFunctions.ValidateNumber Method
  • υPage.RequestFloat Method


Page.RequestString Method

The RequestString method retrieves a value from a URL query string or form post variable and performs string processing on it, based on the specified locale.

This processing may involve stripping out leading and trailing white spaces, stripping out carriage returns, checking the string’s length against a specified range, and validating the string based on the specified or default locale.

Syntax

Page.RequestString(Name, Default, MinStrLen, MaxStrLen, StripWhiteSpaces, StripReturn, Case, Locale)

Parameters

Name
The name of the URL query string or form post variable to retrieve.
Default
Optional. The string to return if the specified query string or form post variable does not exist or contains no value. If this parameter is not supplied, the method returns Null in this case.
MinStrLen
Optional. A number that indicates the minimum length against which the length of Name must be validated.
MaxStrLen
Optional. A number that indicates the maximum length against which the length of Name must be validated. The default value is 65535.
StripWhiteSpaces
Optional. A Boolean value that indicates whether the leading and trailing white spaces should be stripped from the string. The default value for this parameter is False.
StripReturn
Optional. A Boolean value that indicates whether the carriage returns should be stripped from the string. The default value for this parameter is False.
Case
Optional. A number that indicates the case to which the string should be converted. The default value for this parameter is zero (0), which results in no modification to the case of the string. If Case is 1, the string is converted to uppercase. If Case is 2, the string is converted to lowercase.
Locale
Optional. A number that specifies the locale to be used as the basis of the conversion. If this value is not specified, RequestString uses the value of the DataFunctions object’s Locale property.

Example

In the following example, the value of a field on the purchase form (filled out by the customer) is read into the variable ship_to_name. Because the Default parameter is specified as null, RequestString returns Null if the field is empty or missing, or if the string is outside of the range of 1 to 100 characters:

ship_to_name = page.RequestString("ship_to_name", null, 1, 100)

Related Topics

  • υThe Page Object’s Request Methods
  • υDataFunctions.CleanString Method


Page.RequestTime Method

The RequestTime method retrieves a value from a URL query string or form post variable and converts the string to a Date Variant, based on the specified or default locale.

Optionally, RequestTime also checks the time against a specified range.

Syntax

Page.RequestTime(Name, Default, LowTime, HighTime, Locale)

Parameters

Name
The name of the URL query string or form post variable to retrieve.
Default
Optional. The time value to return if the specified query string or form post variable does not exist or contains no value. If this parameter is not supplied, then RequestTime returns Null in this case.
LowTime
Optional. A time value that specifies the low end of the range against which to validate Name. The default is no low-end validation.
HighTime
Optional. A time value that specifies the high end of the range against which to validate Name. The default is no high-end validation.
Locale
Optional. A number that specifies the locale to use to convert the date/time value. If this value is not specified, RequestTime uses the value of the DataFunctions object’s Locale property.

Related Topics

  • υThe Page Object’s Request Methods
  • υDataFunctions.ConvertTimeString Method
  • υPage.RequestDate Method


Page.SiteRoot Property

The SiteRoot method returns the physical directory that contains the Commerce Server site.

Example

The following example is from the Product.asp file in a site generated by the Commerce Site Builder Wizard:

<IMG SRC="<%= "/" & mscsPage.SiteRoot %>/assets/product_images/
<%= mscsPage.HTMLEncode(rsProduct("image_file").value) %>"

This example uses the SiteRoot method to get the directory in which the site is located, which it then uses to form a reference to the graphic image for the product, which is then displayed on the product page. Assuming the site resides in a directory called mysite, the example resolves to the following HTML code:

<IMG SRC="/mysite/assets/product_images/product.gif"

Related Topics

  • υPage.VirtualDirectory Property


Page.SURL Method

The SURL method generates a properly formatted Secure HTTP URL based on the provided file name and an optional list of name/value arguments. The formatted URL includes the server name (copied from the site dictionary’s SecureHostName value), the virtual directory in which the file is stored (taken from the context in which the Web site is running), and the name of the file itself .

Additionally, if the StandardSManager for the application is initialized in URL mode, the SURL method uses the value stored in the MSCSSIDUrlKey Application object variable as the name in a name/value pair, the value of which is the current customer’s shopper ID.

Syntax

Page.SURL(Filename, Arguments)

Parameters

Filename
The name of the file for the SURL to reference.
Arguments
An optional list of arguments that identify the name/value pairs to be appended to the SURL.

Remarks

During application development, you can set the Site.DisableHTTPS property to one (1), which causes the SURL method to use the NonsecureHostName value as the host name. The SURL method generates a secure URL only if Site.DisableHTTPS is set to zero (0).

Example

The following example is from Clocktower’s Purchase.asp file:

<FORM METHOD="POST"
   ACTION="<% = mscsPage.SURL("xt_orderform_purchase.asp") %>">

Assuming that the host name is www.microsoft.com, and assuming that security is not disabled, the preceding example produces the following URL (note that the protocol is specified as HTTPS):

https://www.microsoft.com/clocktower/xt_orderform_purchase.asp

Related Topics

  • υPage.URL Method
  • υSite.DisableHTTPS Value


Page.SURLPrefix Method

The SURLPrefix method returns the secure root domain as determined by the site dictionary’s SecureHostName value. The returned string can be used as the prefix of a complete URL.

Syntax

Page.SURLPrefix()

Parameters

None.

Remarks

During application development, you can set the DisableHTTPS property of the site dictionary is set to one (1), which causes the SURLPrefix method to use the NonsecureHostName value as the host name. The SURLPrefix method generates a secure URL only if Site.DisableHTTPS is set to zero (0).

Example

The following script:

mscsPage.SURLPrefix()

returns the following string, assuming the secure host domain is www.microsoft.com:

https://www.microsoft.com

Related Topics

  • υPage.VirtualDirectory Property
  • υPage.SURL Method
  • υPage.URLArgs Method
  • υPage.URLShopperArgs Method


Page.URL Method

The URL method generates a URL based on the specified file name and an optional list of name/value arguments. This URL includes the server name, the virtual directory in which the file is stored, and the name of the file itself.

Additionally, if the StandardSManager for the application is initialized in URL mode, the URL method uses the value stored in the Application object’s MSCSSIDUrlKey variable as the name in a name/value pair, the value of which is the current shopper ID.

The method applies URL encoding to the values passed in.

Syntax

Page.URL(Filename, Arguments)

Parameters

Filename
The name of the file to reference in the URL.
Arguments
An optional list of name/value pairs.

Remarks

The URL method spares the site builder the need to map a file to the HTTP path to that file, or to build name/value pairs manually into the query string appended to the URL. For example, assume the following call to URL:

<%= Page.URL("filename.asp", "sku", sku) %>

This call resolves to the correct HTTP path to filename.asp, and appends the sku name and sku value to that URL as follows:

http://host_name/virtual_directory/filename.asp?sku=13428

The value for host_name is determined by the contents of the site dictionary’s NonsecureHostName value, or in the case of the SURL method, the SecureHostName value. The virtual_directory is determined automatically from the scripting context.

For sites in which the StandardSManager is initialized in URL mode, a call to URL, SURL or URLShopperArgs appends the current customer’s shopper ID to the URL argument list. The name of the argument passed in the URL is stored in the Application object’s MSCSSIDUrlKey variable. Thus, where the Application object’s MSCSSIDUrlKey variable is initialized as Application("MSCSSIDURLKey") = "mscssid" and where the StandardSManager is running in URL mode, the script:

<%= Page.URL("filename.asp", "sku", sku) %>

resolves to the following:

http://host_name/virtual_directory/filename.asp?sku=13428&mscssid=Q0H4SE915ASH2KC000Q79QB1E

You can generate the parts of a URL separately, using the methods and properties shown in the following table.

Elements of a URL

URL Part | Obtained using | Example
Domain | page.URLPrefix page.SURLPrefix | http(s)://www.microsoft.com
Directory | page.VirtualDirectory | clocktower
Arguments | page.URLArgs() | sku=1342
Arguments with shopper ID | page.URLShopperArgs() | sku=13428&current_shopper=12345

Related Topics

  • υPage.VirtualDirectory Property
  • υPage.SURL Method
  • υPage.SURLPrefix Method
  • υPage.URLArgs Method
  • υPage.URLPrefix Method
  • υPage.URLShopperArgs Method
  • υThe StandardSManager Object


Page.URLArgs Method

The URLArgs method generates a series of query string arguments in an appropriate form for passing in a URL. The method applies URL encoding to the values passed in.

Syntax

Page.URLArgs(Arguments)

Parameters

Arguments
An optional list of name/value pairs.

Example

The following example:

Page.URLArgs("a", 1, "b", 2)

returns the string:

a=1&b=2

The following example (from Volcano Coffee’s Manager/xt_data_add_update.asp file) redirects the client browser to the page specified by the goto query string variable, and appends as query string arguments the product family ID and the attribute ID.

Response.redirect Cstr(Request.Form("goto")) & "?" & mscsPage.URLArgs("pfid", CStr(Request.Form("pfid")), "attribute_id", CStr(Request.Form("attribute_id")))

Related Topics

  • υPage.URLEncode Method
  • υPage.VirtualDirectory Property
  • υPage.SURL Method
  • υPage.SURLPrefix Method
  • υPage.URL Method
  • υPage.URLPrefix Method
  • υPage.URLShopperArgs Method


Page.URLEncode Method

The URLEncode method applies URL encoding rules, including escape characters, to a specified string. A URL-encoded string may be passed in a URL as a query string argument.

Syntax

Page.URLEncode(String)

Parameters

String
The string to encode.

Remarks

Strings that contain certain characters such as spaces, slashes (/) or percentage symbols (%) cannot be passed as URL query arguments. URL encoding encodes these characters as escaped text so that they can be passed in a URL.

The Page.URLEncode method is equivalent to Server.URLEncode, except that the Page.URLEncode method handles Null values by returning an empty string (Server.URLEncode fails when the String parameter is Null). This distinction is important because a database queries can return Null.

Example

Suppose that a variable called referringURL contains the URL http://www.microsoft.com, which is to be passed as a query string argument in another URL.

The following script:

<A HREF="Sample.asp?referringURL=<% = mscsPage.URLEncode(referringURL) %>">My link</A>

generates the following HTML:

<A HREF="Sample.asp?referringURL=http%3A%2F%2Fwww%2Emicrosoft%2Ecom">My link</A>

The receiving page (Sample.asp) can use the Request method to get the value of the variable. The method converts the string back to its original form and returns it to the script on the page.

Related Topics

  • υPage.HTMLEncode Method


Page.URLPrefix Method

The URLPrefix method returns the root domain as determined by the site dictionary’s NonSecureHostName value. The returned string can be used as the prefix to a complete URL.

Syntax

Page.URLPrefix()

Parameters

None.

Remarks

To generate the domain for the secure host, use the Page.SURLPrefix method.

Example

The following example:

mscsPage.URLPrefix()

returns the following string, assuming the domain is www.microsoft.com:

http://www.microsoft.com

Related Topics

  • υPage.VirtualDirectory Property
  • υPage.SURL Method
  • υPage.SURLPrefix Method
  • υPage.URL Method
  • υPage.URLArgs Method
  • υPage.URLShopperArgs Method


Page.URLShopperArgs Method

The URLShopperArgs method generates a series of query string arguments in an appropriate form for passing in a URL, and includes in the arguments the shopper ID if the StandardSManager has been initialized to URL mode. The URLShopperArgs method URL-encodes the values passed in.

Syntax

Page.URLShopperArgs(Arguments)

Parameters

Arguments
An optional list of name/value pairs.

Remarks

URLShopperArgs appends the current customer’s shopper ID to the URL argument list. The name of the argument passed in the URL is stored in the Application object’s MSCSSIDUrlKey variable.

Example

Assuming that the Application object’s MSCSSIDUrlKey variable is initialized as Application("MSCSSIDURLKey") = "mscssid", that the StandardSManager is running in URL mode, and that the value of sku is 123, the script

<%= Page.URLShopperArgs("sku", sku) %>

resolves to the following:

sku=123&mscsid=Q0H4SE915ASH2KC000Q79QB17E

If no arguments are given, the method returns only the shopper ID in the query string:

mscssid=Q0H4SE915ASH2KC000Q79QB17E

The following example redirects the current page to the Basket.asp page using a relative URL and appending the shopper ID:

pageRedirect = "basket.asp" & "?" & mscsPage.URLShopperArgs()
call Response.Redirect(pageRedirect)

Related Topics

  • υPage.SURLPrefix Method
  • υPage.URL Method
  • υPage.URLArgs Method
  • υPage.URLPrefix Method
  • υPage.URLShopperArgs Method


Page.VerifyWith Method

The VerifyWith method outputs HTML tags in the form <INPUT TYPE="HIDDEN"> in an HTML form. These hidden fields contain specified values from the OrderForm object, to be used to verify that an order has not been altered between presentation of the OrderForm and final purchase. When the order form is submitted, the ProcessVerifyWith method on the target page stores these fields in a Dictionary object in the OrderForm, which is then passed to the OPP. One of the objects in the pipeline compares the original values with the values from the hidden fields.

Syntax

Page.VerifyWith(OrderForm, Arguments)

Parameters

OrderForm
The OrderForm object that contains the values to verify.
Arguments
One or more arguments that identify the OrderForm fields to use for verification.

Remarks

The VerifyWith method verifies String, Number or Double Variants. This method cannot be used to verify a Date Variant.

Example

The following example generates hidden fields containing the values stored in the _total_total, ship_to_zip, and _tax_total fields of the supplied OrderForm object:

<FORM METHOD="POST"
    ACTION="<% = mscsPage.SURL("xt_orderform_purchase.asp") %>">
    <% = mscsPage.VerifyWith(mscsOrderForm, "_total_total", "ship_to_zip", "_tax_total") %>

When the page containing this call is loaded in the client browser, the document source for the page would contain the following HTML script (assuming a total of 138.95, a zip code of 98133, and a tax of 8.75):

<FORM METHOD="POST"
ACTION="http://example.microsoft.com/clocktower/xt_orderform_purchase.asp">
<INPUT TYPE=HIDDEN NAME="_VERIFY_WITH" VALUE="_total_total=13895">
<INPUT TYPE=HIDDEN NAME="_VERIFY_WITH" VALUE="ship_to_zip=98133">
<INPUT TYPE=HIDDEN NAME="_VERIFY_WITH" VALUE="_tax_total=875">

Related Topics

  • υPage.ProcessVerifyWith Method


Page.VirtualDirectory Property

The VirtualDirectory property contains the name of the virtual directory for the site.

Example

Assuming that the path to a site is:

http://www.microsoft.com/clocktower/default.asp

then the following script displays “clocktower”:

Response.Write mscsPage.VirtualDirectory

Related Topics

  • υPage.SiteRoot Property
  • υPage.SURL Method
  • υPage.SURLPrefix Method
  • υPage.URL Method
  • υPage.URLArgs Method
  • υPage.URLPrefix Method
  • υPage.URLShopperArgs Method
  • υThe StandardSManager Object


The Predictor Object

The Predictor object enables Intelligent Cross-Sell by suggesting other items that a customer might be interested in.

The Predictor makes its suggestions by correlating the items that the customer has ordered with a database of items that other customers have ordered previously. The object examines the database to find orders that are similar to the current customer’s order, and generates a list of recommended products. The object also ensures that none of the products already in the current customer's order are suggested.

The Predictor object provides an automated means for constructing a dynamic, adaptive cross-sell table that changes as products and buying trends change. The Predictor removes the burden of having to create and maintain a cross-sell table manually. Another advantage of this object is that predictions can be made based on a combination of items and not on a per-item basis as is done in traditional manually constructed cross-sell tables.

The Predictor object supports the following methods.

Method | Description
GetPredictions | Examines a customer’s order form (or any list of orders) and suggests other products in which the customer may be interested.
InitPredictor | Builds a knowledge base of customer preferences by importing a table containing the site purchase history.


Predictor Object Overview

The Predictor object is usually created in the Global.asa file. Use the Active Server Pages (ASP) Server object’s CreateObject method to create a Predictor object, as follows:

REM -- Create the predictive cross selling engine
set MSCSPredictor = Server.CreateObject("Commerce.Predictor")

Also in Global.asa, store the new object in the Application object, as follows:

Set Application("MSCSPredictor")    = MSCSPredictor

The Predictor object depends on two resources in order to model its predictions:

  • A site purchase history.
  • A customer interest list.

Site Purchase History

The site purchase history is a database table of previous purchases by all customers at the site. The site purchase history provides the raw data that is input to the Predictor by means of the InitPredictor method. The InitPredictor method processes this input to produce a knowledge base.

The site purchase history must contain, at minimum, the shopper ID, the SKU, and the quantity for each item purchased. Preferably, it also contains the date, enabling an administrator to remove outdated records.

The site purchase history is updated for each item in the basket that is purchased by the SQLItemADO pipeline component in the Accept stage of the pipeline, which runs a query defined in the site’s query map as follows:

MSCSQueryMap.insert_predictor_data.SQLCommand = "insert into mspress30_predictor_data values (?, ?, ?, {fn CurDate()})"

In building the knowledge base, the Predictor object processes all purchased items listed in the site purchase history. The resulting knowledge base is organized by shopper ID, so that it consists of merged baskets that each contain all the items ever purchased by each customer, as long as the orders are still included in the site purchase history. Because information is collected for specific customers even when the items are purchased at different times, the knowledge base contains more complete customer preference patterns.

Customer Interest List

The customer interest list is a list of items in which the current customer has already ordered or expressed interest. Usually, this list contains the contents of the customer’s shopping basket, but it can also contain products the customer has requested information on, or purchased in the past.

In the page in which you want the suggested cross promotional items to appear, use scripting to pass the customer interest list as an argument to the GetPredictions method. This method then returns a list of additional items to suggest to the customer, based on the customer interest list and purchasing patterns. Your page then displays the suggested items to the customer.

The customer interest list is implemented as a SimpleList object that contains Dictionary objects, where each Dictionary object represents an item and contains properties representing the SKU and quantity for each item.

The GetPredictions method excludes any items that are in the customer interest list from the returned list of suggestions. For products (such as books) that customers tend to purchase only once, you can submit as the customer interest list not just the customer's current basket, but a merged collection of all items that customer has ever purchased, using data from the receipts table. Not only will this generate a more accurate list of recommendations, it will also prevent the list of recommendations from including books the shopper has previously purchased.

Maintaining the Site Purchase History

As purchases are made, they are added to the site purchase history. However, Predictor component is not affected by changes to the site purchase history until the InitPredictor method is called.

Note

Reinvoke the InitPredictor method as the mix of relevant products and relevant user purchase patterns change. Usually, the initialization should be invoked at least once a week, and possibly more often depending on the application.

The following additional suggestions will help to ensure optimal results when using the Predictor object:

  • υRebuild and purge the site purchase history of older entries over time. Without occasional purging, the site purchase history would accumulate transactions forever. Frequent removal of older items can be especially important for stores that change or update their inventory of offerings frequently. Purge the oldest items first, so that as trends in buying change, the Predictor will continue to emphasize the most recent trends.
  • υMake sure that the site purchase history contains many more baskets than there are SKUs appearing in those baskets. Preferably there should be at least 5 to 10 times as many baskets as SKUs in the site purchase history. Baskets containing only one SKU (after all baskets of a customer are merged) are not used by the Predictor object.
  • υWhen a site is first deployed and does not have any transactions, the Predictor object will be unable to make predictions. It may be desirable to seed the site purchase history with a set of typical or generic customer transactions.
Note

The Predictor object works with Microsoft® SQL Server™ or Oracle databases. It does not work with Microsoft® Access databases.

Examples

The following two topics illustrate the use of the Predictor object, using example code from the Microsoft® Press starter site:

  • υPredictor Example: Microsoft Press Basket.asp
  • υPredictor Example: Microsoft Press Product.asp


Predictor Example: Microsoft Press Basket.asp

The Basket.asp page displays items that the customer has ordered, or placed in the shopping basket. In this example, from the Microsoft Press® site, the Basket.asp page includes Intelligent Cross-Sell, by suggesting other items that the customer might be interested in based on the contents of the basket and on the site purchase history.

Before the page can call the GetPredictions method, it must create a list of purchased items to pass to this method. This list already exists in the OrderForm object, assuming that the customer has already placed at least one item in the basket. The list of items is a property of the OrderForm object and is named Items. (Refer to the figure in OrderForm Object Overview.)

The following code is invoked immediately after the OrderForm object is created. The code creates a variable called orderitems, which references the item list if an order form exists for this customer:

set orderitems = mscsOrderForm.Items

This list of items is later passed as an argument to GetPredictions.

The following code calls the GetPredictions method, which returns the resulting suggested items in a SimpleList object called products. This list is then enumerated, and for each item, the SKU value is passed in a query to return the name of a suggested item (the title of a book). The SKU and book title are also used to generate a URL for the product page of the suggested book to create a link, which the customer can click for more information:

<% REM Display a list of predictive data
   predictor = NULL
   on error resume next
set predictor = Application("MSCSPredictor")
   on error goto 0

if Not IsNull(predictor) and Not IsEmpty(predictor) then
   set predictions = predictor.GetPredictions(orderItems, 6, 0.3, 2)
        if predictions.Count > 0 then
header = 0
for i = 0 to predictions.Count - 1
   cmdTemp.commandText = "select title from mspress30_product where sku = '" & predictions(i).sku & "'"
   set product = Server.CreateObject("ADODB.RecordSet")
   product.Open cmdTemp, , adOpenKeyset, adLockReadOnly
   if predictions.Count > 0 then
      if header = 0 then
         Response.Write("Other people who have bought the books you are interested in have also purchased the following titles:")
         Response.Write("<P>")
         header = 1
      end if
   %>
      <A HREF="<% = mscsPage.URL("product.asp", "sku", predictions(i).sku) %>"><% = product("title") %></A>
      <br>
   <%      end if
next
        end if
end if
   %>
<% end if %>


Predictor Example: Microsoft Press Product.asp

The Product.asp page in the Microsoft Press starter site is generated when the visitor clicks a book title in a list of titles. The page displays information about the particular book. Using the Predictor, this page also displays other books that this customer might be interested in.

Whereas the prediction in the Basket.asp page is based on the customer's shopping basket, the prediction on the Product.asp page is based primarily on the book being displayed. The assumption is that if the customer is interested in this book, he or she may have a preference for certain other books. The customer’s shopping basket may be empty at this point. However, if the shopping basket does contain items, the logic of this page also takes those items into account in generating the suggestions, and prevents any items already ordered from appearing in the list of suggestions.

The following script accomplishes this logic by building a customer interest list containing both the book currently displayed on this page as well as any items in the shopping basket, but with the Quantity property for the current book artificially set to 100. This weighting causes the Predictor to place the greatest emphasis on the current book, while still considering any books already in the basket. In this way, none of the suggestions will duplicate the contents of the basket.

Specifically, the following script creates a SimpleList object called thisitems to serve as the customer interest list. The script then adds the current book to this list, in the form of a Dictionary object that contains the SKU of the current book and the Quantity of 100.

Next, the script iterates through the customer’s order form and copies each item from the order form to the customer interest list, using the actual quantities ordered (orderitem is defined as the item list in the shopping basket by the statement set orderitem = mscsOrderForm.items, which appears in Order_bar.asp):

Finally, the generated customer interest list is passed to the Predictor’s GetPredictions method. The remainder of the page displays the list of suggestions in the same manner as the Microsoft Press Basket.asp page:

set predictor = Application("MSCSPredictor")
set interestList = Server.CreateObject("Commerce.SimpleList")

set thisitem = Server.CreateObject("Commerce.Dictionary")
thisitem.sku = CStr(sku)
thisitem.quantity = 100
interestList.add(thisitem)

for i = 0 to orderitem.Count - 1
    set thisitem = Server.CreateObject("Commerce.Dictionary")
    thisitem.quantity = orderitem(i).quantity
    thisitem.sku = orderitem(i).sku
    interestList.add(thisitem)
next

set products = predictor.GetPredictions(interestList, 3, 0.1, 2)

The parameters passed to GetPredictions are the list of current items and quantities (thisitems), the desired number of suggestions to return (3), the PopularItemFilter (the value of 0.1 indicates that GetPredictions should include popular products in the suggestion list if they are relevant), and the RequiredMatches (the value of 2 in this example ensures that the returned list will be a composite of purchases of at least two similar customers).


Other Uses of Predictor

When the Predictor object is used to suggest specific products, it uses the product SKU as the basis of its predictions. However, the Predictor is by no means limited to the concept of a SKU.

In some situations, a SKU may be too specific an identifier to use as the basis for predictions. For example, the Volcano Coffee sample store offers a dress shirt in a variety of colors and sizes. The dress shirt itself is assigned a product family id (pfID), while each combination of size and color is designated with a separate SKU comprised of the pfID and the attribute IDs. To best implement the Predictor in the Volcano Coffee application, the pfID, rather than the SKU, should be used as the basis for predictions.

The basis for prediction can extend beyond products and departments. For example, a site that sells music CDs and tapes could base predictions on recording artists. Using the Predictor, the site could correlate customer musical preferences and suggest other artists that the customer might enjoy. Another site could keep track of the URLs that a user has visited, and suggest other pages to that visitor.

You can use any type of identifier as the basis for predictions, either numbers or strings. However, you must ensure the following:

  • υThe prediction identifier must uniquely identify the product or category to be used as the basis for prediction.
  • υYour implementation of the Predictor object must use the prediction identifier consistently.
  • υAll prediction identifiers representing the same item or category must use the same case. The Predictor object is case-sensitive.

To use a prediction identifier other than the SKU, you must make sure that this identifier is logged to the site purchase history and that the prediction results are displayed in a way that is appropriate. If you are using the Microsoft Press sample site as a starting point for implementing a site using Predictor, perform the following steps to use a prediction identifier other than the SKU.

  1. Make sure that the prediction identifier exists in the order form object when the Payment stage of the Purchase pipeline configuration is executed. If the prediction identifier is not already available, write a Scriptor component to synthesize the identifier from other values and write the result into the order form object.
  2. If necessary, modify the database schema for the site purchase history table. In Microsoft Press, the site purchasing history table (mspress30_predictor_data) contains a varchar column named sku, whose width is 30 characters. Change the name and width as needed.
  3. Using the Commerce Server Pipeline Editor, open the Purchase.pcf configuration file. In the Accept stage, open the component labeled SQLItemADO (Predictor data). This component writes values into the site purchasing history table whenever purchases are made. On the property pages for this component, select the SQL Item (ADO) tab. Change the item.sku parameter to the name of the property in the order form to use as the prediction identifier.
  4. If you have changed the name of the column that specifies the prediction identifier in the site purchasing history database, then open the site’s Global.asa file for editing. Locate the call to the InitPredictor method, and change the name of the SkuColumn argument from "sku" to the new name of the column. This will initialize the Predictor object correctly based on the site purchasing history.
  5. On the page where you want to list prediction results, pass the prediction identifier instead of the SKU to the GetPredictions method. The prediction identifier is passed in a SimpleList containing Dictionary objects. The name of this property must remain sku because that name is expected by the GetPredictions method.
  6. On the same page, design the display of prediction results so that it uses the prediction identifiers that are returned by GetPredictions. For example, if you have used pfID as the prediction identifier, then design the results display to show product families. In the Dictionary object that is returned, the name of the value containing the suggested prediction identifier is sku, regardless of the type of prediction identifier that you actually used.


Predictor.GetPredictions Method

The GetPredictions method examines a list of orders (usually the customer's order form) and suggests a specified number of products in which the customer may be interested, based on the knowledge base created by the Predictor.

GetPredictions returns a list of products, sorted by Weight, in the form of a SimpleList object that contains Dictionary objects. Each Dictionary object in the returned list corresponds to one suggested item, and contains three properties. The following properties are returned for each suggested item.

Property | Description
SKU | Product SKU for suggested item.
Weight | Predicted quantity for this item, returned as a positive floating point number. Higher values of weight indicate higher predicted preference for that item.
MatchSupport | Number of merged baskets from other customers on which this suggestion is based, expressed as a floating value. Used in combination with the number of baskets evaluated (returned by the InitPredictor method), this number can be used to indicate the validity of this recommendation. In this release, all suggestions returned by a single call to GetPredictions return the same value for MatchSupport.

Syntax

Predictor.GetPredictions(Items, MaxPredictions, PopularItemFilter, RequiredMatches)

Parameters

Items
The customer interest list, usually a list of items the customer has ordered or expressed interest in. The list must be implemented as a SimpleList object that contains Dictionary objects, where each Dictionary object represents a single item and contains properties called SKU and Quantity. The GetPredictions method evaluates these items to suggest other items.
MaxPredictions
The maximum number of items to be returned by the GetPredictions method.
PopularItemFilter
A factor, expressed as a floating-point number between zero (0) and one (1), representing the degree that popular (frequently purchased) items are filtered from the suggestion list. In certain markets, some items are already so well-known (as indicated by their frequency of purchase) that they do not need to be suggested. For example, suppose that the most popular items at the Microsoft Press site were mouse pads. The store manager may prefer to suppress these items from the suggestion list. A value of one (1) indicates that popular products will be filtered, producing suggestions more specialized to the particular customer. A value of zero (0) indicates that suggestions are based solely on the purchases of similar customers. For applications where most of the users are familiar with many of the popular products, a value of about 0.9 is appropriate. To maximize sales of the most popular items, a value of zero (0) is recommended.
RequiredMatches
The minimum number of similar customers that were matched in the database in generating the suggestions. If there are fewer than RequiredMatches number of matching customers in the knowledge base, then GetPredictions will return no suggestions. Generally, a value of 4 to 6 is recommended for deployed applications where adequate data exists, to ensure higher quality suggestions. Making suggestions based on fewer than two matching customers is not advisable and may lead to issues of privacy intrusions and potentially revealing the contents of a single customer’s basket.

Example

The following example, from Microsoft Press Basket.asp, gets suggestions from the Predictor, returning the results in a SimpleList object, called products, that contains Dictionary objects:

set products = predictor.GetPredictions(orderItems, 6, 0.3, 2)

For a complete example, see Predictor Example: Microsoft Press Product.asp.

Remarks

Calling the GetPredictions method does not update the knowledge base.


Predictor.InitPredictor Method

The InitPredictor method builds a knowledge base of customer preferences by examining a database table containing the site purchase history. The method merges purchases by shopper ID, creating merged baskets that contain all purchases for each unique customer in the site’s purchase history.

The InitPredictor method returns the total number of merged baskets that it has loaded into the knowledge base. This value may be used to verify that the Predictor object has correctly processed the site purchase history. Also, when used in combination with the number of matches returned by the GetPredictions method, the value can help to determine the validity of a particular suggestion.

Syntax

Predictor.InitPredictor(DSN, Table, UserColumn, SKUColumn, QuantityColumn, MaxMemory)

Parameters

DSN
The data source name (DSN) for the table containing the site purchase history.
Table
The name of the table containing the site purchase history.
UserColumn
The name of the column that contains the shopper ID. This must be a column in Table.
SKUColumn
The name of the column that contains the SKU of the item(s) ordered. This must be a column in Table.
QuantityColumn
The name of the column that contains the quantity of items ordered. This must be a column in Table.
MaxMemory
The maximum amount of memory, in kilobytes (K), to allocate to the knowledge base. This setting must be at least 1000 (1 megabyte (MB) of memory). A recommended size is 4000 (indicating that a maximum of 4 MB of RAM could be used by the object). The object uses this limit in determining which baskets (sets of SKUs associated with a single customer) to sample for its analysis. If the MaxMemory parameter is less than the amount needed to store a complete knowledge base, priority is given to those merged baskets containing the most items. (Baskets are merged for all purchases with the same shopper ID in the site purchase history.)

Additional memory generally improves performance. Because the quality of recommendations increases significantly with the size of the sample that the Predictor object can accommodate, higher settings of this parameter are recommended. This parameter sets the limit of memory used. The Predictor object does not necessarily use all the memory specified.

The following table may be used to determine suggested memory sizes (in kilobytes). The table maps the approximate number of unique SKUs appearing in the site’s purchase history (from 100 to 100,000 SKUs) against an estimate of the number of SKUs each individual customer has purchased, based on shopper ID in the site’s purchase history (an average of either 10 or 3 SKUs per basket). The table suggests memory requirements based on average number of baskets per SKU (thickness of the data) between 20 and 50.
Unique SKUs in site purchase history | Average SKUs per customer | Suggested memory requirement (KB)
100 | 10 | 1,000
100 | 3 | 1,000
1,000 | 10 | 1,100–1,900
1,000 | 3 | 1,600–3,100
10,000 | 10 | 3,500–7,400
10,000 | 3 | 6,000–13,600
20,000 | 10 | 6,500–14,200
20,000 | 3 | 11,400–26,700
100,000 | 10 | 30,300–69,200
100,000 | 3 | 55,200–131,500

Example

The following example, from Microsoft Press Global.asa, initializes the knowledge base:

call MSCSPredictor.InitPredictor(MSCSSite.DefaultConnectionString, "mspress30_predictor_data", "shopper_id", "sku", "quantity", 2000)

You can also make use of the value returned as an additional determination of validity. The following example performs the initialization and saves the value returned (the total number of merged baskets loaded into the knowledge base):

Application("predictorBaskets") = MSCSPredictor.InitPredictor(MSCSSite.DefaultConnectionString, "mspress30_predictor_data", "shopper_id", "sku", "quantity", 2000)

Using this value, you can add a test for a reasonable number of baskets to determine whether to call the GetPredictions method:

if Not IsNull(predictor) and Not IsEmpty(predictor)  and
      Application("predictorBaskets") > 20 then
   set products = predictor.GetPredictions(orderItems, 6, 0.3, 2)
   REM display suggestions

Remarks

The knowledge base is created or updated only by calling the InitPredictor method. If the InitPredictor method is called in Global.asa, then the knowledge base will be updated only when the application is started.

The site purchase history may have any valid name, and its columns may have any valid name, because the InitPredictor method accepts arbitrary names. Furthermore, the columns may appear in any order in the table, and the table may optionally contain other columns as well.


The SimpleDBDS Object

The SimpleDBDS object enables a Commerce Server site to deploy Personalization & Membership (P&M) while using a standard database to store customer information.

SimpleDBDS is a namespace provider for the Active Directory Service Interfaces (ADSI) standard that supports database storage. P&M uses the Active User Object (AUO) to represent user information. The AUO assumes that user information is saved using Active Directory Services (ADS).

The SimpleDBDS provider maps an ADS to a database table, so that a Commerce Server site can maintain customer information using P&M while retaining the convenience of a standard database.

Once you have configured the AUO to use the SimpleDBDS ADSI provider, your site accesses the customer database using the AUO. The SimpleDBDS object enables a Commerce Server 3.0 site to use an existing customer database without modification.

Commerce Server 2.0 sites use the StandardSManager object to generate shopper IDs, and use a DBStorage object to access customer information in the database. Configured with the SimpleDBDS provider, Commerce 3.0 sites can use the AUO to generate shopper IDs and to access customer information in the database.

Two versions of SimpleDBDS are provided. One version enables reading and writing of the database, the other is read-only.

For both read-only and read/write versions, the SimpleDBDS object maps to a single row in the customer database table (representing a single customer).

The methods of the SimpleDBDS object are not usually used directly by Active Server Pages (ASP) in a Commerce Server site. Instead, the AUO is configured to use SimpleDBDS as an ADSI provider, and the AUO is used to access customer information.

The SimpleDBDS object supports the following methods.

Method | Description
Get | Reads and returns the value of a specified column in the database.
GetInfo | Reloads data from the database into the object.
Put | Sets the value of a property in the object. This value is not written back to database until and unless SetInfo is called.
PutEx | Sets the value of a property in the object or clears a property in the object. The change is not written back to database until and unless SetInfo is called.
SetInfo | Writes property values from the object to the database.


SimpleDBDS Object Overview

To create a SimpleDBDS ADSI provider object, use the GetObject function, supplying the appropriate path syntax, as follows:

Set objectname = GetObject(“SimpleDBDS://path”)

For example, the following creates a read-only ADSI provider:

Set myProduct = GetObject("SimpleDBDS://RO/DSN=cs;UID=sa;PWD=/select sku, name, dept_name from clocktower_product,  clocktower_dept where clocktower_product.dept_id = clocktower_dept.dept_id and sku = ?//Lor-842W")

The path syntax differs depending on whether the provider is configured as read-only or read/write.

When a SimpleDBDS object is created, or opened with the GetObject function, its properties are initialized from the database. You can refresh these values from the database using the GetInfo method, overwriting any changes you have made to the property values cached in the object.

You can use the Get method to retrieve the object properties, as in the following example:

Dim mySKU
mySKU = myProduct.Get("sku")

Alternately, you can retrieve the value using dot notation:

mySKU = myProduct.sku

If you have created a read/write provider, use the Put method to modify property values in the object.

myProduct.Put "sku", mySKU

Alternately, you can set values on the object using dot notation:

myProduct.sku = mySKU

The following built-in properties have specially defined values, and can be accessed only with Get and Put.

  • υName
  • υADsPath
  • υParent
  • υClass
  • υGUID
  • υSchema

Use the SetInfo method to write property values from the object to the database. When you call SetInfo, only the properties that you changed in the object are written back to the database. If you do not call SetInfo, your changes will not be written to the database.

Note

When you retrieve database properties into a SimpleDBDS object, the database is not locked while you are changing property values in the object. Other programs may make changes to values in the database after you have retrieved values and before you save them back into the database. The final values in the database will reflect the last change written. Your program should minimize the time between retrieving and saving values.

Example

The following example creates a read/write SimpleDBDS object that enables access to a customer with the specified shopper ID in the customer database table. It then reads the value of the shopper_name column for that record, and stores this value into the shopperName variable. The example also shows how a new value can be stored into the variable, saved to the object with the Put method, and written back to the database with the SetInfo method:

Dim customer, shopperName
Set customer = GetObject("SimpleDBDS://RW/DSN=cs;UID=sa;PWD=/
vc30_shopper/shopper_id//////Q0H4SE915ASH2KC000Q79QB17E500439")
' Get the value from the object
shopperName = customer.GetEx "shopper_name"
' Get updated shopper name

' Put the value back in the object
customer.Put "shopper_name", updatedShopperName
' Save the changes back to the metabase
customer.SetInfo
Note

The SimpleDBDS object’s Put, PutEx, and SetInfo methods do not support database tables containing fields of type TimeStamp. Instead, use the DateChanged argument in the Directory Services path for read/write access. This argument provides the same functionality as using TimeStamp fields (see SimpleDBDS Read/Write Path and Methods).


Inserting a New Record Using SimpleDBDS

When a SimpleDBDS object is created, or opened with the GetObject function, it queries the database. If no matching record is found, a new object containing no properties is returned.

To insert a new record, create a SimpleDBDS object that does not return an existing record, set any desired properties using the Put method, and use the SetInfo method to write the record to the database.


SimpleDBDS Read-only Path and Methods

The Directory Services path for read-only access is expressed in the format:

SimpleDBDS://RO/ConnectionString/SQL Statement/[KeyType]/[KeyValue]

where:

RO
Indicates read only.
ConnectionString
A connection string for the data source, specified as a string Variant.
SQL Statement
A SQL query. The query may contain up to one ? character. The query must use a primary key so that it returns no more than one row in the database table.
KeyType
Optional. The data type of the KeyValue. If not specified, the default is string. The / separator is not optional. Usually keys are strings or long integers, but any of the following types may be used.
KeyType specifier | Data type of KeyValue specifier
string | String (default)
long | 32-bit long integer
integer | 16-bit integer
single | Single-precision floating-point number
double | Double-precision floating-point number
currency | Currency
date | Date

KeyValue
Optional. The value for the ? in the SQL query. If the path does not include a ? in the SQL query, a Key Value should not be provided. The / separator is not optional.

Example

The following example creates a read-only ADSI provider that uses the connection string “DSN=cs; UID=sa;PWD=”, and queries the Clocktower product database using a given SKU (Lor-842W) as a query argument. The example uses the property of the ADSI provider object to display values in a page:

<%
Set CurrentNode = GetObject("SimpleDBDS://RO/DSN=cs;UID=sa;PWD=/select sku, name, dept_name from clocktower_product,  clocktower_dept where clocktower_product.dept_id = clocktower_dept.dept_id and sku = ?//Lor-842W")

Response.Write("<br>Name: ")
Response.Write(CurrentNode.Name)

Response.Write("<br>ADsPath: ")
Response.Write(CurrentNode.ADsPath)

Response.Write("<br>Parent: ")
Response.Write(CurrentNode.Parent)

Response.Write("<br>sku: ")
Response.Write(CurrentNode.Get("sku"))

Response.Write("<br>name: ")
Response.Write(CurrentNode.Get("name"))

Response.Write("<br>dept_name: ")
Response.Write(CurrentNode.Get("dept_name"))
%>

The previous script produces the following output:

Name: RO/DSN=cs;UID=sa;PWD=/select sku, name, dept_name from clockped_product, clockped_dept where clockped_product.dept_id = clockped_dept.dept_id and sku = ?//Lor-842W
ADsPath: SimpleDBDS://RO/DSN=cs;UID=sa;PWD=/select sku, name, dept_name from clockped_product, clockped_dept where clockped_product.dept_id = clockped_dept.dept_id and sku = ?//Lor-842W
Parent: SimpleDBDS:
sku: Lor-842W
name: Primrose Wall Clock
dept_name: Wall Clocks
Note

The methods of the SimpleDBDS object are not usually used directly by ASP in a Commerce Server site. Instead, the AUO is configured to use SimpleDBDS as an ADSI provider, and the AUO is used to access customer information.

The read-only SimpleDBDS supports the following ADSI properties.

Property | Description
Name | Portion of the path following “SimpleDBDS://”.
ADsPath | ADSI path.
Parent | Name of the ADSI provider, in this case SimpleDBDS.

The read-only SimpleDBDS supports the following methods.

Method | Description
GetInfo | Reloads the object with property values that exist in the metabase.
Get | Retrieves value for a named property from the object.
GetEx | Retrieves value(s) for a named single-valued or multi-valued property of the object.


SimpleDBDS Read/Write Path and Methods

The Directory Services path for read/write access is expressed in the format:

SimpleDBDS://RW/ConnectionString/Table/Key/Reserved/Marshalled Column/DateChanged/DateCreated/[KeyType]/KeyValue

where:

RW
Indicates read/write.
ConnectionString
A connection string for the data source, specified as a string Variant.
Table
The table within the data source in which to maintain the data.
Key
The column name that the DBStorage object uses as a key into the database table. This column should be marked to contain unique values.
Reserved
This parameter is reserved for future use. No value should be supplied.
MarshalColumn
Optional. A column that stores data for which no appropriate column exists in the data source table (see the following section, “Remarks”).
DateChanged
Optional. The name of a key or attribute in the database into which to write the date on which the data is changed. (If you do not specify a column name that exists in the database, the change date will be included in the marshalled data.)
DateCreated
Optional. The name of a column in the database into which to write the date on which the record is created. SimpleDBDS adds a date stamp when it creates a new entry in the database. If you do not want to store this date, do not supply this argument. The / separator is not optional.
KeyType
Optional. The data type of the KeyValue. If not specified, the default is string. The / separator is not optional. Usually keys are strings or long integers, but any of the following types may be used:
KeyType specifier | Data type of KeyValue specifier
string | String (default)
long | 32-bit long integer
integer | 16-bit integer
single | Single-precision floating-point number
double | Double-precision floating-point number
currency | Currency
date | Date

KeyValue
Optional. The value for the ? in the SQL query. If the path does not include a ? in the SQL query, a Key Value should not be provided. The / separator is not optional.

Remarks

The ConnectionString¸ Table, Key, ProgID, MarshalColumn, and DateChanged parameters are identical to the corresponding parameters to the DBStorage.InitStorage method.

The Key parameter references a column in the table referenced by Table that the DBStorage object uses to key into the data source table. It is recommended that this column be configured at table creation to store only unique values.

The MarshalColumn parameter is used to store data that does not appropriately belong in any other column in the data source table. For example, should you specify my_column as the column in which you want to store data, and no such column exists, then the value that you specify for that column will be stored in the column that you specify as MarshalColumn.

Example

The following sample specifies a read/write ADSI provider that uses the connection string “DSN=cs; UID=sa;PWS=”, and queries the Volcano Coffee shopper database, in which shopper_id is the key. By default, the KeyType is string:

SimpleDBDS://RW/DSN=cs;UID=sa;PWD=/vc30_shopper/shopper_id//////Q0H4SE915ASH2KC000Q79QB17E500439

When this path is used to create a SimpleDBDS object, the object’s GetInfo method can be called to retrieve information from the vc30_shopper table, where the value in the shopper_id column matches the specified shopper ID.

Note

The methods of the SimpleDBDS object are not usually used directly by ASP in a Commerce Server site. Instead, the AUO is configured to use SimpleDBDS as an ADSI provider, and the AUO is used to access customer information.

The read/write SimpleDBDS supports the following properties.

Property | Description
Name | Portion of the path following “SimpleDBDS://”.
ADsPath | ADSI path.
Parent | Name of the ADSI provider, in this case SimpleDBDS.

The read/write SimpleDBDS supports the following methods.

Method | Description
Get | Retrieves value for a named property from the object.
GetEx | Same function as Get.
GetInfo | Reloads the object with property values that exist in the database.
Put | Sets the value for a named property of an object.
PutEx | Sets the value for a named property of an object, or allows a property to be cleared.
SetInfo | Writes object property values to the metabase.


SimpleDBDS.Get Method

The Get method reads and returns the value of a specified column in the database.

Syntax

SimpleDBDS.Get(Column)

Parameters

Column
The name of the column in the database from which to retrieve the value.

Example

The following example assumes that a SimpleDBDS object named myProduct has been created, and that it has returned an object containing properties corresponding to the columns in the database table row. The following example stores the value of the sku column into the variable sku:

sku = myProduct.Get("sku")

Applies To

SimpleDBDS read only and read/write


SimpleDBDS.GetInfo Method

The GetInfo method reloads data from the database into the object.

When a SimpleDBDS object is created, or opened with the GetObject function, its properties are initialized from the database. You need to call the GetInfo method only to refresh these values from the database if they may have changed. GetInfo overwrites any changes you have made to the property values cached in the object.

Syntax

SimpleDBDS.GetInfo()

Parameters

None.

Applies To

SimpleDBDS read only and read/write


SimpleDBDS.Put Method

The Put method sets the value of a property in the object. This value is not written back to database until and unless SetInfo is called.

Syntax

SimpleDBDS.Put(Column, Value)

Parameters

Column
The name of the column in the database in which to store the value.
Value
The value to store in the database for the column.

Example

See SimpleDBDS Object Overview.

Applies To

SimpleDBDS read/write


SimpleDBDS.PutEx Method

The PutEx method sets the value of a property in the object or clears a property in the object. The change is not written back to database until and unless SetInfo is called. This method is similar to the Put method, except that it includes an option for clearing values.

Syntax

SimpleDBDS.PutEx(ControlCode, Column, Value)

Parameters

ControlCode
If this parameter is ADS_PROPERTY_CLEAR (1), the property specified by Column is cleared from the object. If this parameter is set to ADS_PROPERTY_UPDATE (2), the changes specified by Column and Value are applied.
Column
The name of the column in the database in which to store the value.
Value
The value to store in the database for the column.

Applies To

SimpleDBDS read/write


SimpleDBDS.SetInfo Method

The SetInfo method writes property values from the object to the database. When you call SetInfo, only the properties that you changed in the object are written back to the database. If you do not call SetInfo, your changes will not be written to the database.

Syntax

SimpleDBDS.SetInfo()

Parameters

None.

Applies To

SimpleDBDS read/write


The SimpleList Object

The SimpleList object consists of an array of Variants that supports enumeration.

The SimpleList object supports the following property.

Property | Description
Count | Read-only number that identifies the number of elements in the SimpleList object.

The SimpleList object supports the following methods.

Method | Description
Add | Adds the specified item to the list.
Delete | Deletes an item based upon a specified index value.

To create a SimpleList object, use the Active Server Pages (ASP) Server object’s CreateObject method, as follows:

Set listColors = Server.CreateObject("Commerce.SimpleList")

After creating a SimpleList object, you can use the SimpleList’s Add and Delete methods to add and remove items from the underlying list:

Call listColors.Add("Red")
Call listColors.Add("Green")
Call listColors.Add("Blue")

To retrieve elements, you can index into the list, as you would index into an array. The index is specified relative to zero (0):

Response.Write listColors(1)

Or you can use the Microsoft® Visual Basic® Scripting Edition For Each statement to iterate through the contents of the SimpleList object:

For each color in listColors
   Response.Write color & "<br>"
next

Related Topics

  • υISimpleList Interface


SimpleList.Add Method

The Add method adds an item to a SimpleList object.

Syntax

SimpleList.Add(Item)

Parameters

Item
The item to add to the SimpleList object.

Example

The following example adds the text string “Hello” to the list myList:

Call myList.Add("Hello")


SimpleList.Count Property

The Count property returns the number of elements in the SimpleList object. (Read-only)

Example

The following example displays the number of items in the my_list object:

Response.Write my_list.Count


SimpleList.Delete Method

The Delete method deletes an item, specified by Index, from the SimpleList object.

Syntax

SimpleList.Delete(Index)

Parameters

Index
The zero-relative position of the item in the SimpleList to delete.

Example

In the following example (from Clocktower’s xt_orderform_delitem.asp file), the Delete method deletes an item from the customer’s order form. The index argument is passed to the xt_orderform_delitem.asp page by the Basket.asp page when the customer clicks the Remove item button:

orderForm.Items.Delete(index)


The StandardSManager Object

The StandardSManager object supports methods that facilitate the run-time creation, deletion, and retrieval of shopper IDs.

The StandardSManager object supports the following methods.

Method | Description
CreateShopperID | Creates and returns a unique shopper ID.
GetShopperID | Retrieves the shopper ID from the cookie, if available. Otherwise, returns an empty string.
InitManager | Initializes the StandardSManager with information that determines how shopper IDs will be stored and retrieved.
PutShopperID | For backward compatibility only.


StandardSManager Overview

Use the ASP Server object’s CreateObject method to create a StandardSManager object, specifying the Commerce.StandardSManager program identifier.

In the Clocktower store Global.asa file, the StandardSManager object is instantiated by the following script:

REM -- Create a Shopper Manager to deal with managing shopperId values
Set  MSCSShopperManager = Server.CreateObject("Commerce.StandardSManager")
Call MSCSShopperManager.InitManager(SiteName, "cookie")

Also in Global.asa, store the object reference as a variable in the Application object:

Set Application("MSCSShopperManager")   = MSCSShopperManager

This Application variable must have the name MSCSShopperManager, because other Commerce Server objects expect this string.

Note

Commerce Server 3.0 sites can optionally use the Active User Object (AUO) instead of the StandardSManager object to manage shopper IDs.


StandardSManager Initialization Modes

After creating a StandardSManager object, but before calling its GetShopperID or PutShopperID method, you must initialize the StandardSManager. To do this, call the StandardSManager’s InitManager method, specifying the site name and the initialization mode. The StandardSManager’s initialization mode determines how the Page object’s GetShopperID and PutShopperID methods retrieve and store shopper IDs.

The following modes are available.

Mode | Behavior
cookie | PutShopperID stores the shopper ID in a cookie on the client system. GetShopperID retrieves this cookie.
url | PutShopperID appends the shopper ID to the URL, using the MCSSIDUrlKey as the name part of the URL variable. GetShopperID retrieves the shopper ID from the URL.
cookieurl | PutShopperID stores the shopper ID in a cookie on the client system and in the URL. GetShopperID first attempts to retrieve the shopper ID from the cookie, and then from the URL.
urlcookie | PutShopperID stores the shopper ID in a URL, and stores it as a cookie on the client system. GetShopperID first attempts to retrieve the shopper ID from the URL, then from the cookie.


StandardSManager.CreateShopperID Method

The CreateShopperID method creates and returns a new shopper ID.

Syntax

StandardSManager.CreateShopperID()

Parameters

None.

Remarks

The CreateShopperID method has no parameters, and returns the newly created shopper ID.

For information about StandardSManager modes, see StandardSManager Initialization Modes.

Related Topics

  • υStandardSManager.InitManager Method


StandardSManager.GetShopperID Method

Note

Sites that save and restore shopper IDs by means of URLs or cookies should use the GetShopperID method of the Page object instead of the GetShopperID method of StandardSManager. Sites using the AUO do not require these methods.

The GetShopperID method returns the shopper ID from a cookie stored on the client system or from a URL.

Syntax

StandardSManager.GetShopperID(Context)

Parameters

Context
This Active Server Pages (ASP) scripting context, which can be obtained by using the Page.Context property.

Remarks

If no shopper ID is stored on the client system, GetShopperID returns an empty string.

Related Topics

  • υStandardSManager.PutShopperID Method


StandardSManager.InitManager Method

The InitManager method initializes the StandardSManager object to the specified site key and mode.

Syntax

StandardSManager.InitManager(SiteKey, Mode)

Parameters

SiteKey
The name of the site.
Mode
A string that indicates how customer information is to be stored (see StandardSManager Initialization Modes).

Related Topics

  • υStandardSManager.PutShopperID Method


StandardSManager.PutShopperID Method

Note

Sites that save and restore shopper IDs by means of URLs or cookies should use the PutShopperID method of the Page object instead of the PutShopperID method of StandardSManager. Sites using the AUO do not require these methods.

The PutShopperID method stores a shopper ID in the cookie and/or a URL/SURL, depending on the mode in which the StandardSManager is running.

Syntax

StandardSManager.PutShopperID(Context, ShopperID)

Parameters

Context
This ASP scripting context, which can be obtained by using the Page.Context property.
ShopperID
The shopper ID to be stored.

Remarks

This method is included for compatibility with previous releases.


Dictionary Implementations

Commerce Server sites use implementations of the Dictionary object to store sets of data that are required by various other objects and pipeline components. The following implementations of the Dictionary object are used in typical Commerce Server sites.

Implementation of Dictionary Object | Name in site | Description | Usage
PipeContext | mscsPipeContext (user-definable) | Contains properties passed from ASP files to pipeline components. | Passed as an argument to the Execute method of MtsTxPipeline or MtsPipeline.
QueryMap | MSCSQueryMap (required) | Stores multiple query descriptions to be passed to pipeline components. | Required by order processing pipeline (OPP) components.
Site | MSCSSite (required) | Contains properties related to the Commerce Server site. These values are copied from the Commerce Server site configuration stored in the Site.csc file. | Required by Page object.


The PipeContext Dictionary

The PipeContext object is a Dictionary object that is passed through the pipeline as a holder of properties needed by pipeline components.

The PipeContext Dictionary object must contain the following values.

Value | Description
MessageManager | Reference to the MessageManager object (usually created in Global.asa).
DataFunctions | Reference to the DataFunctions object (usually created in Global.asa).
QueryMap | Reference to the QueryMap object (usually created in Global.asa). The QueryMap is a Dictionary object that contains a number of other Dictionary objects, each of which represents a query name and the SQL text of the query.
ConnectionStringMap | Reference to the Dictionary object containing connection strings that are available to the site. (This property is copied from the site dictionary.)
DefaultConnectionString | Default connection string for the site. (This property is copied from the site dictionary.)
Language | Name of a message set (defined in the MessageManager object) containing error messages to be used by the pipeline components in the event of an error.
ReceiptStorage | DBStorage object for receipts (needed only if saving receipts).
Shopper | If AUO support is installed and the site uses the AUO, this property contains an AUO representing the customer. A component in the pipeline will use the AUO to load ShopperInfo into the OrderForm.

The following example creates a PipeContext object and initializes its values prior to running an OPP (the objects referred to are defined in Global.asa):

REM Set Pipecontext:
Set mscsPipeContext = Server.CreateObject("Commerce.Dictionary")
Set mscsPipeContext("MessageManager")        = MSCSMessageManager
Set mscsPipeContext("DataFunctions")            = MSCSDataFunctions
Set mscsPipeContext("QueryMap")                = MSCSQueryMap
Set mscsPipeContext("ConnectionStringMap")    = MSCSSite.ConnectionStringMap
mscsPipeContext("DefaultConnectionString")    = MSCSSite.DefaultConnectionString
mscsPipeContext("Language")                = "usa"
Set mscsPipeContext.ReceiptStorage = MSCSReceiptStorage
Set mscsPipeContext.Shopper = MSCSShopper


The QueryMap Dictionary

The QueryMap Dictionary object saves multiple query descriptions, including the text of each query, enabling queries to be passed conveniently to OPP components.

The query map is implemented as a Dictionary object, where each name/value pair represents a single query description. Each query description in the query map is also implemented as a Dictionary object that specifies properties of the query.

The query map, named MSCSQueryMap, is created in the Application_OnStart subroutine in your site's Global.asa file.

The following values may be created and specified for each query description. Only one of these values, SQLCommand, is required in a query description; the others are optional. If any of these optional values are not specified, the pipeline component will use the default value shown in the right-hand column in the following table.

Query description value | Description
SQLCommand | SQL statement to be executed.
ConnectionTimeout | Optional. Overrides Microsoft® ActiveX® Data Object’s (ADO’s) default ConnectionTimeout property for the Connection object for this query.
CommandType | Optional. Type of Command object to create for this query. If not specified, the pipeline component will use adCmdText.
MaxRecords | Optional. Overrides ADO’s default MaxRecords property for the Recordset object used for this query.
CursorType | Optional. The value to pass to the CursorType property of the Recordset object when opening the Recordset object. If not specified, the pipeline component will use adOpenForwardOnly.
CacheSize | Optional. Overrides ADO’s default CacheSize property for the Recordset object when opening the Recordset object.

Related Topics

  • υSite.ConnectionStringMap Value


The Site Dictionary

The site dictionary is an instance of the Dictionary object that contains a copy of the Commerce Server site configuration stored in the Site.csc file. Commerce Server sites access the site configuration using the site dictionary.

The site configuration, available through the site dictionary, includes information such as the path to the site directory, the secure host, and the nonsecure host. The configuration also contains the names of lists of named connection strings and named queries used in the Commerce Server site.

In Commerce Server 3.0 sites, this Dictionary object must be named MSCSSite.

The following code, from the Clocktower Global.asa file, creates and initializes the site dictionary from the Site.csc file (for an explanation of this code, see ReadDictionaryFromFile):

REM -- Read Site Dictionary
Set FD = Server.CreateObject("Commerce.FileDocument")
Set MSCSSite = Server.CreateObject("Commerce.Dictionary")
Call FD.ReadDictionaryFromFile( Server.MapPath("/clocktower") + "/config/site.csc",
                                "Metabase", MSCSSite)
Set FD = Nothing

The site dictionary contains the following named values.

Value | Description
CloseRedirectURL | URL of a Web page to display to the customer when the Commerce Server site is closed.
ConnectionStringMap | Dictionary object containing connection strings that are available to the site.
DefaultConnectionString | Default connection string for the site.
DisableHTTPS | Integer that indicates whether to disable secure HTTP. Zero (0)=enabled; one (1)=disabled.
DisplayName | The Commerce Server site’s full name.
NonsecureHostName | Name of the nonsecure host, used by the Page.URL and Page.SURL methods to format the URL on the pages.
SecureHostName | Name of the secure host, used by the Page.URL and Page.SURL methods to format the URL on the pages.


Site.CloseRedirectURL Value

The CloseRedirectURL value specifies the URL of a Web page to display to the customer when the Commerce Server site is closed.


Site.ConnectionStringMap Value

The ConnectionStringMap value contains a Dictionary object containing connection strings that are available to the site.

The connection string map provides an abstraction for database connection strings by mapping names to connection strings. The names are called connection names. The connection string map is saved in a Commerce Server site configuration as MSCSSite.ConnectionStringMap.

The connection string map can be created when a new Commerce Server site is created, using the Commerce Server Site Foundation Wizard.

Related Topics

  • υSite.DefaultConnectionString Value


Site.DefaultConnectionString Value

The DefaultConnectionString value is a string variant containing the default connection string for the site.

Remarks

A connection string is a text string describing properties of a database connection as a series of argument = value statements separated by semicolons. The connection string usually includes all the information needed to make a connection, including user name and password.

When a Commerce Server site requires more than one connection, additional connection strings are saved in the connection string map.

Example

Invoked from ASP as:

Response.Write MSCSSite.DefaultConnectionString

Related Topics

  • υSite.ConnectionStringMap Value


Site.DisableHTTPS Value

The DisableHTTPS value is a read/write Boolean that indicates whether to disable secure HTTP. If set to one (1), security is disabled and the Page.SURL method uses HTTP, functioning the same as the Page.URL method. If set to zero (0), the Page.SURL method uses HTTPS (secure).

DisableHTTPS is set to its default value of one (1) when the site configuration is created by the Site Foundation Wizard. Security is disabled in the sample sites and in sites that you create with the Site Foundation Wizard. This is done so that you can create and test these sites without causing an error even on a server where a server certificate is not installed.

Also, because HTTP is more efficient than HTTPS, during application development it may be convenient to have the Site.DisableHTTPS property set to one (1).

This value should be set it to zero (0) before putting a site into production if the Page.SURL is used.

Usually you set this property by using one of the Commerce Server administrative tools. For example, using the Commerce Host Administration snap-in for Microsoft® Management Console (MMC), select the Web site, and then click Properties. On the properties page, click the Security tab, and then select the Enable HTTPS check box. (This is the same as setting the DisableHTTPS property to zero (0).)

Example

The following example, when invoked from ASP, enables security:

MSCSSite.DisableHTTPS = 0

Related Topics

  • υPage.URL Method
  • υPage.SURL Method


Site.DisplayName Value

The DisplayName value is a string variant containing the currently registered Commerce Server site full name. The full name is used for descriptive purposes, such as in the heading Welcome to The Clocktower Store.

Example

Invoked from ASP as:

Response.Write MSCSSite.DisplayName


Site.NonsecureHostName Value

This read/write value is a string Variant containing the name of the nonsecure host, used by the Page.URL and Page.SURL methods to format the URL on the pages.


Site.SecureHostName Value

This read/write value is a string Variant containing the name of the secure host, used by the Page.URL and Page.SURL methods to format the URL on the pages.

Related Topics

  • υPage.URL Method
  • υPage.SURL Method


Commerce Server 2.0 Objects and Methods

The following methods, properties, and objects are included only for backward compatibility with sites created in Commerce Server 2.0, and will be discontinued in future releases of Commerce Server:

  • υPage.IncrShopperPerfCtrs Method
  • υPage.Messages Property
  • υPage.RunPlan Method
  • υPage.RunProduct Method
  • υPage.RunPurchase Method
  • υThe StandardSManager Object
  • υThe Content Object
  • υThe Datasource Object
  • υThe TrafficLogFile Object
  • υThe TrafficTable Object


Page.IncrShopperPerfCtrs Method

Note

The IncrShopperPerfCtrs property is included only for backward compatibility with sites created in Commerce Server 2.0, and will be discontinued in future releases.

The IncrShopperPerfCtrs method performs no operation in Commerce Server 3.0.

Syntax

Page.IncrShopperPerfCtrs()

Parameters

None.


Page.Messages Property

Note

The Messages property is included only for backward compatibility with sites created in Commerce Server 2.0, and will be discontinued in future releases. Use the Language property of the PipeContext object to pass the desired message set to the order processing pipeline (OPP) components.

The Messages property identifies the alias of the message sets to use to return basket and purchase errors in the OrderForm. This value must identify one of the message sets added to the MessageManager through a call to that object’s AddLanguage method.


Page.RunPlan Method

Note

The RunPlan method is included only for backward compatibility with sites created in Commerce Server 2.0, and will be discontinued in future releases. Use the OrderExecute method of the OrderPipeline object instead of this method.

The RunPlan method invokes the OPP to perform preliminary processing on an OrderForm object that contains the contents of the current customer’s order form storage.

Syntax

Page.RunPlan(OrderForm)

Parameters

OrderForm
An OrderForm object that contains the contents of the order form storage for the current customer.

Remarks

The RunPlan method does not result in the purchase of the items referenced in the specified OrderForm’s items collection. Instead, RunPlan runs the OrderForm through all but the last stages of the OPP.

Usually, RunPlan is used to set nonsensitive information such as shipping and billing address data and adjusted price information in the OrderForm, and then to compute the total. If the OPP encounters errors, it stores these errors in the OrderForm’s _Basket_Errors_ collection.

After RunPlan has been run on an OrderForm, and the customer has confirmed the purchase, the site calls RunPurchase on the modified OrderForm to write the OrderForm’s contents to receipt storage.

Related Topics

  • υPage.RunProduct Method
  • υPage.RunPurchase Method


Page.RunProduct Method

Note

The RunProduct method is included only for backward compatibility with sites created in Commerce Server 2.0, and will be discontinued in future releases. Use the OrderExecute method of the OrderPipeline object instead of this method.

The RunProduct method runs an OrderForm through the Product Information, Merchant Information, Shopper Information, and Item Adjust Price stages of the OPP. The Item Adjust Price stage writes the adjusted price for a given item to the OrderForm item’s _iadjust_currentprice member. By comparing the value of this member with the item’s list_price member, you can determine whether an item is on sale.

Syntax

Page.RunProduct(OrderForm)

Parameters

OrderForm
An OrderForm object initialized with the items on which to check the current price.

Related Topics

  • υPage.RunPlan Method
  • υPage.RunPurchase Method


Page.RunPurchase Method

Note

The RunPurchase method is included only for backward compatibility with sites created in Commerce Server 2.0, and will be discontinued in future releases. Use the OrderExecute method of the OrderPipeline object instead of this method.

The RunPurchase method runs the OPP on an OrderForm object that contains the contents of order form storage for the current customer.

Syntax

Page.RunPurchase(OrderForm)

Parameters

OrderForm
An OrderForm object that contains the contents of order form storage for the current customer.

Remarks

RunPurchase runs the entire OPP on the OrderForm. If no errors are encountered in the OrderForm, the OPP writes the OrderForm’s contents to receipt storage.

Related Topics

  • υDBStorage Object Overview


The Content Object

Note

The Content object is included in Commerce Server 3.0 only for backward compatibility with sites created in Commerce Server 2.0. New sites should be constructed using Microsoft® ActiveX® Data Objects (ADO). Connection strings (not data source names (DSNs)) should be stored in the ConnectionStringMap (part of the site dictionary) and queries should be stored in the QueryMap Dictionary object.

The Content object provides a way for Commerce Server 2.0 sites to create and maintain a group of variables that identify the queries and DSNs needed to interact with a site’s inventory. You can use Content object methods to associate string variables with configured system and file DSNs, to associate SQL query strings with Application-wide variables, and to create the Datasource objects through which these queries are executed.

The Content object supports the following methods.

Method | Description
AddDatasource | Associates a string variable with a configured system or file DSN and stores this variable in the Content object cache.
AddQuery | Associates a string variable with an SQL statement, and stores this variable in the Content object cache.
Datasource | Returns a Datasource object based on the variable name associated with a DSN variable. The Datasource method is the default method for the Content object.


Content Object Overview

Note

The Content object is included in Commerce Server 3.0 only for backward compatibility with sites created in Commerce Server 2.0. New sites should be constructed using ADO. Connection strings (not DSNs) should be stored in the ConnectionStringMap (part of the site dictionary) and queries should be stored in the QueryMap Dictionary object.

The Content object consists of a collection of variables that identify the DSNs and queries that a Commerce Server 2.0 site uses to read subsets of site inventory into site pages. It implements methods that make it possible to add query variables to the object, and that support the creation of the Datasource object, which you use to execute queries associated with Content cache elements.

Note

In Commerce Server 3.0 and later, mapping of names to data sources is accomplished by the Site object. Connection to data sources is accomplished with ADO’s Command and Connection objects.

Creating the Content Object

Because the pages in your site need to access a central collection of queries and DSNs, you should create the Content object to have Application scope. This means that this object must be created in the Application_OnStart event, which you define in your \Shop directory’s Global.asa file, and you must initialize the Application object’s MSCSContent variable to reference this object.

Additionally, if your site uses more than one DSN, identify one of the Datasource objects that you create as the site’s default data source. To do this, initialize the Application object’s MSCSDefaultDatasource variable to reference the string variable name of the data source. The following example, which contains a subset of the statements that appear in the Clocktower’s Global.asa file, illustrates this initialization:

<SCRIPT LANGUAGE=VBScript RUNAT=Server>
Sub Application_OnStart

REM -- Create a content object and datasource for connection to the database

Set  MSCSContent = Server.CreateObject("Commerce.Content")
Call MSCSContent.AddDatasource("Clocktower", MSCSDSN)

REM -- Set up the Application instrinsic object

Application.Lock

Set Application("MSCSContent")          = MSCSContent
Application("MSCSDefaultDatasource") = "Clocktower"

Application.Unlock
End Sub

</SCRIPT>

The Datasource object, unlike the Content object, is created on a per-page basis. For example, in the Clocktower site, the Shop.asp file is included in every file that needs to retrieve a data source from the Content object, and includes the following example:

Set MSCSDatasource = Application("MSCSContent")("Clocktower")

When you need to connect to a database using one of the DSN variables you have added, or need to execute one of the added queries, you use the Content object to create a Datasource object based on the name of a given DSN. A Datasource object has access to all the queries stored in the Content object through which it was created. Additionally, the Datasource object can return query results to the caller either as a SimpleList object containing Dictionary objects, or as an ADO Recordset.

Using the Content Object

Use of the Content object begins with the creation of a DSN variable, a string variable that you associate with a DSN that you have created using the Microsoft® Open Database Connectivity (ODBC)32 Control Panel utility. The Content object’s AddDatasource method adds a DSN variable to the Content object. Because the Content object will contain all the DSNs and queries used by the site to retrieve site content, this object should have Application scope. This means that it should be created in the Application_OnStart subroutine in the site’s Global.asa file:

REM -- Create a content object and datasource for connection to the database

Set  MSCSContent = Server.CreateObject("Commerce.Content")
Call MSCSContent.AddDatasource("Clocktower", MSCSDSN)

This example call to AddDatasource assigns the string name Clocktower to the data source identified by MSCSDSN. MSCSDSN is a string variable that contains the database connection string necessary to access the database, and is defined in The Clocktower’s Dsn_include.asp file as follows:

MSCSDSN = "DSN=Stores;UID=sa;PWD=;APP=;DATABASE=Commerce"

In this string, Stores identifies the DSN that you assigned to this data source when you configured it using the ODBC32 Control Panel utility, and Commerce identifies a Microsoft® SQL Server™ database that you specified when you created the DSN. The preceding string is a sample database connection string, and that the actual string varies from one data source to another.

After adding a DSN variable, Clocktower in this example, to the Content object, you use the AddQuery method to add your site’s queries to the object:

REM -- Add queries to the content object for use in our pages

Call MSCSContent.AddQuery("departments", "select * from Clocktower_dept")

Call MSCSContent.AddQuery("products-by-dept", "select sku, name,
dept_id, manufacturer, list_price, image_file, image_width,
image_height, description from Clocktower_product where dept_id =
convert(numeric,:1)")

Call MSCSContent.AddQuery("department", "select * from Clocktower_dept
where dept_id = convert(numeric,:1)")

Call MSCSContent.AddQuery("product", "select sku, name, dept_id,
manufacturer, list_price, image_file, image_width, image_height,
description from Clocktower_product where sku = :1")

The first parameter to AddQuery identifies the name by which you will reference this query when you execute it, and the second parameter contains the query’s SQL text. The values that follow the text of the query consist of parameters that you can use to enhance the speed and efficiency with which queries are executed.

For information about these parameters, see Content.AddQuery Method.

To execute one of the queries added, you need to use the Content object’s Datasource method to create a Datasource object, and then call its Execute method, referencing the string name that you have associated with the query. Here is an example of such a call:

Set  MSCSDataSource = MSCSContent.Datasource("Clocktower")

After you have created a Datasource object, it has access to all the queries in the Content object cache. Consequently, you use the Datasource object’s Execute method to execute a query stored in the Content cache without directly referencing the Content object through which the Datasource object was originally created. For example, the following call, which appears in the Clocktower’s Default.asp file, calls the Execute method on the departments query that was added to the Content object earlier in this section, and iterates through the SimpleList object containing the query’s results to display the Clocktower’s departments on the page:

<UL>
    <% set depts = MSCSDataSource.Execute("departments") %>
    <% for each dept in depts %>
        <LI><A HREF="<% = mscsPage.URL("dept.asp", "dept_id",
dept.dept_id) %>"><% = mscsPage.Encode(dept.dept_name) %></A>
    <% next %>
</UL>


Content.AddDatasource Method

Note

The Content object is included in Commerce Server 3.0 only for backward compatibility with sites created in Commerce Server 2.0. New sites should be constructed using ADOs. Connection strings (DSNs) should be stored in the ConnectionStringMap (part of the site dictionary) and queries should be stored in the QueryMap Dictionary object.

The AddDatasource method associates a configured file or system DSN with a string alias.

Syntax

Content.AddDatasource(Alias, ConnectionString)

Parameters

Alias
A string that identifies the name by which you will reference the DSN in your site.
ConnectionString
A database connection string that contains connection and login information. Usually the database connection string is defined in the Dsn_include.asp file, which is included at the start of Global.asa.

Remarks

If you use more than one DSN in a site, you should specify one of them as the default DSN for the site. To do this, set the Application object’s MSCSDefaultDatasource variable to reference the string variable name that you have associated with a DSN that you have added to the Content object query collection.

Example

The following example, from the Clocktower sample site, creates a Content object, adds a DSN variable to the object, and makes that DSN the default DSN for the site:

REM Create a Content object for access to the database
Set  MSCSContent = Server.CreateObject("Commerce.Content")
Call MSCSContent.AddDatasource("Clocktower", MSCSDSN)
Set  MSCSDataSource = MSCSContent.Datasource("Clocktower")

' Later, in Application_OnStart
Application("MSCSDefaultDatasource") = "Clocktower"

Related Topics

  • υContent.AddQuery Method


Content.AddQuery Method

Note

The Content object is included in Commerce Server 3.0 only for backward compatibility with sites created in Commerce Server 2.0. New sites should be constructed using ADOs. Connection strings (not DSNs) should be stored in the ConnectionStringMap (part of the site dictionary) and queries should be stored in the QueryMap Dictionary object.

The AddQuery method adds a query variable to the Content object.

Syntax

Content.AddQuery(QueryName, QueryText, Timeout, CommandType, MaximumRows, CursorType, CursorSize, RetrievalMethod)

Parameters

QueryName
A string variable that identifies the query. This name must be a non-Null string, but can contain spaces, numbers, and other non-Null characters.
QueryText
The SQL text of the query.
Timeout
Optional. A number that specifies the period of time, in seconds, to wait for the database to respond after an operation has been executed. A value of zero (0) indicates that the defaults for the database driver should be used. This value should be increased for database operations that are slow, or during operations that are known to take more time than is allowed by the default.
CommandType
Optional. An integer constant that specifies the kind of command that QueryText represents. Specifying the precise type of the command (as opposed to adCmdUnknown), results in faster execution time. The following table lists the possible constant values.
Constant | Value | Description
adCmdText | 1 | Evaluates QueryText as a textual definition of a command.
AdCmdTable | 2 | Evaluates QueryText as a table name.
AdCmdStoredProc | 4 | Evaluates QueryText as a stored procedure.
AdCmdUnknown | 8 | Type of command for the QueryText value is not known. This is the default value.

MaximumRows
Optional. The maximum number of rows to return. The default value is zero (0). Specifying a value greater than zero for queries that always return a small number of rows can substantially reduce the speed of query execution.
CursorType
Optional. An integer constant that references the ADO cursor type. The CursorType is used most often in conjunction with the CursorSize parameter. This parameter can contain one of the following values.
Constant | Value | Description
adOpenForwardReadOnly | 0 | Forward-only cursor. Identical to a static cursor except that you can only scroll forward through records. This improves performance in situations when you only need to make a single pass through a Recordset. (Default.)
adOpenKeyset | 1 | Keyset cursor. Like a dynamic cursor, except that you cannot view records that other users add, although records that other users delete are inaccessible from your Recordset. Data changes by other users are still visible.
adOpenDynamic | 2 | Dynamic cursor. Additions, changes, and deletions by other users are visible, and all types of movement through the Recordset are allowed, except for bookmarks if the provider does not support them.
adOpenStatic | 3 | Static cursor. A static copy of a set of records that you can use to find data or generate reports. Additions, changes, or deletions by other users are not visible.

CursorSize
Optional. A number that specifies the number of rows to gather at one time. Specifying a value of one (1) optimizes the server-side cursor by ensuring that the server never has to retrieve more than a single row in server memory at a time. The default value is zero (0).
RetrievalMethod
Optional. A number that specifies the method to use to retrieve data from the results set. The default value is 2 (unknown). If you are using an Oracle database, the block retrieval method is unavailable; you must use the row retrieval option.

The following values can be used for this parameter.
Value | Description
0 | Block retrieval. Indicates that the result set contains no long text or binary data, or that the database fully supports block retrieval of long data.
1 | Row retrieval. Indicates that the database supports the retrieval of long data, but only on a row-by-row basis.
2 | Unknown. When you use this value, you effectively ask the system to determine for itself which method to call by searching for columns that contain binary data.

Remarks

When you execute a query using the Datasource object’s Execute method, you can simply pass Execute the name you have associated with the query through a call to AddQuery.

Although you can also pass the Execute method the SQL text of a query that you have not added to the Content object, this results in a degradation in performance time. For optimal efficiency, you should always pass Execute query variables stored by AddQuery in the Content object’s query list.

Additionally, if you pass Execute the text of your query, the Datasource object internally uses a set of default values for the Timeout, CommandType, MaximumRows, CursorType, and CursorSize values described previously, and you cannot override these defaults.

Related Topics

  • υContent.AddDatasource Method


Content.Datasource Method

Note

The Content object is included in Commerce Server 3.0 only for backward compatibility with sites created in Commerce Server 2.0. New sites should be constructed using ADOs. Connection strings (not DSNs) should be stored in the ConnectionStringMap (part of the site dictionary) and queries should be stored in the QueryMap Dictionary object.

The Datasource method returns a Datasource object for the specified DSN variable. The DSN parameter references a DSN variable added to the Content object cache through a previous call to AddDatasource.

Syntax

Content.Datasource(DSN)

Parameters

DSN
A string that identifies the variable name associated with a DSN through a previous call to AddDatasource.

Example

The following example, from the Clocktower sample site, creates a Content object, adds a DSN variable to the object, and then uses the Datasource method to create a Datasource object instance for that DSN:

REM -- Create a content object and datasource for connection to the database
Set  MSCSContent = Server.CreateObject( "Commerce.Content" )
Call MSCSContent.AddDatasource("Clocktower", MSCSDSN)
Set  MSCSDatasource = MSCSContent.Datasource("Clocktower")

You can also use the variable name of the Content object to retrieve a Datasource object, as follows:

Set MSCSDatasource = MSCSContent("Clocktower")


The Datasource Object

Note

The Datasource object is included in Commerce Server 3.0 only for backward compatibility with sites created in Commerce Server 2.0. New sites should be constructed using Microsoft® ActiveX® Data Objects (ADO).

The Datasource object executes queries against a system or file data source name (DSN), and where appropriate, returns query results in a SimpleList object containing Dictionary objects, or in an ADO Recordset object. The queries that you execute can be SQL statements declared as string variables in the page in which you execute the query, or query variables cached in a Content object.

You do not use the Active Server Pages (ASP) Server object’s CreateObject method to create a Datasource object. Instead, you use the Content object’s Datasource method, which creates the object based on the DSN variable that is cached by the Content Object. Once you have created a Datasource object, the Datasource has access to the Content object’s cache of queries.

The Datasource object supports the following methods.

Method | Description
CreateADOConnection | Returns a read-only Connection object. You can pass this object as a parameter to ExecuteADO.
Execute | Executes the specified query against a data source, and where appropriate, returns the results in a SimpleList object containing Dictionary objects.
ExecuteADO | Executes the specified query on an open ADO Connection, and where appropriate, returns the results in an ADO Recordset object.


Datasource Object Overview

Note

The Datasource object is included in Commerce Server 3.0 only for backward compatibility with sites created in Commerce Server 2.0. New sites should be constructed using ADOs.

Although you can use the Datasource object to perform any operation that you need to perform on your site database, Commerce Server sites generally use this object in two contexts:

  • υTo execute queries that retrieve product information for display on a page.
  • υTo retrieve product information for storage in an OrderForm.


Datasource.CreateADOConnection Method

Note

The Datasource object is included in Commerce Server 3.0 only for backward compatibility with sites created in Commerce Server 2.0. New sites should be constructed using ADOs.

The CreateADOConnection method returns a Connection object that represents an open, read-only connection. If you want results sets to be returned in the ADO Recordset object (as opposed to being returned as a SimpleList object containing Dictionary objects), use the ExecuteADO method.

Syntax

Datasource.CreateADOConnection()

Parameters

None.

Related Topics

  • υDatasource.ExecuteADO Method


Datasource.Execute Method

Note

The Datasource object is included in Commerce Server 3.0 only for backward compatibility with sites created in Commerce Server 2.0. New sites should be constructed using ADOs.

The Execute method executes the specified query and returns the results of the query, if any, in a SimpleList object containing Dictionary objects.

Syntax

Datasource.Execute(SQL, Parameters)

Parameters

SQL
The string resource identifier of a query added to a Content object through a previous call to AddQuery, or the SQL text of the query.
Parameters
Optional. One or more parameters to bind to the parameter markers in SQL.

Remarks

You can pass the Execute method the text of a query, but this technique does not take advantage of the speed optimizations built into the Content object, and is not advised. If the SQL parameter to Execute is the text of a query, default values are used for the query’s timeout, command type, maximum rows fetched, cursor type, and cursor size. The default value for each of these arguments is listed under AddQuery.

Related Topics

  • υContent.AddQuery Method


Datasource.ExecuteADO Method

Note

The Datasource object is included in Commerce Server 3.0 solely for backward compatibility with sites created in Commerce Server 2.0. New sites should be constructed using ADOs.

The ExecuteADO method executes the specified query on an open ADO connection and returns the results of the query, if any, in an ADO Recordset object.

Syntax

Datasource.ExecuteADO(Connection, SQL, Parameters)

Parameters

Connection
An open ADO connection. The caller creates this connection by using the ASP Server object’s CreateObject method, specifying ADO.Connection as the programmatic identifier, and then by using the Connection’s Open method to open a DSN.
SQL
The string resource identifier of a query added to a Content object through a previous call to AddQuery, or the SQL text of the query.
Parameters
One or more parameters to bind to the parameter markers in SQL.

Related Topics

  • υDatasource.Execute Method


The OrderPipeline Object

Note

The OrderPipleline object is included in Commerce Server 3.0 only for backward compatibility with sites created in Commerce Server 2.0. New sites should be constructed using MtsTxPipeline or MtsPipeline.

The OrderPipeline object creates and executes an order processing pipeline (OPP). The OrderPipeline pipeline is not registered under Microsoft® Transaction Server (MTS).

Commerce Server 3.0 provides three similar objects that execute pipeline configurations. These objects differ in the way they are registered with MTS (see MtsTxPipeline and MtsPipeline Overview).

The OrderPipeline object supports the following methods.

Method | Description
LoadPipe | Loads a pipeline configuration (.pcf) file.
OrderExecute | Runs the stages in the pipeline.
SetLogFile | Identifies the file to which pipeline events are logged.

Related Topics

  • υIOrderPipeline Interface


OrderPipeline.LoadPipe Method

The LoadPipe method loads a pipeline configuration (.pcf) file into the pipeline.

The LoadPipe method must be called to initialize every pipeline.

Syntax

OrderPipeline.LoadPipe(Path)

Parameters

Path
The path and file name of the configuration file.

Related Topics

  • υOrderPipeline.OrderExecute Method
  • υOrderPipeline.SetLogFile Method


OrderPipeline.OrderExecute Method

The OrderExecute method runs the specified set of stages in the pipeline, applying their actions to the specified order form. Before invoking OrderExecute, you must load the pipeline configuration using the LoadPipe method.

OrderExecute returns a Long result containing one of the following values:

  • υThe number 1 indicates the pipeline executed successfully.
  • υThe number 2 indicates errors raised by pipeline components in the basket or purchase error collections. These are typically customer errors, such as a mis-typed credit card number. An error message is displayed to the customers so that they can submit the information again.
  • υThe number 3 indicates failure of the pipeline, such as the inability to access the database. This type of error cannot be corrected by the customer.

Syntax

OrderPipeline.OrderExecute(Mode, OrderForm, PipeContext, Reserved)

Parameters

Mode
Specifies the mode in which to execute the stages in the pipeline. This parameter may be set to one of the following:
1    Runs the product verification stages.
2    Runs all stages except payment and accept.
4    Runs the complete pipeline.

The values for Mode may be defined as constants in Global.asa:

Application("OPPMODE_PRODUCT")  = 1
Application("OPPMODE_PLAN")     = 2
Application("OPPMODE_PURCHASE") = 4
Note

The Mode parameter is included only for backward compatibility with sites created in Commerce Server 2.0, and will be discontinued in future releases. In Commerce Server 3.0 and later, the selection of pipeline stages is made by loading an appropriate pipeline configuration file with the LoadPipe method. Commerce Server 3.0 applications should use the value one (1) for this parameter; zero (0) will cause no stages to run.

OrderForm
An initialized OrderForm.
PipeContext
A PipeContext object. The PipeContext object is a Dictionary object that references a group of initialized objects containing information needed by the pipeline.
Reserved
This value is not used and must be set to zero (0).

Remarks

The OrderExecute method should be used instead of the RunProduct, RunPlan, and RunPurchase methods on the Page object, as used in Commerce Server 2.0.

Related Topics

  • υOrderPipeline.LoadPipe Method
  • υThe PipeContext Dictionary


OrderPipeline.SetLogFile Method

The SetLogFile method identifies the file to which the pipeline logs operations that occur when the pipeline is run.

Note

This method is intended for use by developers who want to analyze the operations of a pipeline configuration. Logging should never be enabled in a production environment, both because it degrades performance and because it can compromise the security of credit card numbers in non-set transactions.

Syntax

OrderPipeline.SetLogFile(Filename)

Parameters

Filename
The name of the file to which to pipeline events. When set to an empty string (""), logging is disabled.

Related Topics

  • υOrderPipeline.OrderExecute Method


The TrafficLogFile Object

Note

The TrafficLogFile object is included in Commerce Server 3.0 only for backward compatibility with sites created in Commerce Server 2.0. New sites should measure traffic with Site Server Analysis.

The TrafficLogFile object provides Commerce Server sites with the ability to log user information and site events to a plain text file. A site manager can then analyze traffic information by loading the log file into an application such as Microsoft® Excel.

The TrafficLogFile object provides the same functionality as the TrafficTable object, except that the latter logs information to a table in the database rather than to a file.

The TrafficLogFile object supports the following properties.

Property | Description
LocaleDate | Specifies the locale to use to format dates in the log file. The default is American (&H0409).
LocaleTime | Specifies the locale to use to format time in the log file. The default is American (&H0409).
ColumnDelimiter | Specifies the ASCII character (or string of characters) to use to separate columns in the log file. The default is a blank space.
ColumnSubstitution | Specifies the character(s) to be used as the column delimiter if the data itself contains the character(s) previously specified as the ColumnDelimiter. The default is a blank space.
RowDelimiter | Specifies the character(s) to use to delimit rows. The default is a newline.
RowSubstitution | Specifies the character to be used as the row delimiter if the data itself contains the character(s) previously specified as the RowDelimiter. The default is a blank space.
BlankSubstitution | Specifies the character to substitute for blank spaces. The default is nothing; that is, blank spaces will be removed.

The TrafficLogFile object supports the following methods.

Method | Description
InitTraffic | Initializes the TrafficLogFile object by specifying the file name to which to log traffic data and the items to log.
LogTraffic | Logs traffic data to a file.


TrafficLogFile Object Overview

Note

The TrafficLogFile object is included in Commerce Server 3.0 only for backward compatibility with sites created in Commerce Server 2.0. New sites should record and measure traffic with Site Server Analysis.

To create a TrafficLogFile object, use the Server.CreateObject method, specifying Commerce.TrafficLogFile as the object’s programmatic identifier:

Set MSCSTraffic = Server.CreateObject("Commerce.TrafficLogfile")
Set Application("MSCSTraffic") = MSCSTraffic

If you create a TrafficLogfile object in your site’s Global.asa file, you should initialize the Application object’s MSCSTraffic variable to reference the object instance.

After creating the object, and before calling its LogTraffic method, use the InitTraffic method to initialize the object.


TrafficLogFile.InitTraffic Method

Note

The TrafficLogFile object is included in Commerce Server 3.0 only for backward compatibility with sites created in Commerce Server 2.0. New sites should measure traffic with Site Server Analysis.

The InitTraffic method initializes the TrafficLogfile object by identifying the kinds of information to log and the location of the log file.

Syntax

TrafficLogfile.InitTraffic(SiteName, FileName, Arguments)

Parameters

SiteName
An arbitrary string that will be included with each log, usually used to identify the site in the log. This string will be logged only if the store_name keyword is included in the Arguments list. (If you do not want to log this string, specify a string with a single blank.)
FileName
The local path to the file where events and data will be logged.
Arguments
Optional. A list of keywords that identify the information you want to log.

The following table lists the keywords that might be listed when calling the InitTraffic method, along with the type of information each keyword causes to be logged.
Keyword | Information to be logged
store_name | Enables the LogTraffic method to log the text that was provided to InitTraffic as its SiteName argument. Usually this string contains the name of the site.
shopper_id | Enables the LogTraffic method to log the unique identifier of the current shopper, which is provided as its ShopperID argument.
event | Enables the LogTraffic method to log the number provided as its Event argument. This arbitrary number is usually used to identify the type of event being logged.
item_requested | Enables the LogTraffic method to log the string provided as its ItemRequested argument. This arbitrary string is usually used to identify the URL of the page being requested.
event_time | Enables the LogTraffic method to include the current time in the log record.
args_argname | Enables the LogTraffic method to log the value of a specified URL query string passed to the page in the URL (either from a FORM or a generated URL). argname must match the name of the variable in a query string. For example, if the keyword args_product is listed, then LogTraffic will look for a query string in the URL beginning "?product=" and will include the value specified in the log.
remote_addr | Enables the LogTraffic method to log the IP address of the client computer.
remote_host | Enables the LogTraffic method to log the host name of the client computer (in some cases, this value may be an IP address).
http_argname | Enables the LogTraffic method to log environment variables, such as REFERER and USER_AGENT (for example, http_REFERER). In names containing hyphens, an underscore is used instead of a hyphen because database column names cannot contain hyphens.

Example

The following example creates and initializes a database traffic server to log the site name (Clocktower) and shopper ID to the specified file:

Set  MSCSTraffic = Server.CreateObject("Commerce.TrafficLogfile")
call MSCSTraffic.InitTraffic("Clocktower", "c:\\Clocktower_traffic.log", "store_name", "shopper_id")


TrafficLogFile.LogTraffic Method

Note

The TrafficLogFile object is included in Commerce Server 3.0 only for backward compatibility with sites created in Commerce Server 2.0. New sites should log and measure traffic with Site Server Analysis.

The LogTraffic method logs event or customer information to the log file for this TrafficLogfile object. You can call this method at any time to log events as they occur, and optionally, distinguish between different types of events by using the Event argument.

Syntax

TrafficLogfile.LogTraffic(ShopperID, Event, ItemRequested, Context)

Parameters

ShopperID
The shopper ID of the customer who loaded the page that triggered the event. This value will be logged only if the shopper_id keyword was included in the Arguments list when the InitTraffic method was called.
Event
This arbitrary integer is usually used to identify the event being logged. For example, the number ‘107’ might be assigned to indicate that a customer has placed an item in the basket, ‘108’ might indicate that a customer has responded to a particular cross-promotion, and so on. This number will be logged only if the event keyword was included in the Arguments list when the InitTraffic method was called.
ItemRequested
An arbitrary string usually used to identify the URL of the page being requested. This string will be logged only if the item_requested keyword was included in the Arguments list when the InitTraffic method was called.
Context
The Page object’s Context property. This read-only property is initialized when the Page object is created, and references the Active Server Pages (ASP) scripting context.


The TrafficTable Object

Note

The TrafficTable object is included in Commerce Server 3.0 only for backward compatibility with sites created in Commerce Server 2.0. New sites should measure traffic with Site Server Analysis.

The TrafficTable object provides Commerce Server sites with the ability to log user information and site events to a database table. A site manager could then analyze traffic information by querying the table with an application such as Microsoft® SQL Server™.

The TrafficTable object provides the same functionality as the TrafficLogFile object, except that the latter logs information to a file rather than to a table in the database.

The TrafficTable object supports the following methods.

Method | Description
InitTraffic | Initializes the TrafficTable object with the data source to which to log traffic data, and (where applicable) a site key.
LogTraffic | Logs traffic data to a data source.


TrafficTable Object Overview

Note

The TrafficTable object is included in Commerce Server 3.0 only for backward compatibility with sites created in Commerce Server 2.0. New sites should record and measure traffic with Site Server Analysis.

To create a TrafficTable object, use the Server.CreateObject method, specifying Commerce.TrafficTable as the object’s programmatic identifier:

Set MSCSTraffic = Server.CreateObject("Commerce.TrafficTable")
Set Application("MSCSTraffic") = MSCSTraffic

After creating the object, and before calling its LogTraffic method, use the InitTraffic method to initialize the object, specifying the table to which you want to log.


TrafficTable.InitTraffic Method

Note

The TrafficTable object is included in Commerce Server 3.0 only for backward compatibility with sites created in Commerce Server 2.0. New sites should measure traffic with Site Server Analysis.

The InitTraffic method initializes the TrafficTable object. InitTraffic determines what information is to be logged by examining the column names in the destination database table. The following table lists the column names that may appear in the table, along with the information that will be stored into that column by the LogTraffic method.

Column name | Information to be logged
store_name | Text that was provided to InitTraffic as its SiteName argument. Usually this string contains the name of the site.
shopper_id | Unique identifier of the current shopper, which is provided as the ShopperID argument to the LogTraffic method.
event | Number provided as the Event argument to the LogTraffic method. This arbitrary number is usually used to identify the type of event being logged.
item_requested | String provided as the ItemRequested argument to the LogTraffic method. This arbitrary string is usually used to identify the URL of the page being requested.
event_time | Current time.
args_argname | Value of a specified URL query string passed to the page in the URL (either from a FORM or a generated URL). argname must match the name of the variable in a query string. For example, if the keyword args_product is listed, then LogTraffic will look for a query string in the URL beginning "?product=" and will include the value specified in the log.
remote_addr | IP address of the client computer.
remote_host | Host name of the client computer (in some cases, this value may be an IP address).
http_argname | Environment variables, such as REFER and USER_AGENT (for example, http_REFER). In names containing hyphens, an underscore is used instead of a hyphen because database column names cannot contain hyphens.

Syntax

Traffic.InitManager(Datasource, SiteName, TableName)

Parameters

Datasource
A variable that identifies the Datasource object for the table to which you want to log.
SiteName
An arbitrary string that will identify the site in the log.
TableName
The name of the table in the referenced data source.

Example

REM -- Create and initialize database traffic server
Set  MSCSTraffic = Server.CreateObject("Commerce.TrafficTable")
call MSCSTraffic.InitTraffic(MSCSDataSource, "Clocktower", "Clocktower_traffic")

Related Topics

  • υTrafficTable.LogTraffic Method


TrafficTable.LogTraffic Method

Note

The TrafficTable object is included in Commerce Server 3.0 only for backward compatibility with sites created in Commerce Server 2.0. New sites should measure traffic with Site Server Analysis.

The LogTraffic method logs event information to a database table.

Syntax

Traffic.LogTraffic(ShopperID, Event, ItemRequested, Context)

Parameters

ShopperID
The shopper ID to log in the record, usually the ID of the customer who loaded the page that triggered the event.
Event
This arbitrary integer is usually used to identify the event being logged. For example, the number ‘107’ might be assigned to indicate that a customer has placed an item in the basket, ‘108’ might indicate that a customer has responded to a particular cross-promotion, and so on. This number will be logged only if one of the columns in the destination table is named event.
ItemRequested
An arbitrary string usually used to identify the URL of the page being requested. This string will be logged only if one of the columns in the destination table is named item_requested.
Context
The Page object’s Context property.

Related Topics

  • υTrafficTable.InitTraffic Method


Hexadecimal Locale Identifiers

Many of the methods implemented in the Commerce Server objects take locale identifiers as optional parameters. These identifiers are represented by unique hexadecimal codes, which are listed in the following table.

The list of locale and language identifiers can be found in the National Language Support API. This specification can be found on the Microsoft® Developer Network (MSDN) compact disc (Platform SDK, Windows Base Services, International Features).

This list is continually growing and further locale support may be added to any future product.

Identifier | Locale
0x0000 | Language Neutral
0x0400 | Process Default Language
0x0401 | Arabic (Saudi Arabia)
0x0801 | Arabic (Iraq)
0x0c01 | Arabic (Egypt)
0x1001 | Arabic (Libya)
0x1401 | Arabic (Algeria)
0x1801 | Arabic (Morocco)
0x1c01 | Arabic (Tunisia)
0x2001 | Arabic (Oman)
0x2401 | Arabic (Yemen)
0x2801 | Arabic (Syria)
0x2c01 | Arabic (Jordan)
0x3001 | Arabic (Lebanon)
0x3401 | Arabic (Kuwait)
0x3801 | Arabic (U.A.E.)
0x3c01 | Arabic (Bahrain)
0x4001 | Arabic (Qatar)
0x0402 | Bulgarian
0x0403 | Catalan
0x0404 | Chinese (Taiwan)
0x0804 | Chinese (PRC)
0x0c04 | Chinese (Hong Kong)
0x1004 | Chinese (Singapore)
0x0405 | Czech
0x0406 | Danish
0x0407 | German (Standard)
0x0807 | German (Swiss)
0x0c07 | German (Austrian)
0x1007 | German (Luxembourg)
0x1407 | German (Liechtenstein)
0x0408 | Greek
0x0409 | English (United States)
0x0809 | English (United Kingdom)
0x0c09 | English (Australian)
0x1009 | English (Canadian)
0x1409 | English (New Zealand)
0x1809 | English (Ireland)
0x1c09 | English (South Africa)
0x2009 | English (Jamaica)
0x2409 | English (Caribbean)
0x2809 | English (Belize)
0x2c09 | English (Trinidad)
0x040a | Spanish (Traditional Sort)
0x080a | Spanish (Mexican)
0x0c0a | Spanish (Modern Sort)
0x100a | Spanish (Guatemala)
0x140a | Spanish (Costa Rica)
0x180a | Spanish (Panama)
0x1c0a | Spanish (Dominican Republic)
0x200a | Spanish (Venezuela)
0x240a | Spanish (Colombia)
0x280a | Spanish (Peru)
0x2c0a | Spanish (Argentina)
0x300a | Spanish (Ecuador)
0x340a | Spanish (Chile)
0x380a | Spanish (Uruguay)
0x3c0a | Spanish (Paraguay)
0x400a | Spanish (Bolivia)
0x440a | Spanish (El Salvador)
0x480a | Spanish (Honduras)
0x4c0a | Spanish (Nicaragua)
0x500a | Spanish (Puerto Rico)
0x040b | Finnish
0x040c | French (Standard)
0x080c | French (Belgian)
0x0c0c | French (Canadian)
0x100c | French (Swiss)
0x140c | French (Luxembourg)
0x040d | Hebrew
0x040e | Hungarian
0x040f | Icelandic
0x0410 | Italian (Standard)
0x0810 | Italian (Swiss)
0x0411 | Japanese
0x0412 | Korean
0x0812 | Korean (Johab)
0x0413 | Dutch (Standard)
0x0813 | Dutch (Belgian)
0x0414 | Norwegian (Bokmal)
0x0814 | Norwegian (Nynorsk)
0x0415 | Polish
0x0416 | Portuguese (Brazilian)
0x0816 | Portuguese (Standard)
0x0418 | Romanian
0x0419 | Russian
0x041a | Croatian
0x081a | Serbian (Latin)
0x0c1a | Serbian (Cyrillic)
0x041b | Slovak
0x041c | Albanian
0x041d | Swedish
0x081d | Swedish (Finland)
0x041e | Thai
0x041f | Turkish
0x0421 | Indonesian
0x0422 | Ukrainian
0x0423 | Belarusian
0x0424 | Slovenian
0x0425 | Estonian
0x0426 | Latvian
0x0427 | Lithuanian
0x0429 | Farsi
0x042a | Vietnamese
0x042d | Basque
0x0436 | Afrikaans
0x0438 | Faeroese


Commerce Server Tools

Commerce Server 3.0 includes a number of tools that make it easier than ever to create a customized Commerce Server site.

  • υ Site Foundation Wizard . This wizard makes it easy to set up the infrastructure for a new Commerce Server site: its physical directories, its Microsoft® Internet Information Server (IIS) virtual directories, its configuration files, the Microsoft® Windows NT® user account that will be used to manage the new site, and so on. Separating this function from the Site Builder Wizard supports hosting scenarios in which a server administrator creates the foundation, but the site operator builds the site itself.
  • υ Site Builder Wizard . This wizard removes the complexity of creating a commerce site by providing a simple step-by-step interface that generates a completely functional Commerce Server site quickly and easily. The wizard supports a variety of site options, including department hierarchies, products in multiple departments, variable numbers of product attributes, different registration models (on entry, none, on purchase), price and cross-sell promotions, Microsoft Wallet payment options, and so on. Sites generated by this wizard conform to recommended Microsoft® Transaction Server (MTS) and ADO architecture, and they can be edited using Microsoft® Visual InterDev™.
  • υPipeline Editor . The Pipeline Editor is used to customize a site’s pipeline for complete integration with legacy or other business systems. Both a Win32®-based Pipeline Editor and an ASP-based Pipeline Editor are included to support both local and remote editing.
  • υCertificate Management Tool . Several of the components in the Commerce Interchange Pipeline (CIP) use digital certificates for encryption and decryption of business objects such as purchase orders, receipts, and so on. The Certificate Manager is used both to create a certificate request and to manage the exchange of certificates between business trading partners.
  • υCommerce Site Packager. The Commerce Site Packager is a utility for developers that packages an existing Commerce Server site into a self-extracting executable file. This file can then be sent over the Internet for installation at a remote location.
  • υ Administrative Tools . The server administrator can perform tasks such as creating, closing, opening, and deleting Commerce Server sites using any of three administrative interfaces: the Commerce Server snap-in for the Microsoft® Management Console (MMC), the Commerce pages of Site Server Web-based Administration (WebAdmin), or the Commerce Server command-line interface.


The Pipeline Editor

The Pipeline Editor is an application used for editing Commerce Interchange Pipelines and Commerce Server order processing pipelines. There are two versions of the Pipeline Editor:

  • υThe Win32®-based Pipeline Editor. Used for editing a pipeline on the local computer or on a computer connected to a local area network (LAN).
  • υThe ASP-based Pipeline Editor. Used for editing a pipeline remotely over the Internet using a Web browser.

The functionality is very similar in the two versions. You can edit existing pipelines in either Pipeline Editor, but you can create a new pipeline only in the Win32-based Pipeline Editor.


Starting the Pipeline Editor

Because the Win32®-based version of the Pipeline Editor is designed to be used locally, you start it from the Start menu. You start the Active Server Pages (ASP)-based Pipeline Editor from the browser by connecting to the site’s Manager page, and then clicking a button to launch the Pipeline Editor with the selected pipeline loaded.

To start the Win32-based pipeline editor
  1. On the Start menu, point to Programs, point to Microsoft Site Server, point to Commerce, and then click Pipeline Editor.
  2. On the File menu, click Open.
  3. Locate the .pcf file for the pipeline you want to edit. The default location for a site’s .pcf file is \Inetpub\wwwroot\sitename\Config.
  4. Select the .pcf file, and then click Open.
To start the ASP-based pipeline editor
  1. Start your browser and then type the URL of the Manager page of the site whose pipeline you want to edit.

    For example, to edit a pipeline for the Volcano Coffee site, you would type the following URL, substituting the name of the computer for servername: http://servername/vc30/manager/default.asp.

  2. In the System area on the site’s Manager page, select the pipeline you want to edit in the drop-down list, and then click Edit Pipeline.


Creating a New Pipeline (Win32 only)

You can create a new pipeline only in the Win32®-based version of the Pipeline Editor.

Commerce Server version 3.0 provides the following standard templates on which you can base a new pipeline. The template files on which you base the new pipeline have the .pct file extension (pipeline configuration template). When you save the new template, it is saved with the standard .pcf file extension (pipeline configuration file).

Template name | Description
CorpPurchaseSubmit.pct | Two-stage corporate purchasing pipeline, contains Purchase Order Validate and Purchase Order Submit stages.
CorpPurchasingPlan.pct | Fourteen-stage corporate purchasing pipeline, contains Requisition Item Info, Supplier Information, Buyer Information, Requisition Initialization, Requisition Check, Requisition Item Price, Requisition Item Adjust Price, Requisition Adjust Price, Requisition Subtotal, Shipping, Handling, Tax, Requisition Total, and Inventory stages.
plan.pct | Fourteen-stage order processing pipeline (OPP); contains Product Info, Merchant Information, Shopper Information, Order Initialization, Order Check, Item Price, Item Adjust Price, Order Adjust Price, Order Subtotal, Shipping, Handling, Tax, Order Total, and Inventory stages.
product.pct | Five-stage OPP; contains Product Info, Shopper Information, Item Price, Item Adjust Price, and Inventory stages.
purchase.pct | Three-stage OPP; contains only the final Purchase Check, Payment, and Accept stages.
transmit.pct | Commerce Interchange transmit pipeline; contains Map, Sign, Encrypt, Transport, and Audit stages.
receive.pct | Commerce Interchange receive pipeline; contains Transport, Decrypt, Verify, Map, and Application Integration stages.

The template provides a preconfigured pipeline. You can change the names of stages, but you cannot delete or add a stage.

Note

Deleting all the components in a stage does not necessarily provide the same effect as deleting the stage would. Many stages have required components that do not appear in the Pipeline Editor, and those components run even though the stage appears empty in the Pipeline Editor. The Save Values Read & Written command on the Pipeline Editor’s File menu displays a text file that shows the values of the required components as well as all the other components (see Creating a List of Values Read and Written).

You can add or delete any component in any stage.

To create a new pipeline
  1. On the Start menu, point to Programs, point to Microsoft Site Server, point to Commerce, and then click Pipeline Editor.
  2. On the File menu, click New.
  3. Select a template, and then click OK.
  4. Modify the pipeline as necessary.
  5. On the File menu, click Save.


Adding a Component to a Pipeline

Using the Pipeline Editor, you can add a component to any stage in a pipeline. Note, however, that the values that a particular component needs must exist on the order form before that component can successfully complete its function. Therefore, you must make sure that the components in the preceding stages have written the necessary values to the order form before the stage at which you insert a component that needs those values (see Creating a List of Values Read and Written).

To add a component to a pipeline using the ASP-based Pipeline Editor
  1. In the Pipeline Editor, open the pipeline to which you want to add the component.
  2. Locate the stage into which you want to add the component, and then click the Insert component link.

    If the stage already has one or more components, you can insert the new component either before or after an existing component by clicking the link at the location where you want to insert the component.

  3. The Component list displays the list of components normally used in the current stage of the pipeline. Click a component to add it to the pipeline.

    To expand the list to display all components, click Show all available components. To return to the list of only the components normally used in the current stage, click Show only components for stagename.

  4. To configure the new component, click its Edit link. Modify the component’s properties as necessary, and then click Update.
  5. At the top of the page, click Save.
To add a component to a pipeline using the Win32-based Pipeline Editor
  1. In the Pipeline Editor, open the pipeline to which you want to add the component.
  2. Do one of the following:
    • υRight-click the name of the stage into which you want to insert the component, and then on the shortcut menu, click Insert Component. The new component will be inserted at the beginning of the stage.
    • υRight-click the name of an existing component within that stage, point to Insert Component on the shortcut menu, and then click either Before or After. The new component is inserted either before or after the component you selected.
  3. In the Choose a component dialog box, click an option for Stages.

    The option you choose determines which components are displayed in the Components area. The default value is the name of the stage into which you are inserting the component; selecting this option displays only those components that are usually used in that stage. Selecting All displays all components, regardless of the stage in which they are normally used.

  4. In the Components list, click the name of the component you want to insert, and then click OK.
  5. To configure the new component, right-click the component, and then on the shortcut menu, click Properties. Modify the component’s properties as necessary, and then click OK.
  6. On the File menu, click Save.

Related Topics

  • υStarting the Pipeline Editor
  • υ Reloading a Site Using MMC
  • υ Reloading a Site Using WebAdmin


Changing the Order of Components in a Pipeline Stage

You can move a component up or down within its stage. If only one component exists in a stage, you cannot move it. (However, you can delete it and then insert the same component into another stage.)

To move a component in the Win32-based Pipeline Editor
  1. In the Win32®-based Pipeline Editor, open the pipeline.
  2. Right-click the name of the component, and then on the shortcut menu, click either Move Down or Move Up.
To move a component in the ASP-based Pipeline Editor
  1. In the ASP-based Pipeline Editor, open the pipeline.
  2. Locate the component you want to move, and then click its up or down button.
To | Click
Move up | Up button
Move down | Down button

Related Topics

  • υStarting the Pipeline Editor


Creating a List of Values Read and Written (Win32 only)

Each component in a pipeline reads values from the order form, performs its function, and then writes values to the order form. Components that execute later in the pipeline often read values that previous components have written to the order form. When you are modifying a pipeline or creating a new one, it can be helpful to see a list of the values that each component reads and writes so you can ensure that the necessary values are present at each point.

The Win32®-based Pipeline Editor can create a text file that lists each component of a particular pipeline in the order in which it is executed. The text file lists all of the components executed by the pipeline, including the required components that are not displayed in the Pipeline Editor. (The required component always executes last in a given stage.) For each component, the file lists the following information:

  • υInput values (values read)
  • υOutput values (values written)
  • υContext values (values read from the PipeContext Dictionary object, which is passed as a parameter to the pipeline object’s Execute method)
To create a list of all values read and written
  1. In the Win32-based Pipeline Editor, open the .pcf file.
  2. On the File menu, click Save Values Read & Written.
  3. In the Save as dialog box, specify a location and a filename for the text file, and then click Save.

    The Pipeline Editor saves the file and opens it in Notepad.

Related Topics

  • υStarting the Pipeline Editor


Using the Pipeline Editor Property Pages

The property pages available in the Pipeline Editor provide an easy interface for viewing and modifying pipelines, stages, and components.

The following property pages are available.

Element | Property pages | Description
Pipeline (available in Win32® Pipeline Editor only) | Pipe Properties | Pipeline name; the type of pipeline the .pcf file can be used with; comments.
Stage (available in Win32 Pipeline Editor only) | Stage Properties | Stage name and comments.
Component | Component Properties, Values Read and Written, component-specific page | Component name; Class ID; Program ID; description; values read from and written to the order form; values read from the PipeContext. A component that has configurable properties may have an additional property page whose options are specific to that component.

To view property pages
  • υIn the Win32-based Pipeline Editor, right-click the name of the pipeline, stage, or component, and then on the shortcut menu, click Properties.
  • υIn the ASP-based Pipeline Editor, click the Edit link on a component.


Pipeline Properties

You can view this property page only in the Win32-based Pipeline Editor.Use this property page to change the name of the pipeline, specify its transaction mode, or save notes about the pipeline.

  • υLabel. Specifies the name that the Pipeline Editor displays for this pipeline. You can change the name by typing a new name here.
  • υTransaction compatibility. Specifies what pipeline object this configuration file can be used with.
    • υAny pipeline. Indicates that this configuration file can be used with an OrderPipeline object, an MtsPipeline object, or an MtsTxPipeline object.
    • υRequires transacted pipeline (MtsTxPipeline). Indicates that this configuration file can be used only with an MtsTxPipeline object. The MtsTxPipeline object is registered with Microsoft® Transaction Server (MTS) as transactions required, and holds a transaction that spans all components in the pipeline.
    • υRequires non-transacted pipeline (MtsPipeline). Indicates that this configuration file can be used only with an MtsPipeline object. The MtsPipeline object is registered with MTS as transactions not supported.
  • υDescription. Provides a place for you to enter comments about this pipeline.


Stage Properties

You can view this property page only in the Win32-based Pipeline Editor.Use this property page to change the name of the stage or to save notes about the stage.

  • υLabel. Specifies the name that the Pipeline Editor displays for this stage. You can change the name by typing a new name here.
  • υDescription. Provides a place for you to enter comments about this stage.


Component Properties

You can view this property page only in the Win32-based Pipeline Editor.Use this property page to change the name of the component, to view the component’s Class ID or Program ID, and to save notes about the component.

  • υLabel. Specifies the name that the Pipeline Editor displays for this component. You can change the name by typing a new name here.
  • υClass ID. Specifies the globally unique identifier (GUID) that uniquely identifies this component on any computer. This ID does not change even if you change the component’s name.
  • υProgram ID. Specifies the easily recognizable ID for the component. This ID does not change even if you change the component’s name.
  • υDescription. Provides a place for you to type comments about this component.


Values Read and Written

You can view this property page only in the Win32-based Pipeline Editor.Use this property page to view the values that this component reads from and writes to the order form and the values it reads from the PipeContext Dictionary object.

Note

The Pipeline Editor is unable to display Values Read and Written for components that do not support the IPipelineComponentDescription interface (such as Commerce Server 2.0 components).

  • υValues Read. Specifies the values that this component reads from the order form before it performs its function.
  • υValues Written. Specifies the values that this component writes to the order form after it has completed its function.
  • υContext Values Read. Specifies the values that this component reads from the PipeContext Dictionary object. The PipeContext is passed as a parameter to the pipeline object’s Execute method.

Related Topics

  • υCreating a List of Values Read and Written


Creation Error

This property page displays an error to help you determine the reason that a pipeline component could not be loaded.

Try the following solutions:

  • υDelete the component from the pipeline and then reinsert it.
  • υMake sure that the DLL associated with the component is properly registered.
  • υIf neither of the above solutions corrects the problem, try reinstalling Commerce Server.


Custom Properties

Use this property page to create a custom user interface for Visual Basic components.

  • υCustom User Interface. Opens a separate window for defining a custom user interface for Visual Basic components.


Using the Win32-based Pipeline Editor in Expert Mode

The Win32®-based Pipeline Editor is a powerful tool in its standard mode, but it can also be run in Expert mode, which provides additional capabilities useful to developers of custom pipeline components and pipelines.

Caution

In standard mode, the Pipeline Editor has built-in safeguards that prevent some actions that could disable a site’s pipeline. In Expert mode, these protections do not exist. It is recommended that you do not run the Pipeline Editor in Expert mode unless you specifically need the additional functionality it provides.

In Expert mode, the Pipeline Editor provides the following additional functionality:

  • υCreate a custom pipeline without basing it on a preconfigured template file.
  • υInsert, move, and delete pipeline stages.
  • υCut, copy, and paste a stage, including its components.
  • υAssign globally unique identifiers (GUIDs) to stages.
  • υView the required components that are not displayed in standard mode.
  • υMark a component as Required if it is the last component in a stage.


Starting the Win32-based Pipeline Editor in Expert Mode

The Pipeline Editor can be started in Expert mode only from a command-line prompt.

Caution

In standard mode, the Pipeline Editor has built-in safeguards that prevent some actions that could disable a site’s pipeline. In Expert mode, these protections do not exist. It is recommended that you do not run the Pipeline Editor in Expert mode unless you specifically need the additional functionality it provides.

To start the Pipeline Editor in Expert mode
  1. On the Start menu, click Run.
  2. In the Open box, type the path to the PipeEditor.exe file, and add the switch /e to the end of the command.

    If you installed Commerce Server in the default location, you would type the following command:
    \Microsoft Site Server\Bin\PipeEditor.exe /e

  3. Click OK.

Related Topics

  • υStarting the Pipeline Editor (in standard mode)


Setting Stage Properties in Expert Mode

Using the Win32-based Pipeline Editor in Expert mode, you can set the following properties of a pipeline stage:

  • υGUID. The globally unique identifier is a number that uniquely identifies this stage.
  • υMode. The Mode field is provided for compatibility with Commerce Server 2.0 pipelines, in which the number identified which stages of a pipeline should be run by the RunProduct, RunPlan, and RunPurchase methods of the Page object.
  • υError level. When any component in the stage generates an error at or above the level specified in the Error level box, the stage stops running and generates an error.
Caution

In standard mode, the Pipeline Editor has built-in safeguards that prevent some actions that could disable a site’s pipeline. In Expert mode, these protections do not exist. It is recommended that you do not run the Pipeline Editor in Expert mode unless you specifically need the additional functionality it provides.

To set stage properties in Expert mode
  1. Start the Win32 Pipeline Editor in Expert mode, and then open the pipeline whose stage you want to edit.
  2. Right-click the stage, and then, on the shortcut menu, click Properties.
  3. For GUID, type a unique identifier for this stage.
  4. If this is a Commerce Server 2.0 pipeline, type a value for Mode.
  5. For Error level, type a number that represents the error level at which you want to stage to stop execution.
  6. Save the pipeline and close the Pipeline Editor.


Creating a Custom Pipeline in Expert Mode

Using the Win32-based Pipeline Editor in Expert mode, you can create a custom pipeline without basing it on one of the preconfigured pipeline template files (.pct).

Caution

In standard mode, the Pipeline Editor has built-in safeguards that prevent some actions that could disable a site’s pipeline. In Expert mode, these protections do not exist. It is recommended that you do not run the Pipeline Editor in Expert mode unless you specifically need the additional functionality it provides.

To create a new pipeline in Expert mode
  1. Start the Win32 Pipeline Editor in Expert mode.
  2. On the File menu, click New.
  3. In the Choose a Pipeline Template box, double-click Empty.pce.

    This opens an empty pipeline file.

  4. Right-click Empty Pipeline Template, and then on the shortcut menu, click Properties. In the Label field, type a new name for the pipeline. Select an option for Transaction Compatibility, add a description of the pipeline in the Description field, and then click OK.
  5. Right-click the name of the pipeline and then on the shortcut menu, click Insert Stage. Right-click New Stage, and then on the shortcut menu, click Properties. Set the stage properties, and then click OK.
  6. Right-click the name of the stage, and then on the shortcut menu, click Insert Component. For Stages, select All, click the name of the component you want to insert, and then click OK.
  7. To configure the new component, right-click the component, and then on the shortcut menu, click Properties. Modify the component’s properties as necessary, and then click OK.
  8. On the File menu, click Save As, and then type a name for the pipeline configuration file.

    When the Pipeline Editor saves the file, it adds the .pcf file extension.


Commerce Site Packager

The Commerce Site Packager is a utility that packages an existing Commerce Server site into a self-extracting executable file. This file can then be sent over the Internet for installation at a remote location.

The Site Packager program files are installed into the \Commerce\SDK\Commerce\bin directory as part of the Commerce Server SDK installation. (To install the SDK, you must choose the Custom option during Setup, and then select the SDK check box.)


Before You Run the Site Packager

The following programs must be located either in the PATH or in the same directory from which you are running the Commerce Site Packager:

  • υcabarc.exe
  • υiexpress.exe
  • υmakecab.exe
  • υwextract.exe

These files are installed as part of the Commerce Server SDK installation. By default they are installed into the same directory as the Commerce Site Packager program (\Commerce\SDK\Commerce\bin).

Before you run the Commerce Site Packager, you must:

  • υCreate the site that you intend to package. The site must have the standard Commerce Server 3.0 site structure.
  • υPrepare the install script that installs the site after it has been copied to the remote computer.
  • υIf there are additional files other than the site itself that you want to bundle with the packaged site, copy those files to the same directory as the install script. (This is not a requirement, but makes it faster to set program options because the necessary files are in one place.)


Packaging a Site

Use the following procedure to package a site.

To package a site:
  1. Open an MS-DOS window, change to the directory in which CommerceSitePkgr.exe is located, and run CommerceSitePkgr.exe. (Alternatively, you can double-click on the CommerceSitePkgr icon in the Windows NT Explorer.)

    By default, Setup saves CommerceSitePkgr.exe in:
    \Microsoft Site Server\SiteServer\Commerce\SDK\Commerce\bin\i386\

  2. For Site Directory, enter the full path to the top-level directory of the site you want to package. You can click the Browse button to locate the directory if you aren't certain of the path.
  3. For Target Directory, enter the full path to the directory on your local computer into which the self-extracting executable file will be saved.

    After the compressed file has been saved onto your computer, you can transfer it to the remote computer using FTP, email, etc. NOTE: This directory must already exist on your computer—the program will not create it for you if it does not already exist.

  4. The Files To Include field lists additional files other than the site itself that you want to bundle with the packaged site. If you have only a single additional file, you can type its path and file name in the Files To Include field. At the minimum, you must include the install script that installs the site after it has been copied to the remote computer. If you have multiple files, click the Multiple Files button and then select the files you want to include. (To clear the list of files, click the Clear Files button.) Note that this field does not take wildcards. You must specify the entire path and filename, including the extension for each file.
  5. Click the drop-down arrow on the Files To Include field and select the install script.

    The name of this file now appears in the Script To Execute On Install field, and the OK button becomes available.

  6. The default behavior of the self-extracting executable file is to simply install transparently, presenting no user interface. If you prefer to display dialog boxes and message boxes to the user during and after the installation, click the Install Options button to specify the user interface options. The following steps assume that you have clicked the Install Options button.
  7. For Title Shown On Dialog Boxes, type the text string that will be displayed in the title bar of the dialog boxes that are displayed during the installation.
  8. For Install Script Command Line Options, type the parameters that you want to pass to your install script during the installation of the packaged site. Separate each parameter by a space. If the parameter includes a space, enclose the parameter in quotation marks. You must enter the following parameters:
    • υ/sitename: Specifies the name that will be used for naming the site's virtual directory and top-level physical directory.
    • υ/DisplayName: Specifies the name of the site that is displayed on the site's pages.
    • υ/WebSiteID: Specifies the number of the Web site on which the packaged site is to be installed.

    For example, you might enter the following for the Volcano Coffee sample site:

    /sitename:vc30 /DisplayName:"Volcano Coffee" /WebSiteID:1

    In addition to the above parameters, you can also specify the destination directory (the directory into which the site will eventually be installed on the remote computer). To specify this, enter the following parameter:
    /Path:
    You must enter the full path, including the drive letter. If the path contains spaces, remember to enclose the entire path name in quotes.

  9. For Install Prompt, type the text string that will be displayed to the user at the beginning of the installation to confirm that they want to install the site. This text is displayed to the user in a dialog box with Yes and No buttons.
  10. For Path To Display License, enter the path to the text file that contains the site's License Agreement (if any).
  11. For Post Install Command, type the command that is to be used to launch a program that you want to run after the installation is finished. Type the path and filename for the executable file, plus any command-line parameters that you want to pass to the executable file.
  12. For Finish Message, type the text string that will be displayed to the user at the end of the installation to confirm that the site has been successfully installed. This text appears in a dialog box with an OK button.
  13. The Hide Extraction Dialog box specifies whether you want to display the animated progress indicator as the installation proceeds. Click Yes to hide the progress dialog box; click No to display it.
  14. The Show Install Window box controls the windows in which the installation dialog boxes are displayed.

    Default specifies the normal window settings. Hidden hides the window (in this case, even if you specify options for installation dialog boxes, the dialog boxes are not displayed because the window in which they would be displayed is hidden). The Minimize and Maximize options minimize or maximize the window.

  15. Click OK to close the Advanced Options dialog box.
  16. Click OK to package the site.


Certificate Management Tool

The Certificate Management Tool enables you to manage your certificates and those of your trading partners, and to generate certificate requests.

The EncryptPKCS, DecryptPKCS, DigitalSig, VerifyDigitalSig, EncodeSMIME and DecodeSMIME components used in Commerce Interchange Pipelines use certificates to perform operations on data stored in the business data object. To use these components, you must first configure the Certificate Management Tool to import and export certificates generated using the Microsoft Certificate Server.

Note

At this time, the Certificate Management Tool works only with the Windows NT Certificate Server. Support by other certificate authorities is currently in progress.

This section explains how to use the Certificate Management Tool to perform the following tasks:

  • υGenerate certificate requests.
  • υGenerate certificates using Microsoft Certificate Server.
  • υImport certificates from certificate chain (.chn) files.
  • υExport certificates to trading partners.


Generating a Certificate Request

A certificate request is a text file that contains information about you and your organization. After using the Certificate Management Tool to generate a certificate request, you can use the Microsoft® Certificate Server to generate certificates that fulfill the request contained in the request file.

Note

At this time, the Certificate Management Tool works only with the Windows NT Certificate Server. Support by other certificate authorities is currently in progress.

To generate a request file
  1. On the Start menu, point to Programs, point to Microsoft Site Server, point to Commerce, and then click Certificate Management to display the Certificate Management Tool.
  2. Click Create A Certificate Request.
  3. In the File name box, type the full path and file name for the new certificate request file (.crq).

    To simplify keeping track of the certificate requests that you generate, you should store certificate requests in the shared folder that you specified when you installed the Microsoft Certificate Server.

  4. Fill in the personal and business information in the appropriate text boxes.
  5. For Usage, click an option to specify how you will use the key stored in the certificate that you generate based on this request.

    For example, if you intend to use the generated certificate to digitally sign data, click Signature. If you intend to use the generated certificate to encrypt data, click Exchange.

  6. For Scope, specify the context in which the generated certificate can be used.

    If you want the certificate chain file to be imported only by the currently logged-on user, click Current User. If you want to allow anyone logged onto the current machine to import or export the certificate, click Machine.

    If you are generating a request for a certificate that you intend to use under the Internet Information Server (IIS) service, the certificate must be a machine-based certificate. This requirement arises from the fact that IIS does not run under the current user’s security context. Certificates that you generate for use with the DigitalSig or DecryptPKCS components must be machine-based certificates because these components are executed under IIS and therefore use the machine context. This requirement does not apply to certificates submitted to you by your trading partners for use with the EncryptPKCS or VerifyDigitalSig components.

  7. Click OK.

    The Certificate Management Tool generates the request file (.crq) and saves it in the directory that you specified.

After generating a certificate request file, you can use the Microsoft Certificate Server to generate the certificate (.crt) and certificate chain (.chn) files that fulfill that request.


Generating Certificates with Microsoft Certificate Server

Microsoft® Certificate Server is included with the Windows NT 4.0 Option Pack, however, it is not installed as part of the Typical option in setup. To install Certificate Server, run the Windows NT 4.0 Option Pack Setup. If you have already installed the Option Pack, click the Add/Remove button (which enables you to add a component to the existing installation), select the Certificate Server check box, and then proceed with setup. If you have not yet installed the Option Pack, click the Custom button during setup, select the Certificate Server check box, and then proceed with setup.

The Certificate Server is a command-line executable file (installed by default in the \WINNT\System32\ directory) that runs as a Windows NT service. Generating a certificate involves running the CertReq application (certreq.exe) while the Certificate Server service is running.

To generate a certificate from a request file
  1. On the Start menu, point to Programs, and then click Command Prompt.
  2. Change to the directory in which your certificate requests are saved.
  3. At the command prompt , make sure that the Certificate Server service is running by typing:
    net start certsvc
  4. At the command prompt, type the following command. For filename, substitute the name of the certificate request file (.crq) that you generated using the Certificate Management Tool (see Generating a Certificate Request):
    certreq filename.crq filename.crt filename.chn

The CertReq application generates a certificate (.crt) file and a certificate chain (.chn) file, based on the request. The .crt file contains only the certificate, while the .chn file contains the certificate plus the certificate for the issuing authority. The Certificate Management Tool requires a certificate chain file (.chn), but because the .crt is a required parameter, a .crt file is generated as well.

Related Topics

  • υImporting a Certificate.
  • υExporting a Certificate


Importing a Certificate

Importing a certificate involves using the Certificate Management Tool to retrieve a certificate from a certificate chain file (.chn) and then installing that certificate on your system. This certificate can be one that you have generated, or can be one that your trading partner has generated and submitted to you.

Note

At this time, the Certificate Management Tool works only with the Windows NT Certificate Server. Support by other certificate authorities is currently in progress.

If you are building a transmit pipeline and you want to digitally sign the data in the business data object, then you first use the Certificate Management Tool to generate a signature certificate request (see Generating a Certificate Request). Next, you use Microsoft Certificate Server to generate a certificate based on this request (see Generating Certificates with Microsoft Certificate Server). The result of this operation is a certificate chain file (.chn), which you import using the Certificate Management Tool.

After you have imported the certificate, you can configure the DigitalSig component to use this certificate to digitally sign the business data object data.

In addition, you supply a copy of the .chn file for this certificate to your trading partner. After your trading partner has imported the certificate, it can be used in a receive pipeline to configure the VerifyDigitalSig component.

If you want to use a trading partner’s certificate to encrypt a business data object, obtain a certificate chain (.chn) file for an exchange certificate from your trading partner, and import it onto your system. After importing the certificate, you can use it to configure the EncryptPKCS component.

To import a certificate that you have created
  1. Click the Start button, point to Programs, point to Microsoft Site Server, point to Commerce, and then click Certificate Management to display the Certificate Management Tool.
  2. Click Manage My Certificates.
  3. Select the .chn file from which to import the certificate, and then click Open.
  4. A message box appears to notify you that the certificate was successfully imported.
Note

A certificate can be imported only once. Subsequent attempts to import the same certificate will fail. If you need to import a certificate again (for example, if you deleted it by accident), you must re-create the certificate (create a new certificate request, generate a new certificate chain file) and then import the new certificate.

To import a trading partner’s certificate
  1. Click the Start button, point to Programs, point to Microsoft Site Server, point to Commerce, and then click Certificate Management to display the Certificate Management Tool.
  2. Click Manage Trading Partner’s Certificates.
  3. Click Import.
  4. Specify which certificate to use if the certificate contained in the .chn file is a duplicate of one already installed on your system.
  5. Type the path to the certificate chain file (.chn) from which to import the certificate (or click the Browse button and locate the file), and then click OK.
  6. Click OK to close the message box that indicates successful completion.

If the certificate you have imported is an exchange certificate, you can use it to configure the EncryptPKCS component.


Exporting a Certificate

Exporting a certificate saves the certificate into a certificate chain file (.chn) that you can then supply to your trading partners. If the certificate is an exchange certificate, a trading partner can use the certificate to configure the EncryptPKCS component. If the selected certificate is a signature certificate, a trading partner can use the certificate to configure the VerifyDigitalSig component.

To export a certificate
  1. Click the Start button, point to Programs, point to Microsoft Site Server, point to Commerce, and then click Certificate Management to display the Certificate Management Tool.
  2. Click Manage My Certificates.
  3. Click the certificate to export, and then click Export to Trading Partner.
  4. Specify a location and a file name for the .chn file, and then click Save.

The Certificate Management Tool exports the certificate to the specified file.


Replicating a Certificate on Multiple Servers

To use the same certificate on multiple servers, you import the certificate and then export it into a .pfx file. The .pfx file can then be distributed to the other servers and imported using the Certificate Management Tool.

On one computer, you must create the original request file (.crq) and then import the certificate chain file that was generated from this request. You then create a backup of the certificate (the .pfx file) using Export with key pair. On the other servers, you use the Certificate Management Tool’s Import with key pair functionality to import the certificate from the .pfx file.

To export a certificate for replication to multiple servers
  1. Click the Start button, point to Programs, point to Microsoft Site Server, point to Commerce, and then click Certificate Management to display the Certificate Management Tool.
  2. Click Manage My Certificates.
  3. Click the certificate to export, and then click Export with Key Pair.
  4. Type a password to use to encrypt the exported key pair.
  5. Type the full path and filename for the .pfx file, or click Browse and specify a location and file name. Click OK.

    The confirmation message specifies the type of certificate that was exported into the .pfx file (the type was specified when you created the original certificate request):

    • υMachine. Allows anyone logged onto the computer to import or export the certificate.
    • υCurrent user. Allows only the user who was logged on when the original certificate request was created to import or export the certificate.

    If this is a machine scope certificate, you must select the Machine Key Scope check box when you import the certificate on the other servers.

To import the certificate on other servers
  1. Click the Start button, point to Programs, point to Microsoft Site Server, point to Commerce, and then click Certificate Management to display the Certificate Management Tool.
  2. Click Manage My Certificates.
  3. Click the certificate to export, and then click Import with Key Pair.
  4. Specify which certificate to use if the certificate contained in the .pfx file is a duplicate of one already installed on your system.
  5. Type the password that was used to encrypt the exported key pair.
  6. Type the path to the .pfx file from which to import the certificate (or click the Browse button and locate the file).
  7. If the .pfx file contains a machine-based certificate, select the Machine Key Scope check box.
  8. Click OK.


Commerce Server Component Interfaces

Microsoft® Commerce Server 3.0 includes a group of Component Object Model (COM) interfaces that are implemented by Commerce Server objects, or that you implement to create your own objects.

These interfaces fall into two categories.

The first consists of the pipeline interfaces. These are interfaces that are defined by Commerce Server 3.0, but that you implement to create order processing pipeline (OPP) or Commerce Interchange components. These interfaces include the following.

Interface | Description
IConfigurationCache | Helps optimize loading of pipeline configuration data under stress.
IPersistStreamInit | Persists an object’s data to a stream.
IPersistXML | Persists an object’s data to an XML stream.
IPipelineComponent | Executes the component.
IPipelineComponentAdmin | Sets and retrieves the properties on a component using a Dictionary object.
IPipelineComponentDescription | Uses a SAFEARRAY to identify the OrderForm and pipe context elements that a component reads and writes.
IPersistStream | Saves and loads a component’s properties to and from persistent storage.
ISpecifyPropertyPages | Supports methods that make it possible to store data in an array of VARIANTs.

The second category of interfaces includes those that are implemented by objects included in Commerce Server 3.0, and which you use in the course of creating custom pipeline components. These interfaces include the following.

Interface | Description
IDataFunctions | Supports methods that perform the locale-based conversion of strings and numeric values.
IDictionary | Supports methods that make it possible to store data as name/value pairs.
IMSCSMessageManager_3_0 | Supports adding and retrieving messages to and from the MessageManager.
IMSCSStandardSManager_3_0 | Supports the creation, storage, and retrieval or unique shopper IDs.
IOrderForm | Supports methods that add and remove items from an OrderForm object.
IOrderPipeline | Supports methods that load and execute an OrderPipeline pipeline.
IPipeline | Supports methods that load and execute an MtsPipeline or MtsTxPipeline pipeline.
ISimpleList | Supports methods that make it possible to store data in an array of VARIANTs.


Header Files

The following table lists and describes the header files that are included with the Commerce Server Software Development Kit (SDK).

File | Description
billingapi.h | Contains the definitions for the Billing Application Programming Interface (API) routines.
commerce.h | Contains the interface definitions for the Commerce Server 3.0 objects.
comp_ids.h | Contains the class identifiers (CLSIDs) for the pipeline component classes.
mspu_guids.h | Contains the CLSIDs for the order processing pipeline objects and interfaces.
pipeline.h | Contains the definitions for the pipeline interfaces.
pipecomp.h | Contains the proxy/stub definitions for the pipeline interfaces.
pipe_stages.h | Contains the globally unique identifiers (GUIDs) for the OPP stages.


IConfigurationCache Interface

Commerce Server objects that support transactions implement the IConfigurationCache interface. By implementing this interface, transacted objects are able to govern the way in which they cache their own configuration information.

When a transacted pipeline initializes a transacted object, it can query for an interface pointer on the object's IConfigurationCache implementation. Through this pointer, the pipeline can call the component's SaveToCache method. This method is implemented by the component to generate a key that uniquely identifies the component’s configuration information.

You can think of this key just as you would think of the primary key to a database table; the primary key is a unique handle to a row of information. In the case of IConfigurationCache, the row is the information that the component stores in a persistent medium and uses to configure itself. Generally, this key is simply the class identifier of the transacted component. However, a component’s configuration key can be any item of information that enables the component to load its configuration information from storage.

The IConfigurationCache interface defines the following methods.

Method | Purpose
FreeCache | Deletes the specified configuration key.
LoadFromCache | Loads an object’s configuration information based upon the specified key.
SaveToCache | Returns an out-value BSTR to the pipeline. This BSTR variable is a unique key that indicates the configuration to load.


IConfigurationCache::FreeCache

The FreeCache method deletes the specified entry from the configuration cache.

HRESULT FreeCache(
BSTR bstrToken// in
);

Parameter

bstrToken
Specifies the entry to delete.

Include

<pipeline.h>
<pipecomp.h>

Return Value

This method returns an HRESULT value.

Related Topic

IConfigurationCache::SaveToCache


IConfigurationCache::LoadFromCache

The LoadFromCache method loads a component’s configuration based on a specified configuration entry. This entry, which is stored in the specified BSTR variable, contains the value that the IConfigurationCache implementation generates and returns to the caller in its SaveToCache implementation.

HRESULT LoadFromCache(
BSTR bstrToken// in
);

Parameter

bstrToken
The configuration key for the object implementing IConfigurationCache. This is the key generated by the object in its SaveToCache implementation.

Include

<pipeline.h>
<pipecomp.h>

Return Value

This method returns an HRESULT value.

Related Topic

IConfigurationCache::SaveToCache


IConfigurationCache::SaveToCache

The SaveToCache method generates a unique key to the object’s configuration information, saves this key to persistent storage, and returns the key to the caller (for example, the pipeline).

Syntax

HRESULT SaveToCache(
BSTR *pbstrToken// out, retval
);

Parameter

pbstrToken
The address of a BSTR that contains the key that will be used to uniquely identify this object’s configuration information and to retrieve this information from storage. While this key is typically the object’s class ID, it can be any unique identifier.

Include

<pipeline.h>
<pipecomp.h>

Return Value

This method returns an HRESULT value.

Related Topic

IConfigurationCache::LoadFromCache


IDataFunctions Interface

The DataFunctions component implements the IDataFunctions interface. This interface supports a group of methods that perform locale-based data type conversions. For example, the IDataFunctions methods convert string values to data types that can be properly inserted into a database or passed in an OrderForm to the order processing pipeline (OPP). In addition, the IDataFunctions interface supports methods that can convert native data types, such as DATE, long, and double, to string VARIANTs.

The IDataFunctions interface supports the following methods.

Method | Description
CleanString | Processes a string, stripping out white spaces, modifying the case of the string, and validating that the length of the string falls within a given range.
ConvertDateString | Converts a string representation of the date to a DATE VARIANT, based on the specified locale.
ConvertDateTimeString | Converts a string representation of the date/time to a DATE VARIANT, based on the specified locale.
ConvertFloatString | Converts a string representation of a number to a double VARIANT, based on the specified locale.
ConvertMoneyString | Converts a string representation of a monetary value to a currency VARIANT, based on the specified locale.
ConvertNumberString | Converts a string representation of a number to a long VARIANT, based on the specified locale.
ConvertTimeString | Converts a string representation of the time to a DATE VARIANT, based on the specified locale.
Date | Converts a DATE VARIANT to a BSTR VARIANT, based on the specified locale.
DateTime | Converts a DATE VARIANT to a BSTR VARIANT, based on the specified locale.
Float | Converts a double to a BSTR VARIANT, based on the specified locale.
GetLocaleInfo | Returns information on the specified locale in a BSTR VARIANT.
GetLocaleList | Returns an ISimpleList interface pointer on a SimpleList that contains the locale available on the system.
Money | Converts a currency value to a BSTR VARIANT, based on the specified locale.
Number | Converts a long integer to a BSTR VARIANT, based on the specified locale.
Time | Converts a DATE VARIANT to a BSTR VARIANT, based on the specified locale.
ValidateDateTime | Verifies that the specified DATE VARIANT falls within the specified range.
ValidateFloat | Verifies that the specified double falls within a provided range.
ValidateNumber | Verifies that the specified long integer falls within the given range.


IDataFunctions::CleanString

The CleanString method processes a string, stripping out white spaces, modifying the case of the string, and validating that the length of the string falls within a given range. If successful, CleanString returns the processed string.

Syntax

HRESULT CleanString(
VARIANT vtInput,// in
VARIANT vtMinLen,// in
VARIANT vtMaxLen,// in
VARIANT vtStripWhite,// in
VARIANT vtStripReturn, // in
VARIANT vtCase,// in
VARIANT vtLocale,// in
VARIANT *pvarOutput// out
);

Parameters

vtInput
A BSTR VARIANT that contains the string to process.
vtMinLen
A long (VT_I4) VARIANT that specifies the minimum length of the string. If this VARIANT is empty, CleanString initializes it to a default value of zero (0).
vtMaxLen
A long (VT_I4) VARIANT that specifies the minimum length of the string. If this VARIANT is empty, CleanString initializes it to a default value of zero (0).
vtStripWhite
A long (VT_I4) VARIANT that indicates whether to strip white spaces from the string. By default, this value is one (1), in which case the white spaces are stripped.
vtStripReturn
A long (VT_I4) VARIANT that indicates whether to strip the carriage returns from the string. By default, this value is one (1), in which case the white spaces are stripped.
vtCase
A long (VT_I4) VARIANT that indicates whether to convert the string to uppercase. By default, this value is zero (0), in which case the string is not converted to upper case.
vtLocale
A long (VT_I4) VARIANT that designates the locale to use to perform the conversion. If this VARIANT is empty, then the locale specified by a previous call to put_Locale is used to perform the conversion.
pvarOutput
If CleanString is successful, pvarOutput contains the address of a BSTR VARIANT that has been initialized to contain the processed string; otherwise, NULL.

Include

<commerce.h>

Return Values

Value | Description
S_OK | The method succeeded, and pvarOutput contains the processed string.
E_OUTOFMEMORY | CleanString could not allocate the memory for pvarOutput.


IDataFunctions::ConvertDateString

The ConvertDateString method converts a string representation of the date to a DATE VARIANT, based on the specified locale.

Syntax

HRESULT ConvertDateString(
VARIANT vtDate,// in
VARIANT vtLocale,// in
VARIANT *pVarDate// out
);

Parameters

vtDate
A VARIANT that contains the date to be set. This is a VARIANT in which the vt member is of type V_BSTR and in which the BSTR member contains the string expression of the date.
vtLocale
A VARIANT that specifies the locale to be used to perform the conversion. If this VARIANT is empty or NULL, ConvertDateString uses the locale specified by a previous call to put_Locale.
pVarDate
If the conversion is successful, pVarDate points to the VARIANT that contains the converted value; otherwise, NULL. Note that if a time is included in the string expression of the date, ConvertDateString fails, and pvarDate is set to NULL.

Include

<commerce.h>

Return Value

Value | Description
S_OK | ConvertDateString always returns S_OK. If the conversion is unsuccessful, the pvarDate out-value is NULL.

Related Topic

IDataFunctions::ConvertDateTimeString, IDataFunctions::ConvertTimeString


IDataFunctions::ConvertDateTimeString

The ConvertDateTimeString method converts string representation of the date/time to a DATE VARIANT, based on the specified locale.

Syntax

HRESULT ConvertDateTimeString(
VARIANT vtDateTime,// in
VARIANT vtLocale,// in
VARIANT *pvarDate// out
);

Parameters

vtDateTime
A VARIANT that contains the string representation of the date/time. The vt member of this VARIANT must be initialized to VT_BSTR, and its pbstrVal member must contain the BSTR value to convert.
vtLocale
A VARIANT that specifies the locale to be used to perform the conversion. If this VARIANT is empty (VT_EMPTY) or NULL (VT_NULL), ConvertDateString uses the locale specified by a previous call to put_Locale.
pvarDate
If successful, a pointer to a VARIANT that contains the converted value; otherwise, NULL. Note that the vtDateTime passed to this method must contain only the time. If it contains the date also, ConvertTimeString sets pvarDate VARIANT pointer to NULL.

Include

<commerce.h>

Return Values

Value | Description
S_OK | The conversion was successful.
DISP_E_TYPEMISMATCH | The value in vtDate is not a BSTR value.

Related Topic

IDataFunctions::ConvertDateString, IDataFunctions::ConvertTimeString


IDataFunctions::ConvertFloatString

The ConvertFloatString method converts a string representation of a number to a double VARIANT, based on the specified locale.

Syntax

HRESULT ConvertFloatString(
VARIANT vtNum,// in
VARIANT vtLocale,// in
VARIANT *pvarNumber// out
);

Parameters

vtNum
A VARIANT that contains the string representation of the number to convert. The vt member of this VARIANT must be initialized to VT_BSTR, and its pbstrVal member must contain the BSTR value to convert.
vtLocale
A VARIANT that specifies the locale on which to base the conversion. If this VARIANT is empty (VT_EMPTY) or NULL (VT_NULL), ConvertFloatString uses the locale specified by a previous call to put_Locale.
pvarNumber
If successful, a pointer to a VARIANT that contains the converted value. ConvertFloatString initializes this VARIANT’s vt member to VT_R8, and stores the converted value in its dblVall member. If unsuccessful, ConvertFloatString sets pvarNumber to NULL.

Include

<commerce.h>

Return Values

Value | Description
S_OK | The conversion was successful.
DISP_E_TYPEMISMATCH | The value in vtNum is not a BSTR value.

Related Topic

IDataFunctions::ConvertNumberString


IDataFunctions::ConvertMoneyString

The ConvertMoneyString method converts a string representation of a currency value to a currency VARIANT, based on the specified locale.

HRESULT ConvertMoneyString(
VARIANT vtMoney,// in
VARIANT vtLocale,// in
VARIANT vtNumber// out
);

Parameters

vtMoney
A VARIANT that contains the string representation of the number to convert. The vt member of this VARIANT must be initialized to VT_BSTR, and its pbstrVal member must contain the BSTR value to convert.
vtLocale
A VARIANT that specifies the locale on which to base the conversion. If this VARIANT is empty (VT_EMPTY) or NULL (VT_NULL), ConvertMoneyString uses the locale specified by a previous call to put_Locale.
pvtNumber
If successful, a pointer to a VARIANT that contains the converted value. ConvertMoneyString initializes this VARIANT’s vt member to VT_CY, and stores the converted value in its cy member. If unsuccessful, ConvertMoneyString sets pvarNumber to NULL.

Include

<commerce.h>

Return Values

Value | Description
S_OK | The conversion was successful.
DISP_E_TYPEMISMATCH | The value in vtNum is not a BSTR value.
DISP_E_OVERFLOW | The value in vtNum is smaller than LONG_MIN (–2147483647–1) or is greater than LONG_MAX (2147483647).

Related Topic

IDataFunctions::Money


IDataFunctions::ConvertNumberString

The ConvertNumberString method converts a string representation of a number to a long VARIANT, based on the specified locale.

Syntax

HRESULT ConvertNumberString(
VARIANT vtNum,// in
VARIANT vtLocale,// in
VARIANT *pvarNumber// out
);

Parameters

vtNum
A VARIANT that contains the string representation of the number to convert. The vt member of this VARIANT must be initialized to VT_BSTR, and its pbstrVal member must contain the BSTR value to convert.
vtLocale
A VARIANT that specifies the locale on which to base the conversion. If this VARIANT is empty (VT_EMPTY) or NULL (VT_NULL), ConvertNumberString uses the locale specified by a previous call to put_Locale.
pvarNumber
If successful, a pointer to a VARIANT that contains the converted value. ConvertNumberString initializes this VARIANT’s vt member to VT_I4, and stores the converted value in its lVal member. If unsuccessful, ConvertNumberString sets the Vt member to VT_NULL.

Include

<commerce.h>

Return Values

Value | Description
S_OK | The conversion was successful.
DISP_E_TYPEMISMATCH | The value in vtNum is not a BSTR value.

Related Topic

IDataFunctions::ConvertFloatString, IDataFunctions::Money


IDataFunctions::ConvertTimeString

The ConvertDateString method converts a string representation of the time to a DATE VARIANT, based on the specified locale. The vt member of this VARIANT must be initialized to VT_BSTR, and its pbstrVal member must contain the BSTR value to convert.

HRESULT ConvertTimeString(
VARIANT vtDate,// in
VARIANT vtLocale,// in
VARIANT *pvarDate// out
);

Parameters

vtDate
A VARIANT that contains the string expression of the date. The vt member of this VARIANT must be of type BSTR, and must not contain a date value. If a date value is present, then the pvarDate out-value is set to NULL.
vtLocale
A VARIANT that specifies the locale to be used to perform the conversion. If this VARIANT is empty (VT_EMPTY) or NULL (VT_NULL), ConvertTimeString uses the locale specified by a previous call to put_Locale.
pvarDate
If successful, a pointer to a VARIANT that contains the converted value; otherwise, NULL.

Include

<commerce.h>

Return Values

Value | Description
S_OK | The conversion was successful.
DISP_E_TYPEMISMATCH | The value in vtDate is not a BSTR value.

Include

<commerce.h>

Related Topic

IDataFunctions::ConvertDateString, IDataFunctions::ConvertDateTimeString, IDataFunctions::Date, IDataFunctions::DateTime


IDataFunctions::Date

The Date method converts a DATE to a BSTR VARIANT, based on the specified locale.

Syntax

HRESULT Date(
DATE dtDate,// in
VARIANT vtLocale,// in
VARIANT *pvarRet// out
);

Parameters

dtDate
A DATE variable that contains the value to convert. Prior to converting this value, Date sets its time elements to zero (0).
vtLocale
A VARIANT that specifies the locale on which to base the conversion. If this VARIANT is empty (VT_EMPTY) or NULL (VT_NULL), Date uses the locale specified by a previous call to put_Locale.
pvarRet
If successful, a pointer to a VARIANT that contains the converted value. Date initializes this VARIANT’s vt member to VT_BSTR, and stores the converted value in its pbstrVal member. If unsuccessful, Date sets pvarRet to NULL.

Include

<commerce.h>

Return Values

Value | Description
S_OK | This function always returns S_OK. If the conversion is unsuccessful, pvarRet is NULL.

Related Topic

IDataFunctions::DateTime, IDataFunctions::Time


IDataFunctions::DateTime

The DateTime method converts a DATE to a string VARIANT, based on the specified locale.

HRESULT DateTime(
DATE dtDate,// in
VARIANT vtLocale,// in
VARIANT *pvarRet
);

Parameters

dtDate
A DATE variable that contains the date/time to convert.
vtLocale
A VARIANT that specifies the locale on which to base the conversion. If this VARIANT is empty (VT_EMPTY) or NULL (VT_NULL), DateTime uses the locale specified by a previous call to put_Locale.
pvarRet
If successful, a pointer to a VARIANT that contains the converted value. DateTime initializes this VARIANT’s vt member to VT_BSTR, and stores the converted value in its pbstrVal member. If unsuccessful, DateTime sets pvarRet to NULL.

Include

<commerce.h>

Return Values

Value | Description
S_OK | This function always returns S_OK. If the conversion fails, pvarRet evaluates to NULL.

Related Topic

IDataFunctions::Date, IDataFunctions::Time


IDataFunctions::Float

The IDataFunctions::Float method converts a double to a string VARIANT, based on the specified locale.

Syntax

HRESULT Float(
double Number,// in
VARIANT vtLocale,// in
VARIANT *pvarRet// out
);

Parameters

Number
Specifies the number to format as a BSTR.
vtLocale
A VARIANT that specifies the locale to use to perform the conversion. If this VARIANT is empty (VT_EMPTY) or NULL (VT_NULL), Float uses the locale specified by a previous call to put_Locale.
pvarRet
If successful, a pointer to a VARIANT that contains the converted value. Float initializes this VARIANT’s vt member to VT_BSTR, and stores the converted value in its pbstrVal member. If unsuccessful, Float sets pvarRet to NULL.

Include

<commerce.h>

Return Values

Value | Description
S_OK | This function always returns S_OK. If the conversion fails, Float returns an HRESULT indicating failure (for example, E_FAIL), and sets pvarRet evaluates to NULL.

Related Topic

IDataFunctions::ConvertFloatString, IDataFunctions::Number


IDataFunctions::GetLocaleInfo

The GetLocaleInfo method returns information on the specified locale in a BSTR VARIANT.

Syntax

HRESULT GetLocaleInfo(
long info,// in
VARIANT locale,// in
VARIANT *pvarRet
);

Parameters

info
A long integer that indicates the type of locale information to return in pvarRet. This value must map to one of the LCTYPE constants. For information about this constant, see the Win32® SDK Help.
locale
A long VARIANT that identifies the locale on which to return information. If this VARIANT is empty (VT_EMPTY) or null (VT_NULL), GetLocaleInfo returns information for the locale specified in a previous call to put_Locale.
pvarRet
If successful, pvarRet points to a BSTR VARIANT that contains the requested locale information; Otherwise, NULL.

Include

<commerce.h>

Return Values

Value | Description
S_OK | The method succeeded, and pvarRet contains the locale information.
E_FAIL | The locale information could not be retrieved.

Related Topic

IDataFunctions::GetLocaleList


IDataFunctions::GetLocaleList

The GetLocaleList method returns an ISimpleList interface pointer on a SimpleList that lists the locales available on the system.

Syntax

HRESULT GetLocaleList(
VARIANT *pvarRet// out
);

Parameters

pvarRet
An ISimpleList pointer on the SimpleList of system locales, if the method succeeds; Otherwise, NULL.

Include

<commerce.h>

Return Value

Value | Description
S_OK | This method always returns S_OK. If the method fails, pvarRet evaluates to NULL.

Related Topic

IDataFunctions::GetLocaleInfo


IDataFunctions::Money

The IDataFunctions::Money method converts the specified currency value to a string VARIANT, based on the specified locale.

Syntax

HRESULT Money(
long lMoney,// in
VARIANT vtLocale,// in
VARIANT *pvarRet
);

Parameters

lMoney
A long integer that contains the value to convert.
vtLocale
A VARIANT that specifies the locale to use to perform the conversion.
pvarRet
If successful, a pointer to a VARIANT that contains the converted value. Money initializes this VARIANT’s vt member to VT_BSTR, and stores the converted value in its pbstrVal member. If unsuccessful, Float sets pvarRet to NULL.

Include

<commerce.h>

Return Values

Value | Description
S_OK | The conversion was successful. If the conversion fails, Float returns an HRESULT indicating failure (for example, E_FAIL), and pvarRet is set to NULL.

Related Topic

IDataFunctions::ConvertMoneyString


IDataFunctions::Number

The Number method converts a long integer to a string VARIANT, based on the specified locale.

HRESULT Number(
long Number,// in
VARIANT vtLocale,// in
VARIANT *pvarRet
);

Parameters

Number
A long integer which contains the number to convert.
vtLocale
A VARIANT that specifies the locale on which to base the conversion. If this VARIANT is empty (VT_EMPTY) or NULL (VT_NULL), Number uses the locale specified by a previous call to put_Locale.
pvarRet
If successful, a pointer to a VARIANT that contains the converted value. Number initializes this VARIANT’s vt member to VT_BSTR, and stores the converted value in its pbstrVal member. If unsuccessful, Number sets pvarRet to NULL.

Include

<commerce.h>

Return Values

Value | Description
S_OK | The conversion was successful. If the conversion fails, pvarRet evaluates to NULL.

Related Topics

  • υIDataFunctions::ConvertNumberString
  • υIDataFunctions::ValidateNumber


IDataFunctions::Time

The Time method converts a DATE to a string VARIANT, based on the specified locale.

HRESULT Time(
DATE dtDate,// in
VARIANT vtLocale,// in
VARIANT *pvarRet// out
);

Parameters

dtDate
A DATE variable that contains the time to convert. Prior to converting this value, Time converts it to a UDATE, and sets its date members (wYear, wMonth, wDay, and wDayOfWeek) to 1899, 12, 30, and 6, respectively.
vtLocale
A VARIANT that specifies the locale on which to base the conversion. If this VARIANT is empty (VT_EMPTY) or NULL (VT_NULL), Time uses the locale specified by a previous call to put_Locale.
pvarRet
If successful, a pointer to a VARIANT that contains the converted value. Time initializes this VARIANT’s vt member to VT_BSTR, and stores the converted value in its bstrVal member. If unsuccessful, Time sets pvarRet to NULL.

Include

<commerce.h>

Return Values

Value | Description
S_OK | This function always returns S_OK. If the conversion is not successful, pvarRet evaluates to NULL.

Related Topic

IDataFunctions::ConvertTimeString


IDataFunctions::ValidateDateTime

The ValidateDateTime method that the specified DATE VARIANT falls within a specified date range, using the default locale.

HRESULT ValidateDateTime(
VARIANT vtDate,// in
VARIANT vtMin,// in
VARIANT vtMax,// in
VARIANT *pfValid
);

Parameters

vtDate
A DATE VARIANT that contains the date/time info on which to perform range-checking.
vtMin
A DATE VARIANT that contains the low end of the date range. If this VARIANT is empty (VT_EMPTY) or NULL (VT_NULL), this parameter is ignored.
vtMax
A DATE VARIANT that specifies the high end of the date range. If this VARIANT is empty (VT_EMPTY) or NULL (VT_NULL), this parameter is ignored.
pfValid
If ValidateDateTime is successful, this out-value points to a VARIANT_BOOL VARIANT, the boolVal member of which indicates whether the vtNumber falls within the range specified by vtMin and vtMax; otherwise, pfValid is set to NULL.

Include

<commerce.h>

Return Value

Value | Description
S_OK | This method always returns S_OK. If the validation fails, the pfRet value is a BOOL_VARIANT that evaluates to FALSE.

Related Topic

IDataFunctions::DateTime, IDataFunctions::ConvertDateTimeString


IDataFunctions::ValidateFloat

The ValidateFloat method verifies that the specified double falls within the provided range.

Syntax

HRESULT ValidateFloat(
VARIANT vtNumber,// in
VARIANT vtMin,// in
VARIANT vtMax,// in
BOOL* pfValid// out
);

Parameters

vtNumber
A VARIANT that contains the number on which to perform range-checking. This VARIANT’s vt member can be initialized to the following types: VT_I2, VT_I4, VT_R4, VT_R8, VT_CY, VT_I1, VT_UI1, VT_UI2, VT_UI4, VT_I8, VT_INT, VT_UINT. However, prior to performing validation on this number, ValidateFloat converts it to a VARIANT (VT_R8).
vtMin
A VARIANT that specifies the minimum end of the range. Prior to performing the range validation, ValidateFloat converts this VARIANT to a long VARIANT (VT_R8).
vtMax
A VARIANT that specifies the maximum end of the range. Prior to performing the range validation, ValidateFloat converts this VARIANT to a long VARIANT (VT_R8).
pfValid
If ValidateFloat is successful, this out-value points to a VARIANT_BOOL VARIANT, the boolVal member of which indicates whether the vtNumber falls within the range specified by vtMin and vtMax; otherwise, pfValid is set to NULL.

Include

<commerce.h>

Return Value

Value | Description
S_OK | This function always returns S_OK. To determine whether or not the operation was actually successful, check the pfValid out-value.

Related Topic

IDataFunctions::ConvertFloatString , IDataFunctions::Float


IDataFunctions::ValidateNumber

The ValidateNumber method verifies that the specified number falls within the provided range.

Syntax

HRESULT ValidateNumber(
VARIANT vtNumber,// in
VARIANT vtMin,// in
VARIANT vtMax,// in
VARIANT *pfValid// out
);

Parameters

vtNumber
A VARIANT that contains the number on which to perform range-checking. This VARIANT’s vt member can be initialized to the following types: VT_I2, VT_I4, VT_R4, VT_R8, VT_CY, VT_I1, VT_UI1, VT_UI2, VT_UI4, VT_I8, VT_INT, VT_UINT. However, prior to performing validation on this number, ValidateNumber converts it to long (VT_I4) integer.
vtMin
A VARIANT that specifies the minimum end of the range. Prior to performing the range validation, ValidateNumber converts this VARIANT to a long VARIANT (VT_I4).
vtMax
A VARIANT that specifies the maximum end of the range. Prior to performing the range validation, ValidateNumber converts this VARIANT to a long VARIANT (VT_I4).
pfValid
This out-value points to a VARIANT_BOOL VARIANT, the boolVal member of which indicates whether the vtNumber falls within the range specified by vtMin and vtMax.

Include

<commerce.h>

Return Values

Value | Description
S_OK | This function always returns S_OK. To determine whether or not the operation was actually successful, check the pfValid out-value.

Related Topics

  • υIDataFunctions::ConvertNumberString
  • υIDataFunctions::Number


IDBStorage Interface

The DBStorage object implements the IDBStorage interface. This interface supports a group of methods that make it possible to read and write data from and to a database table without the explicit use of SQL queries.

The IDBStorage interface supports the following methods:

Method | Description
CommitData | Updates the database table based on the contents of a Dictionary or an OrderForm.
DeleteData | Deletes a row from the database table, based on a description of the data stored in a Dictionary.
DeleteDataKey | Deletes a row of data, based on the provided key value.
GetData | Gets a row of data from the database, based on a specified key value.
get_Mapping | Returns the mapping Dictionary for this IDBStorage instance.
InitStorage | Initializes the DBStorage object. This method must be called before any other DBStorage method, and must not be invoked twice on the same DBStorage object instance.
InsertData | Inserts the contents of a Dictionary into a database table.
LookupData | Retrieves a row of data based on a specified group of name/value pairs.
LookupMultipleData | Retrieves multiple rows of data based on the criteria that you specify.
ProcessData | Unpacks the data stored in the MarshalColumn for a given row, and returns the resulting row in a Dictionary.
put_Mapping | Sets the mapping Dictionary for this DBStorage object instance.


IDBStorage::CommitData

The CommitData method updates the database table based on the contents of a Dictionary or OrderForm.

Syntax

HRESULT CommitData(
VARIANT vtReserved,// in
IDispatch *pdispData// in
);

Parameters

vtReserved
Reserved for future use. CommitData ignores the value of this parameter.
pdispData
An IDispatch interface pointer on the OrderForm or Dictionary that contains the updated data.

Include

<commerce.h>

Library

commerce.lib

Return Value

Value | Description
S_OK | This method always returns S_OK. If the operation is unsuccessful, the pdispData out-value evaluates to NULL.

Related Topic

IDBStorage::InsertData


IDBStorage::DeleteData

The DeleteData method deletes a row from the data source, based on the data stored in a Dictionary object. The IDispatch pointer passed in by the caller is an interface on this Dictionary.

Syntax

HRESULT DeleteData(
VARIANT vtReserved,// in
IDispatch *pdispData// in
);

Parameters

vtReserved
Reserved for future use. This parameter is ignored by DeleteData.
pdispData
An IDispatch pointer on a Dictionary. This Dictionary describes the data to be deleted. The names in this Dictionary identify the columns in a row, and the values identify the values to be inserted into the referenced columns.

Include

<commerce.h>

Return Value

Value | Description
S_OK | The function was successful.
E_INVALIDARG | The pdispData parameter is NULL.

Related Topic

IDBStorage::DeleteDataKey , IDBStorage::CommitData, IDBStorage::InsertData


IDBStorage::DeleteDataKey

The DeleteDataKey method deletes a row of data, based on the provided key value.

Syntax

HRESULT DeleteDataKey(
VARIANT vtReserved,// in
VARIANT vtKey// in
);

Parameters

vtReserved
This parameter is reserved for future use, and is ignored by the current implementation of DeleteDataKey.
vtKey
A VARIANT that contains the key value for the row to delete. This key corresponds to the column designated as the table key in the initial call to IDBStorage::InitStorage. Thus, if the call to InitStorage specifies column “some_column” as the table key, then DeleteDataKey searches “some_column” for the value stored in vtKey, and deletes the corresponding row of data.

Include

<commerce.h>

Return Value

Value | Description
S_OK | The row corresponding to the specified key was deleted.


IDBStorage::GetData

The GetData method retrieves a row of data from the database, based on a specified key value.

Syntax

HRESULT GetData(
VARIANT vtReserved,// in
VARIANT vtKey// in
VARIANT *pvtRet// out
);

Parameters

vtReserved
Reserved for future use. GetData ignores any value stored in this parameter.
vtKey
A VARIANT that contains the key value on which to base the search. GetData searches for this value in the table column specified as the table key in the initial call to InitStorage.
pvtRet
A Dictionary or OrderForm that contains the retrieved row.

Include File

<commerce.h>

Return Values

Value | Description
S_OK | The function succeeded. If the function fails, GetData returns a failure HRESULT, and pvtRet evaluates to NULL.

Related Topic

IDBStorage::CommitData, IDBStorage::InsertData


IDBStorage::get_Mapping

The get_Mapping method returns the mapping Dictionary for this DBStorage object instance.

HRESULT get_Mapping(
IDispatch **ppdispMapping// out
);

Parameters

ppdispMapping
The address of an IDispatch interface pointer on the Dictionary object that contains the mapping values.

Include File

<commerce.h>

Remarks

A mapping Dictionary makes it possible to map the column names in a database table to one or more names that you choose, usually for display to the site visitor. Suppose, for example, that your database table contains a column named “shopper_name”, but that you want to display the contents of this column as the more human-readable “Shopper Name”. Consequently, you initialize a “shopper_name” key in a Dictionary to “Shopper Name”, and pass this Dictionary to put_Mapping. When you call a DBStorage data retrieval method, such as GetData, to read a row of data into a Dictionary, the Dictionary key for the “shopper_name” column reads “Shopper Name”. This new mapping means that you do not have to translate the column name to a more human-readable name before displaying its values to the site visitor; You can simply display the keys and values as they appear in the Dictionary returned by GetData.

Return Value

Value | Description
S_OK | This method always returns S_OK.

Related Topic

IDBStorage::get_Mapping

© 1997-1998 Microsoft Corporation. All rights reserved.


IDBStorage::InitStorage

The InitStorage method initializes a DBStorage object. You must call this method immediately after creating an instance of the DBStorage object, and before calling any other DBStorage object methods.

HRESULT InitStorage(
VARIANT vtDataSourceDSN,// in
BSTR Table,// in
BSTR bstrKey,// in
VARIANT vtProgID,// in
VARIANT vtMarshal,// in
VARIANT vtChanged// in
);

Parameters

vtDataSourceDSN
A VARIANT in which the pdispVal member references a valid IDispatch pointer on a DataSource object, or in which the BSTR pbstrVal member references a data source name (DSN).
bstrTable
A BSTR that references the table on which this DBStorage object instance will operate.
bstrKey
A BSTR that identifies the key for the table identified by Table.
vtProgID
The program identifier (ProgID) for the object to be used to pass data to and from this DBStorage object instance. Accepted values include “Commerce.Dictionary” and “Commerce.OrderForm”.
vtMarshal
The marshal column for the table identified in Table. See the “Remarks” section.
vtChanged
A BSTR VARIANT that specifies the date on which the change was made.

Include

<commerce.h>

Return Values

Value | Description
S_OK | The method succeeded.
E_FAIL | The InitStorage method was invoked twice on the same object instance.
E_INVALIDARG | The bstrTable or bstrKey parameters are NULL. Alternately, the vtDataSourceDSN parameter does not reference a valid Datasource object instance or data source name (DSN).


IDBStorage::InsertData

The InsertData method inserts the contents of a Dictionary object into a database row.

Syntax

HRESULT InsertData(
VARIANT vtReserved,// in
IDispatch *pdispData// in
);

Parameters

vtReserved
Reserved for future use. This parameter is ignored by InsertData.
pdispData
An IDispatch pointer on the Dictionary that contains the data to insert.

Include

<commerce.h>

Return Value

Value | Description
S_OK | This function always returns S_OK. If the call to InsertData is unsuccessful, the ppdispRet out-value evaluates to NULL.

Related Topic

IDBStorage::DeleteData, IDBStorage::DeleteDataKey


IDBStorage::LookupData

The LookupData method retrieves a row of data based on a specified group of name/value pairs, and returns the resulting row of data (if any) in a Dictionary object.

Syntax

HRESULT LookupData(
VARIANT vtReserved,// in
VARIANT *pvtColumns,// in
VARIANT *pvtValues,// in
VARIANT *pvtRet// out
);

Parameters

vtReserved
Reserved for future use. LookupData ignores any value stored in this parameter.
pvtColumns
A VARIANT that identifies the columns in which to search for the data. This VARIANT can be either a SimpleList or a SAFEARRAY.
pvtValues
A VARIANT that identifies the values for which to search. Like the pvtColumns parameter, this parameter can be either a SimpleList or a SAFEARRAY.
pvtRet
If successful, pvtRet Points to a VARIANT that contains the result of the lookup, and this VARIANT’s pdispValue references an IDispatch interface pointer on a Dictionary that contains the row data. Otherwise, pvtRet evaluates to NULL.

Include

<commerce.h>

Return Value

Value | Description
S_OK | This method always returns S_OK. If the call is unsuccessful, the pvtRet out-value evaluates to NULL.

Related Topic

IDBStorage::LookupMultipleData


IDBStorage::LookupMultipleData

The LookupMultipleData retrieves multiple rows of data.

Syntax

HRESULT LookupMultipleData(
VARIANT vtReserved,// in
VARIANT *pvtColumns,// in
VARIANT *pvtValues,// in
VARIANT *pvtRet// out
);

Parameters

vtReserved
Reserved for future use. LookupData ignores any value stored in this parameter.
pvtColumns
A VARIANT that identifies the columns in which to search for the data. This VARIANT can be either a SimpleList or a SAFEARRAY.
pvtValues
A VARIANT that identifies the values for which to search. Like the pvtColumns parameter, this parameter can be either a SimpleList or a SAFEARRAY.
pvtRet
If successful, pvtRet Points to a VARIANT that contains the result of the lookup. This VARIANT’s pdispValue references an IDispatch interface on a SimpleList object that consists of one or more Dictionary objects, one for each row of data returned.

Include File

<commerce.h>

Return Value

Value | Description
S_OK | The function succeeded. If the function fails, an HRESULT indicating failure is returned, and pvtRet is set to NULL.

Related Topic

IDBStorage::LookupData


IDBStorage::ProcessData

The ProcessData method unpacks the data stored in the MarshalColumn for a given row, and returns the resulting row in a Dictionary.

HRESULT ProcessData(
IDispatch *pdispData,// in
IDispatch **ppdispRet// out
);

Parameters

pdispData
An IDispatch pointer on a Dictionary that contains the marshaled data.
ppdispRet
The address of an IDispatch pointer on a Dictionary that contains the unmarshaled data.

Include

<commerce.h>

Return Value

Value | Description
S_OK | This function always returns S_OK. If the call to ProcessData is unsuccessful, the ppdispRet out-value evaluates to NULL.


IDBStorage::put_Mapping

The put_Mapping method sets the mapping Dictionary for this DBStorage object instance. For more information about the mapping Dictionary, see the “Remarks” section below.

HRESULT put_Mapping(
IDispatch *pdispMapping
);

Parameters

pdispMapping
An IDispatch interface pointer on the mapping Dictionary.

Include File

<commerce.h>

Remarks

A mapping Dictionary makes it possible to map the column names in a database table to one or more names that you choose, usually for display to the site visitor. Suppose, for example, that your database table contains a column named “shopper_name”, but that you want to display the contents of this column as the more human-readable “Shopper Name”. Consequently, you initialize a “shopper_name” key in a Dictionary to “Shopper Name”, and pass this Dictionary to put_Mapping. When you call a DBStorage data retrieval method, such as GetData, to read a row of data into a Dictionary, the Dictionary key for the “shopper_name” column reads “Shopper Name”. This new mapping means that you do not have to translate the column name to a more human-readable name before displaying its values to the site visitor; You can simply display the keys and values as they appear in the Dictionary returned by GetData.

Return Values

This function always returns S_OK.

Related Topic

IDBStorage::get_Mapping


IDictionary Interface

The IDictionary interface is a basic collection interface. It supports associating VARIANT values with BSTR names, adding or retrieving multiple name/value pairs at once, and enumeration.

The IDictionary interface supports the following methods.

Method | Purpose
get_Count | Retrieves the number of items in the Dictionary.
GetMultiple | Returns the value of multiple Dictionary items.
get__newEnum | Returns the IUnknown interface pointer for the Dictionary. The caller can use this interface pointer to call QueryInterface for the enumerator for this object.
get_Prefix | Returns the prefix for this IDictionary instance.
get_Value | Returns the value of an IDictionary element.
put_Prefix | Changes the prefix for the current IDictionary instance.
put_Value | Adds an item to the Dictionary, or modifies the value of an existing element.
PutMultiple | Adds or changes multiple items in a Dictionary.

Note

If you call PutMultiple or GetMultiple from VBScript, these methods fail because they require data types that VBScript does not support.


IDictionary::get_Count

The get_Count method identifies the number of elements in a Dictionary object instance.

Syntax

HRESULT get_Count(
long *newVal// out, retval
);

Parameter

newVal
The address of a long integer in which the get_Count method stores the number of elements in the Dictionary.

Include File

<commerce.h>

Return Value

Value | Description
S_OK | The method succeeded.
E_POINTER | The newVal parameter is a NULL pointer.


IDictionary::GetMultiple

The GetMultiple method returns the values of IDictionary elements that you specify.

Syntax

HRESULT GetMultiple(
long cb,//in
const LPOLESTR rgolestr[],// in
VARIANT rgvar[]// out
);

Parameters

cb
A long integer that specifies the number of values to retrieve.
rgolestr
An array of string values that identify the IDictionary elements for which the values should be retrieved.
rgvar
An array of VARIANTs. When GetMultiple returns, this array contains the values associated with the IDictionary elements identified by the rgolestr array.

Include File

<commerce.h>

Return Value

If successful, this method returns S_OK. Otherwise, it returns an HRESULT indicating failure, and the VARIANT array out-value is empty.

Note

Attempting to use this method from VBScript fails because this method requires data type that VBScript does not support.

Related Topic

IDictionary::get_Value


IDictionary::get__newEnum

The get__newEnum method retrieves an enumerator object that implements IEnumVariant on the Dictionary.

Syntax

HRESULT get__newEnum(
IUnknown **ppUnk// out
);

Parameter

ppUnk
IUnknown for an object that implements IEnumVariant on this collection. The caller can call QueryInterface through the returned pointer to retrieve an instance pointer to the IEnumVariant for this object. To retrieve the values associated with these elements, the caller can retrieve the elements in turn using IEnumVariant::Next, and call IDictionary::get_Value on those elements.

Include File

<commerce.h>

Return Value

Value | Meaning
S_OK | The method succeeded.
E_POINTER | The ppUnk parameter references a NULL pointer.
E_OUTOFMEMORY | Memory failure.


IDictionary::get_Prefix

The get_Prefix method retrieves the prefix for this IDictionary instance and stores it in a BSTR variable that the caller allocates. The prefix designates the character that indicates which IDictionary entries should not be persisted. The default value for this character is an underscore (_).

Syntax

HRESULT get_Prefix(
BSTR *pbstr// out
);

Parameter

pbstr
The address of the BSTR to which the prefix will be returned.

Include File

<commerce.h>

Return Value

Value | Meaning
S_OK | The method succeeded.
E_POINTER | The pbstr parameter references a NULL pointer.
E_OUTOFMEMORY | Memory could not be allocated for the prefix.

Related Topic

IDictionary::put_Prefix


IDictionary::get_Value

The get_Value method retrieves the value of the specified Dictionary element.

Syntax

HRESULT get_Value(
BSTR bstrName,// in
VARIANT *pvarNew// out, retval
);

Parameters

bstrName
The name of the Dictionary element for which to retrieve a value.
pvarNew
The address of a VARIANT to which get_Value returns the value of the element specified by bstrName.

Include File

<commerce.h>

Return Value

If successful, this method returns S_OK. Otherwise, it returns an HRESULT indicating failure, and the pvarNew out-value is set to NULL.

Related Topic

IDictionary::put_Value


IDictionary::put_Prefix

The put_Prefix method changes the prefix for an IDictionary instance. The prefix for an IDictionary instance determines which Dictionary entries are not persisted. By default, the IDictionary prefix is an underscore character (_), so that IDictonary names that begin with an underscore are not persisted.

Syntax

HRESULT put_Prefix(
BSTR bstr// in
);

Parameter

bstr
A variable of type BSTR that contains the new prefix.

Include File

<commerce.h>

Return Value

Value | Meaning
S_OK | The method succeeded.
E_POINTER | The bstr parameter is NULL.

Related Topic

IDictionary::get_Prefix


IDictionary::put_Value

The put_Value method adds a new element to a Dictionary, or reinitializes an existing element.

HRESULT put_Value(
BSTR bstrName,// in
VARIANT varNew// in
);

Parameters

bstrName
The name of the element to add or reinitialize.
varNew
The value to which the element should be initialized.

Include File

<commerce.h>

Return Value

Value | Meaning
S_OK | The new element was added, or the value of an existing element was changed.
E_OUTOFMEMORY | Memory could not be allocated for a new element.

Related Topic

IDictionary::get_Value


IDictionary::PutMultiple

The PutMultiple method adds specified elements to the IDictionary collection, and initializes these elements to the specified values.

Syntax

HRESULT PutMultiple(
long cb,// in
const LPOLESTR rgolestr[],// in
const VARIANT rgvar[]// in
);

Parameters

cb
Identifies the number of elements in the rgolestr and rgvar arrays.
rgolestr
Contains the names of the elements to add to the IDictionary collection.
rgvar
Contains the values to add to the IDictionary collection.

Include File

<commerce.h>

Return Value

If successful, this method returns S_OK. Otherwise, it returns an HRESULT that indicates failure.

Remarks

A one-to-one mapping exists between the elements of the rgolestr and rgvar arrays. This means that rgolestr[n] is added to the IDictionary collection and is initialized to rgvar[n].

If the element specified by rgolestr[n] is already in the Dictionary, the value associated with the element is overwritten with the value stored in rgvar[n].

Note

This method cannot be invoked from VBScript because the method requires data types that VBScript does not support.

Related Topic

IDictionary::GetMultiple


IMSCSMessageManager_3_0 Interface

The Microsoft® Commerce Server version 3.0 MessageManager object implements the IMSCSMessageManager_3_0 interface, which you can use to add or retrieve messages to or from the MessageManager. An instance pointer to the MessageManager object for a site is passed to pipeline components in the pipe context Dictionary.

The IMSCSMessageManager_3_0 interface implements the following methods.

Method | Description
AddLanguage | Adds a language to the MessageManager object.
AddMessage | Adds a message to the specified language.
get_defaultLanguage | Returns the default language for this MessageManager instance.
GetMessage | Returns the text associated with a specified message identifier.
put_defaultLanguage | Sets the default language for this MessageManager instance.


IMSCSMessageManger_3_0::AddLanguage

The AddLanguage method adds a language to the MessageManager object.

Syntax

HRESULT AddLanguage(
BSTR bstrLanguage,
);

Parameters

bstrLanguage
A string that identifies the language name.

Include File

<commerce.h>

Return Values

Value | Meaning
S_OK | The new element was added, or the value of an existing element was changed.
E_OUTOFMEMORY | Memory could not be allocated for a new element.

Related Topic

IMSCSMessageManager_3_0::AddMessage


IMSCSMessageManager_3_0::AddMessage

The AddMessage method adds a message to a specified language.

Syntax

HRESULT AddMessage(
BSTR bstrName,// in
BSTR bstrMessage,// in
VARIANT vtLanguage// in
);

Parameters

bstrName
A string name for the message to add. This name must be a name that is known to the order processing pipeline (OPP) component that will use the message to identify an error condition.
bstrMessage
The text of the message to add.
vtLanguage
A BSTR VARIANT that identifies the language with which to associate this message, or a long VARIANT that identifies a locale constant.

Include File

<commerce.h>

Return Value

Value | Description
E_FAIL | The language specified for this message does not exist in the MessageManager.
S_OK | The method succeeded.

Related Topic

IMSCSMessageManager_3_0::AddLanguage


IMSCSMessageManager_3_0::get_defaultLanguage

The get_defaultLanguage method returns a BSTR that contains the default language for the MessageManager.

HRESULT get_defaultLanguage(
BSTR *pstr// out
);

Parameter

pstr
A BSTR that contains the name of the language.

Include File

<commerce.h>

Return Value

Value | Description
S_OK | The method succeeded, and the BSTR out-value contains the name of the default language.
E_FAIL | The method failed, and the BSTR out-value is NULL.

Related Topic

IMSCSMessageManager_3_0::put_defaultLanguage


IMSCSMessageManager_3_0::GetMessage

The GetMessage method returns the specified message, based on its identifier and the language with which it is associated.

Syntax

HRESULT GetMessage(
BSTR bstrName,// in
VARIANT vtLanguage,// in
BSTR *Message// out
);

Parameters

bstrName
A string that identifies the message to retrieve.
vtLanguage
A VARIANT that identifies the language with which the requested message is associated in the MessageManager. This VARIANT must be either a NULL, empty, or BSTR VARIANT. If NULL or empty, GetMessage returns the requested message for the default language.
Message
The address of a BSTR in which GetMessage stores the text of the requested message.

Include File

<commerce.h>

Return Values

Value | Description
S_OK | The method succeeded, and Message references the text of the message.
E_INVALIDARG | The vtLanguage was not NULL, empty, or a BSTR.

Related Topic

IMSCSMessageManager_3_0::AddMessage


IMSCSMessageManager_3_0::put_defaultLanguage

The put_defaultLanguage method specifies the default language for the message set. The language that you specify must be one that you have added to the message set through a previous call to put_defaultLanguage.

Syntax

HRESULT put_defaultLanguage(
BSTR bstr
);

Parameter

bstr
Identifies the language to make the default for the message set.

Include File

<commerce.h>

Return Values

Value | Description
S_OK | The default language was successfully set.
E_INVALIDARG | The bstr parameter is empty.
E_OUTOFMEMORY | Memory could not be allocated to store the default language.

Related Topic

IMSCSMessageManager_3_0::get_defaultLanguage


IMSCSStandardSManager_3_0 Interface

The IMSCSStandardSManager_3_0 interface supports methods that provide for the creation, retrieval and storage of shopper IDs.

This interface supports the following methods:

Method | Description
CreateShopperID | Creates a unique identifier for the current shopper, and returns the shopper ID in a BSTR variable.
GetShopperID | Retrieves the shopper ID for the current shopper.
InitManager | Initializes the interface with settings that determine how shopper IDs will be stored.
PutShopperID | Writes a shopper ID to the user’s system or to a URL.


IMSCSStandardSManager_3_0::CreateShopperID

The CreateShopperID method creates a shopper ID and returns the shopper ID in a BSTR variable.

Syntax

HRESULT CreateShopperID(
BSTR *pbstrRet// out, retval
);

Parameters

pbstrRet
Points to a BSTR variable, which the CreateShopperID method initializes to the new shopper ID.

Return Value

If CreateShopperID cannot create the shopper ID, the method returns an HRESULT indicating failure, and initializes the pbstrRet out-value to NULL.

Include

<commerce.h>

Return Value

This method returns an HRESULT value.

Note

You must call the IMSCSStandardSManager::InitManager method before calling CreateShopperID.

Related Topic

IMSCSStandardSManager_3_0::InitManager, IMSCSStandardSManager::PutShopperID


IMSCSStandardSManager_3_0::GetShopperID

The GetShopperID method retrieves the current shopper’s shopper ID from a cookie or URL and returns it in a BSTR VARIANT.

Whether GetShopperID locates the shopper ID in a cookie or a URL depends upon the options that you specified in a previous call to IMSCSStandardSManager_3_0::InitManager.

Syntax

HRESULT GetShopperID(
IDispatch *pdispContext,// in
VARIANT *pvtReturn// out, retval
);

Parameters

pdispContext
An IDispatch interface on the pipe context Dictionary. GetShopperID uses this interface pointer to get the IIS Scripting Context.
pvtReturn
If the method is successful, pvtReturn references a BSTR VARIANT that contains the current shopper’s shopper ID. Otherwise, this pointer is NULL.

Include

<commerce.h>

Return Value

If successful, GetShopperID returns S_OK; otherwise, it returns an HRESULT that indicates failure, and sets pvtReturn to NULL.

Related Topic

IMSCSStandardSManager_3_0::CreateShopperID, IMSCSStandardSManager_3_0::PutShopperID


IMSCSStandardSManager_3_0::InitManager

The InitManager method initializes the StandardSManager with settings that determine how the StandardSManager stores and retrieves shopper IDs from the user’s hard disk. or from a URL.

Syntax

HRESULT InitManager(
BSTR bstStoreKey,// in
BSTR bstrMode// in
);

Parameters

bstrStoreKey
The name of the site.
bstrMode
The mode in which to run the StandardSManager. The mode determines how the PutShopperID and GetShopperID methods store and retrieve the shopper ID.

The following four options are available.
Mode | Description
cookie | PutShopperID stores the shopper ID in a cookie on the client system. GetShopperID retrieves this cookie.
url | PutShopperID appends the shopper ID to the URL, using the MCSSIDUrlKey as the name part of the URL variable. GetShopperID retrieves the shopper ID from the URL.
cookieurl | PutShopperID stores the shopper ID in a cookie on the client system and in the URL. GetShopperID first attempts to retrieve the shopper ID from the cookie, and then from the URL.
urlcookie | PutShopperID stores the shopper ID in a URL, and stores it as a cookie on the client system. GetShopperID first attempts to retrieve the shopper ID from the URL, then from the cookie.

Include

<commerce.h>

Return Value

This method always returns S_OK.


IMSCSStandardSManager_3_0::PutShopperID

The PutShopperID method stores the shopper ID generated by CreateShopperID as a cookie on the user’s hard disk, or as a URL argument. The way in which PutShopperID stores the shopper ID depends upon the mode in which the StandardSManager was initialized.

Syntax

HRESULT PutShopperID(
IDispatch *pdispContext,// in
BSTR bstr// in
);

Parameters

pdispContext
An IDispatch interface pointer on the pipe context Dictionary.
bstr
A BSTR that contains the shopper ID created through a previous call to GetShopperID.

Related Topic

IMSCSStandardSManager_3_0::GetShopperID


IOrderForm Interface

The IOrderForm interface, which is implemented by the OrderForm object, consists of a set of SimpleList and Dictionary objects that are designed to contain a detailed summary of purchase and shopper information. Internally, the OrderForm object implements both ISimpleList and IDictionary.

The IOrderForm interface supports the following methods:

Method | Description
AddItem | Adds an item to the OrderForm’s Items list.
ClearItems | Clears the OrderForm’s Items list.
ClearOrderForm | Clears the OrderForm Dictionary.


IOrderForm::AddItem

The AddItem method adds an item to the OrderForm object's Items collection, including the item's SKU, quantity, and placed price. The Items collection is an instantiated ISimpleList interface pointer to a SimpleList object. A SimpleList object is simply an array of VARIANTs. This array consists of IDictionary interface pointers to the Dictionary objects that store the item information that you pass to AddItem.

Syntax

HRESULT AddItem(
VARIANT varSKU,// in
long lCount,// in
long lPlacedPrice,// in
IDispatch **ppdispItem// out
);

Parameters

varSKU
A VARIANT that contains the SKU of the item to add.
lCount
The quantity of the item identified by varSKU.
lPlacedPrice
The placed price of the item identified by varSKU.
ppdispItem
If AddItem is successful, ppdispItem contains the address of an instance pointer to the IDispatch interface for the Dictionary that contains the added item, and AddItem calls AddRef on that Dictionary; otherwise, NULL.

Include File

<commerce.h>

Return Value

Internally, the AddItem method uses ISimpleList::Add and IDictionary::put_Value methods to add the Dictionary that contains the item information to the SimpleList. Consequently, if IOrderForm::AddItem fails, the returned HRESULT can be any HRESULT returned by these methods. If successful, AddItem returns S_OK.

Related Topic

IOrderForm::ClearItems


IOrderForm::ClearItems

The ClearItems method empties the Items Dictionary in an OrderForm.

Syntax

HRESULT ClearItems();

Parameters

None.

Include File

<commerce.h>

Return Value

After removing the Items collection, ClearItems creates a new ISimpleList instance that represents an empty Items collection. Subsequent additions to the Items collection are made internally through this ISimpleList interface pointer. The HRESULT returned by ClearItems is the result of ClearItems’ attempt to instantiate the new ISimpleList interface pointer.

Related Topic

IOrderForm::AddItem


IOrderForm::ClearOrderForm

The ClearOrderForm method empties the OrderForm Dictionary, then creates new instances of the OrderForm's internal collections, which include the ISimpleList Items collection, the ISimpleList _Basket_Errors collection, the ISimpleList _Purchase_Errors collection, and the verify_with collection. These collections are empty.

Syntax

HRESULT ClearOrderForm();

Parameters

None.

Include File

<commerce.h>

Return Value

If ClearOrderForm successfully instantiates these ISimpleList pointers, ClearOrderForm returns S_OK; otherwise, E_FAIL.

Related Topic

IOrderForm::ClearItems


IOrderPipeline Interface

This interface, derived from IDispatch, is the execution interface for the pipeline object. The role of the pipeline is to present the OrderForm to the sequence of components so that they can read and write data to and from the order, and transform the data therein. A component may capture information from the order and transmit it to some other back-end data store (encapsulated by the component).

Because this is an IDispatch interface, the methods may be called from an Active Server Pages–based HTML page.

The IOrderPipeline interface supports the following methods.

Method | description
EnableDesign | Prepares the pipeline for execution in design or execution mode.
LoadPipe | Loads a pipeline configuration (.pcf) file.
OrderExecute | Executes the order processing pipeline (OPP) or Commerce Interchange Pipeline (CIP).
SetLogFile | Sets the log file for the pipeline.


IOrderPipeline::EnableDesign

The EnableDesign method is used to prepare the pipeline for execution in one of two modes: design mode or execution mode. Execution mode (the default) is analagous to production mode, and is the default mode in which a pipeline starts.

The pipeline passes the design mode to the individual components (see IPipelineComponent::EnableDesign).

Only administrative tools should call this method. There is no reason to call it when executing a pipeline.

Syntax

HRESULT EnableDesign(
BOOL fEnable// in
);

Parameters

fEnable
Indicates whether the pipeline should be run in design mode (True) or execution mode (False).

Include File

<pipeline.h>
<pipecomp.h>

Return Value

The method returns an HRESULT value.

Example

CoCreateInstance( ...., &pPipe )
pPipe->EnableDesign(TRUE);
pPipe->IPF::Load( filename );


IOrderPipeline::LoadPipe

The LoadPipe method is an Automation function to be used in those environments where IPersistFile::Load is not available. The function is used to bind to the pipeline’s configuration file. In Commerce Server, this file has a .pcf extension.

Syntax

HRESULT LoadPipe (
BSTR pszFileName// in
);

Parameters

pszFileName
Full path to the pipeline configuration file.

Include File

<pipeline.h>
<pipecomp.h>

Return Value

Value | Description
S_OK | Function was successful.
S_FALSE | Operation failed.


IOrderPipeline::OrderExecute

The OrderExecute method runs the order processing pipeline (OPP).

Syntax

HRESULT IOrderPipeline::OrderExecute(
long lMode// in
IDispatch *pDispOrder// in
IDispatch *pDispContext// in
long lFlags// in
long *plErrorLevel// out, retval
);

Parameters

lMode
The execution mode parameter. This parameter can be one of the following values:
  • υOPPMODE_PRODUCT = 1
  • υOPPMODE_PLAN = 2
  • υOPPMODE_PURCHASE = 4

This parameter indicates the type of operation being conducted on the OrderForm object. For Commerce Server version 3.0, this parameter is set to zero (0) by default, and is ignored.

pDispOrder
A pointer to the OrderForm object.
pDispContext
A pointer to the PipeContext dictionary. This is a Dictionary object that contains pointers to the MessageManager object, ShopperManager object, Content object (for Commerce Server 2.0 sites), and language information.
lFlags
This parameter is not used, and should be zero (0).
plErrorLevel
Points to a long integer in which the component returns status information. This parameter can be one of the following values.
Value | Meaning
1 | No errors, pipeline executed successfully.
2 | Basket or purchase errors for this operation.
3 | Serious errors in execution of this pipeline.

This error information is meant to supplement the HRESULT information that is returned. The pipeline maps errors returned from components (E_xxxx errors) to an error level of 3.

Include File

<pipeline.h>
<pipecomp.h>

Return Value

Value | Description
S_OK | The order processing pipeline (OPP) or Commerce Interchange Pipeline (CIP) was executed successfully.
E_INVALIDARG | The pdispErrorLevel or pdispOrderForm parameters are NULL.


IOrderPipeline::SetLogFile

The SetLogFile method enables order processing pipeline (OPP) logging. This is useful for debugging purposes. Specifying any log file enables logging. To turn it off, set bstrFileName to Null.

Syntax

HRESULT SetLogFile (
BSTR bstrFileName// in
);

Parameter

bstrFileName
Full path to the pipeline log file. This parameter must specify a location in which you have Write permission; otherwise, the log file creation will fail without warning.

Include File

<pipeline.h>
<pipecomp.h>

Return Value

Value | Description
S_OK | The log file was set.
E_INVALIDARG | The bstrFilename parameter designates an invalid or nonexistent file.


IPersistStreamInit Interface

The IPersistStreamInit interface is a standard Win32® OLE interface. This interface is typically implemented on any object that needs to support initialized stream-based persistence, regardless of whatever else the object does. In the context of the order processing pipeline (OPP), it is used to load/save the component configuration in the pipeline configuration file (the pipeline will call on this interface as appropriate). For information about IPersistStreamInit, see the OLE Programmer’s Reference.


IPersistStreamInit::IsDirty

The IPersistStreamInit::IsDirty method checks whether an object has changed since it was last saved so that you can avoid losing information in objects that have not been saved. The dirty flag for an object is conditionally cleared in the IPersistStreamInit::Save method.

Syntax

HRESULT IsDirty(void);

Parameters

None.

Include File

<pipeline.h>
<pipecomp.h>

Return Value

The method returns an HRESULT value.


IPersistStreamInit::Load

The IPersistStreamInit::Load method loads an object from its associated stream. The seek pointer is set as it was in the most recent IPersistStreamInit::Save method. This method can seek and read from the stream, but cannot write to it.

On exit, the seek pointer must be in the same position it was in on entry, immediately past the end of the data.

Syntax

HRESULT Load(
IStream *pStm// in
);

Parameter

pStm
Pointer to the IStream interface on the stream from which the object should be loaded.

Include File

<pipeline.h>
<pipecomp.h>

Return Value

The method returns an HRESULT value.


IPersistStreamInit::Save

The IPersistStreamInit::Save method saves an object into the specified stream and indicates whether the object should reset its dirty flag.

The seek pointer is positioned at the location in the stream at which the object should begin writing its data. The object calls the IStream::Write method to write its data.

On exit, the seek pointer must be positioned immediately past the object data. The position of the seek pointer is undefined if an error returns.

Syntax

HRESULT Save(
IStream *pStm// in
BOOL fClearDirty// in
);

Parameters

pStm
Pointer to the IStream interface on the stream into which the object should be saved.
fClearDirty
Indicates whether to clear the dirty flag after the save is complete. If True, the flag should be cleared. If False, the flag should be left unchanged.

Include File

<pipeline.h>
<pipecomp.h>

Return Value

The method returns an HRESULT value.


IPersistStreamInit::GetSizeMax

The IPersistStreamInit::GetSizeMax method returns the size needed to save an object. You can call this method to determine the size and set the necessary buffers before calling the IPersistStreamInit::Save method.

Syntax

HRESULT GetSizeMax(
ULARGE_INTEGER *pcbSize// out
);

Parameter

pcbSize
Pointer to a 64-bit unsigned integer value, indicating the size in bytes of the stream needed to save this object.

Include File

<pipeline.h>
<pipecomp.h>

Return Value

The method returns an HRESULT value.


IPersistStreamInit::InitNew

The IPersistStreamInit::InitNew method initializes the object to a default state. This method is called instead of IPersistStreamInit::Load.

Syntax

HRESULT InitNew(void);

Parameters

None.

Include File

<pipeline.h>
<pipecomp.h>

Return Value

The method returns an HRESULT value.


IPersistXML Interface

The IPersistXML interface is implemented by an object that needs to read or write its data as XML. In the context of the order processing pipeline (OPP), it is used to map the contents of a business data object as XML data. This work is performed by the Commerce Interchange MapToXML and MapFromXML components. These components can map the data of any object that implements IPersistXML.

The IPersistXML interface supports the following methods:

Method | Description
LoadXML | Loads a component’s data from a BSTR.
SaveXML | Saves a component’s data as XML.


IPersistXML::LoadXML

The LoadXML method loads XML data from a BSTR.

Syntax

HRESULT LoadXML(
long Reserved,// in
BSTR bstrXML// in
);

Parameters

Reserved
This value is not used.
bstrXML
A BSTR that contains the XML data.

Include File

<pipeline.h>
<pipecomp.h>

Return Value

This method returns an HRESULT value.


IPersistXML::SaveXML

The SaveXML data saves the contents of a BSTR as XML data.

Syntax

HRESULT SaveXML(
long Reserved,// in
BSTR *bstrXML// out, retval
);

Parameters

Reserved
This value is not used.
bstrXML
The address of a BSTR in which this method returns its persistent data formatted as XML.

Include File

<pipeline.h>
<pipecomp.h>

Return Value

This method returns an HRESULT value.


IPipeline Interface

This interface, derived from IDispatch, is the execution interface for MtsPipeline and MtsTxPipeline objects. The role of the pipeline is to present the OrderForm to the sequence of components so that they can read and write data to and from the order, and transform the data therein. A component may capture information from the order and transmit it to some other back-end data store (encapsulated by the component).

Because this is an IDispatch interface, the methods may be called from an Active Server Pages–based HTML page.

To get an instance pointer on a component’s IPipeline interface, call CoCreateInstance, specifying the class identifier (CLSID) for the MtsPipeline or MtsOrderPipeline objects, and passing in the address of a pointer to IPipeline.

The IPipeline interface supports the following methods:

Method | description
EnableDesign | Prepares the pipeline for execution in design or execution mode.
LoadPipe | Loads a pipeline configuration (.pcf) file.
OrderExecute | Executes the order processing pipeline (OPP) or Commerce Interchange Pipeline (CIP).
SetLogFile | Sets the log file for the pipeline.


IPipeline::EnableDesign

The EnableDesign method is used to prepare the pipeline for execution in one of two modes: design mode or execution mode. Execution mode (the default) is analagous to production mode, and is the default mode in which a pipeline starts.

The pipeline passes the design mode to the individual components (see IPipelineComponent::EnableDesign).

Only administrative tools should call this method. There is no reason to call it when executing a pipeline.

Syntax

HRESULT EnableDesign(
BOOL fEnable// in
);

Parameters

fEnable
Indicates whether the pipeline should be run in design mode (True) or execution mode (False).

Include File

<pipeline.h>
<pipecomp.h>

Return Value

Value | Description
S_OK | The method succeeded.


IPipeline::LoadPipe

The LoadPipe method is an Automation function to be used in those environments where IPersistFile::Load is not available. The function is used to bind to the pipeline’s configuration file. In Commerce Server, this file has a .pcf extension.

Syntax

HRESULT LoadPipe (
BSTR pszFileName// in
);

Parameters

pszFileName
Full path to the pipeline configuration file.

Include File

<pipeline.h>
<pipecomp.h>

Return Value

Value | Description
S_OK | Function was successful.
S_FALSE | Operation failed.


IPipeline::OrderExecute

The OrderExecute method runs the order processing pipeline (OPP) or Commerce Interchange Pipeline (CIP).

Syntax

HRESULT IPipeline::OrderExecute(
long lMode// in
IDispatch *pDispOrder// in
IDispatch *pDispContext// in
long lFlags// in
long *plErrorLevel// out, retval
);

Parameters

lMode
The execution mode parameter. This parameter can be one of the following values:
  • υOPPMODE_PRODUCT = 1
  • υOPPMODE_PLAN = 2
  • υOPPMODE_PURCHASE = 4

This parameter indicates the type of operation being conducted on the OrderForm or Dictionary object. In Commerce Server version 3.0, this parameter is ignored.

pDispOrder
A pointer to the OrderForm or Transport Dictionary object.
pDispContext
A pointer to the pipe context Dictionary. This is a Dictionary object that contains pointers to the MessageManager object, ShopperManager object, Content object, and language information.
lFlags
This parameter should be zero (0).
plErrorLevel
Points to a long integer in which the component returns status information. This parameter can be one of the following values.
Value | Meaning
1 | No errors, pipeline executed successfully.
2 | Basket or purchase errors for this operation.
3 | Serious errors in execution of this pipeline.

This error information is meant to supplement the HRESULT information that is returned. The pipeline maps errors returned from components (E_xxxx errors) to an error level of 2.

Include File

<pipeline.h>
<pipecomp.h>

Return Value

Value | Description
S_OK | The order processing pipeline (OPP) or Commerce Interchange Pipeline (CIP) was executed successfully.
E_INVALIDARG | The pdispErrorLevel or pdispOrderForm parameters are NULL.


IPipeline::SetLogFile

The SetLogFile method enables order processing pipeline (OPP) logging. This is useful for debugging purposes. Specifying any log file enables logging. To turn it off, set bstrFileName to Null.

Syntax

HRESULT SetLogFile (
BSTR bstrFileName// in
);

Parameter

bstrFileName
Full path to the pipeline log file. This parameter must specify a location in which you have Write permission; otherwise, the log file creation will fail without warning.

Include File

<pipeline.h>
<pipecomp.h>

Return Value

Value | Description
S_OK | The log file was set.
E_INVALIDARG | The bstrFilename parameter designates an invalid or nonexistent file.


IPipelineComponent Interface

All pipeline components must implement the IPipelineComponent interface, passing an OrderForm object interface pointer between each component. If a component returns an error, the pipeline terminates execution and returns an error to the caller.

The IPipelineComponent interface defines the following methods:

Method | Description
Execute | The entry point at which the order processing pipeline (OPP) or Commerce Interchange Pipeline (CIP) begins executing the component.
EnableDesign | Sets the design mode on the component.


IPipelineComponent::Execute

This method executes a pipeline component.

Syntax

HRESULT Execute(
IDispatch *pDispOrder// in
IDispatch *pDispContext// in
long lFlags// in
long *plErrorLevel// out, retval
);

Parameters

pDispOrder
A pointer to the OrderForm object.
pDispContext
A pointer to the Context object. This is a Dictionary object that contains pointers to the MessageManager object, ShopperManager object, Content object, and language information.
lFlags
Reserved. This parameter should be zero (0).
plErrorLevel
Flag that indicates what level of errors is tolerated. This parameter can be one of the following values.
Value | Meaning
0 | No errors, component executed successfully.
1 | Basket or purchase errors for this operation.
2 | Serious errors in execution of this component.

This error information is meant to supplement the HRESULT information that is returned. The pipeline maps errors returned from components (E_xxxx errors) to an error level of 2.

Include File

<pipeline.h>
<pipecomp.h>

Return Value

The method returns an HRESULT value.


IPipelineComponent::EnableDesign

The EnableDesign method is used to prepare the component for execution in one of two modes: design mode or execution mode. In design mode, which is useful for running the Pipeline Editor, errors are more easily tolerated. Execution mode (the default) is analagous to production mode.

Syntax

HRESULT EnableDesign(
BOOL fEnable// in
);

Parameter

fEnable
Indicates whether the component should be run in design mode (True) or execution mode (False).

Include File

<pipeline.h>
<pipecomp.h>

Return Value

The method returns an HRESULT value.


IPipelineComponentAdmin Interface

To support third-party components in the system, components must provide user interface code. IPipelineComponentAdmin is provided as a potential interface for use between the component and the component user interface. Use of this or any other interface is entirely up to the component writer.

The IPipelineComponentAdmin interface defines the following methods:

Method | Description
GetConfigData | Returns a Dictionary that contains a component’s configuration settings.
SetConfigData | Sets the configuration settings on a component using the contents of a Dictionary.


IPipelineComponentAdmin::GetConfigData

The GetConfigData method returns an IDictionary pointer for the user interface to read the configuration data for the component.

Syntax

HRESULT GetConfigData(
IDispatch **ppDict// out
);

Parameter

ppDict
Pointer to an object from which the user interface can read the configuration data (typically using IDictionary).

Include File

<pipeline.h>
<pipecomp.h>

Return Value

The method returns an HRESULT value.

Related Topic

IPipelineComponentAdmin::SetConfigData


IPipelineComponentAdmin::SetConfigData

The SetConfigData method takes a pointer to an object containing the configuration information for the component. This object must implement IDictionary.

Syntax

HRESULT SetConfigData(
IDispatch *pDict// in
);

Parameter

pDict
Interface pointer on the object containing the configuration information.

Include File

<pipeline.h>
<pipecomp.h>

Return Value

The method returns an HRESULT value.

Related Topic

IPipelineComponentAdmin::GetConfigData


IPipelineComponentDescription Interface

The IPipelineComponentDescription interface makes it possible for pipeline components to identify the values that they read from the pipe context, and the name/value pairs that they read or write from or to the OrderForm (for order processing pipeline components) or Dictionary (for Commerce Interchange Pipeline (CIP) components).

Although pipeline components are not required to implement IPipelineComponentDescription, implementing this interface makes it possible for the Commerce Server Pipeline Editor to identify and display the elements that your component reads or writes. This information can aid store builders who are troubleshooting a pipeline configuration.

The IPipelineComponentDescription interface supports the following methods:

Method | Description
ContextValuesRead | Returns a SAFEARRAY VARIANT that identifies the pipe context values that the component reads.
ValuesRead | Returns a SAFEARRAY VARIANT that identifies the values that the component reads.
ValuesWritten | Returns a SAFEARRAY VARIANT that identifies the values that the component writes.

The methods defined in the IPipelineComponentDescription interface all take a single parameter: the address of a VARIANT out-value. The VARIANT that IPipelineComponentDescription method implementations store in this address must contain a safearray of VARIANTs that contain a BSTR. These BSTR variables identify the values read from or written to the pipe context or the OrderForm. Because the VARIANTs in this safearray contain simple BSTR variables, you can conceivably store any kind of string information in these BSTRs. However, for the sake of aiding store developers who are attempting to troubleshoot their pipeline configurations, it is recommended that you initialize these BSTRs to reference elements of only the pipe context, OPP OrderForm, or CIP Dictionary.


IPipelineComponentDescription::ContextValuesRead

The ContextValuesRead method returns a VARIANT that contains a safearray of VARIANTs. Each of the VARIANTs in this safearray contains a BSTR that identifies the pipe context elements that the component reads.

Syntax

HRESULT ContextValuesRead(
VARIANT *pVar// out, retval
);

Parameter

pvar
The address to which the method returns a VARIANT. This VARIANT should contain a safearray of VARIANTs, each of which contains a BSTR that identifies the elements that a component reads from the pipe context.

Include File

<pipeline.h>
<pipecomp.h>

Return Value

If the function implementation does not return S_OK, the Commerce Server Pipeline Editor ignores the contents of the returned VARIANT.


IPipelineComponentDescription::ValuesRead

The ValuesRead method identifies the name/value pairs that a component reads from the OrderForm.

Syntax

HRESULT ValuesRead(
BSTR *pbstrRead
);

Parameter

pvar
The address to which the method returns a VARIANT. This VARIANT should contain a safearray of VARIANTs, each of which contains a BSTR that identifies the name/value pairs that a component reads from the OrderForm.

Include File

<pipeline.h>
<pipecomp.h>

Return Value

If the function implementation does not return S_OK, the Commerce Server Pipeline Editor ignores the contents of the returned VARIANT.

Related Topic

IPipelineComponentDescription::ValuesWritten


IPipelineComponentDescription::ValuesWritten

The ValuesWritten method identifies the name/value pairs that a component modifies in the OrderForm.

Syntax

HRESULT ValuesWritten(
VAIRANT *pvar// out, retval
);

Parameter

pvar
The address to which the method returns a VARIANT. This VARIANT should contain a safearray of VARIANTs, each of which contains a BSTR that identifies the modified name/value pairs.

Include File

<pipeline.h>
<pipecomp.h>

Return Value

If the function implementation does not return S_OK, the Commerce Server Pipeline Editor ignores the contents of the returned VARIANT.

Related Topic

IPipelineComponentDescription::ValuesRead


ISpecifyPropertyPages Interface

The ISpecifyPropertyPages interface is a standard Win32 OLE interface. Implement it to allow the pipeline administration tool to invoke the component’s property page user interface. For more information about ISpecifyPropertyPages, see the OLE Programmer’s Reference.


ISpecifyPropertyPages::GetPages

The GetPages method fills a counted array of universally unique identifier (UUID values where each UUID specifies the class identifier (CLSID) of a particular property page that can be displayed in the property sheet for this object.

The CAUUID structure is caller-allocated, but is not initialized by the caller. The ISpecifyPropertyPages::GetPages method fills the cElements field in the CAUUID structure. This method also allocates memory for the array pointed to by the pElems field in CAUUID using CoTaskMemAlloc. Then, it fills the newly allocated array. After this method returns successfully, the structure contains a counted array of UUIDs, each UUID specifying a property page CLSID.

Syntax

HRESULT GetPages(
CAUUID *pPages// out
);

Parameter

pPages
Pointer to a caller-allocated CAUUID structure that must be initialized and filled before returning. The pElems field in the CAUUID structure is allocated by the callee with CoTaskMemAlloc and freed by the caller with CoTaskMemFree.

\

Return Value

The method returns an HRESULT value.

Remarks

The CAUUID structure is defined as follows:

typedef struct tagCAUUID
{
ULONGcElems;
GUID FAR *pElems;
} CAUUID;

cElems
Size of the array pointed to by pElems.
pElems
Pointer to an array of UUID values, each of which specifies a CLSID of a particular property page. This array is allocated by the callee using CoTaskMemAlloc and is freed by the caller using CoTaskMemFree.


ISimpleList Interface

A SimpleList is an object that implements the ISimpleList interface. This interface supports the creation and maintenance of an array of VARIANTs.

The ISimpleList interface defines the following methods.

Method | Purpose
Add | Appends a VARIANT to the SimpleList.
Delete | Deletes a VARIANT from the SimpleList.
get__NewEnum | Returns an IUnknown pointer for this SimpleList's enumerator object.
get_Item | Initializes a VARIANT for the item stored at the specified index, and returns the address of this VARIANT.
get_Count | Returns the size of the SimpleList's internal array of VARIANTs.
put_Item | Adds an initialized VARIANT to the SimpleList at the specified index.
putref_Item | Adds an object to the SimpleList at the specified index.


ISimpleList::Add

The ISimpleList::Add method appends a VARIANT to the SimpleList.

Syntax

HRESULT Add(
VARIANT *pVar// in
);

Parameter

pVar
A pointer to the VARIANT to append to the SimpleList.

Include File

<commerce.h>

Return Value

Value | Meaning
S_OK | The call succeeded.
E_OUTOFMEMORY | ISimpleList::Add dynamically allocates a VARIANT into which it copies the VARIANT that you specify. This VARIANT could not be allocated.

Related Topic

ISimpleList::Delete


ISimpleList::Delete

The ISimpleList::Delete method deletes a VARIANT from the SimpleList.

Syntax

HRESULT Delete(
long nIndex// in
);

Parameter

nIndex
The index of the item to delete.

Include File

<commerce.h>

Return Value

Value | Meaning
S_OK | The VARIANT at the specified index was deleted.
DISP_E_BADINDEX | The nIndex parameter contains a value greater than the size of the SimpleList or less than zero.

Related Topic

ISimpleList::Add


ISimpleList::get_Count

The ISimpleList::get_Count method returns the address of a long that contains the number of items in the SimpleList.

Syntax

HRESULT get_Count(
long *plCount// out
);

Parameter

plCount
Points to a long integer in which to return the number of items in the SimpleList.

Include File

<commerce.h>

Return Value

Value | Meaning
S_OK | The method succeeded.
E_POINTER | The plCount parameter is a NULL pointer.

Remarks

The caller should always call this method before calling any ISimpleList method that requires an array index in-value as a parameter.


ISimpleList::get_Item

The get_Item method locates the VARIANT at a specified index, copies the contents of this VARIANT to a new VARIANT, and returns the address of the new VARIANT.

Syntax

HRESULT get_Item(
long nIndex,// in
VARIANT *pvarGet// out
);

Parameters

nIndex
The index of the item to retrieve.
pvarGet
The address of the requested VARIANT.

Include File

<commerce.h>

Return Value

The get_Item method returns one of the following values.

Value | Meaning
E_POINTER | The pvarGet VARIANT is a NULL pointer.
DISP_E_BADINDEX | The nIndex parameter specifies a value that is out of range.
S_OK | The method succeeded.

Related Topic

ISimpleList::put_Item


ISimpleList::get__NewEnum

The get__newEnum method retrieves the IUnknown interface for the SimpleList's enumerator object. The caller can call QueryInterface through this pointer to retrieve an instance pointer on the SimpleList's IEnumVariant implementation.

Syntax

HRESULT get__newEnum(
IUnknown **ppUnk// out
);

Parameter

ppUnk
The address of an IUnknown pointer for the object that implements IEnumVariant on this SimpleList.

Include File

<commerce.h>

Return Value

Value | Meaning
S_OK | The method succeeded.
E_POINTER | The ppUnk parameter references a NULL pointer.
E_OUTOFMEMORY | Memory failure.


ISimpleList::put_Item

The put_Item method stores an initialized VARIANT at the specified array index. If an item is already stored at the specified index, that item is overwritten.

Syntax

HRESULT put_Item(
long nIndex,// in
VARIANT varNew// in
);

Parameters

nIndex
The index at which to store the new VARIANT.
varNew
The new VARIANT.

Include File

<commerce.h>

Return Value

The put_Item method returns one of the following values.

Value | Meaning
S_OK | The method succeeded.
DISP_E_BADINDEX | The nIndex parameter references an out-of-range value. This means that nIndex contains a value either larger than the SimpleList or less than zero.

Related Topic

ISimpleList::putref_Item


ISimpleList::putref_Item

The ISimpleList::putref_Item method inserts a VARIANT that references an object's IUnknown or IDispatch implementation into the specified index in the SimpleList.

Syntax

HRESULT putref_Item(
long nIndex,// in
VARIANT varNew// in
);

Parameters

nIndex
The position at which to insert this item in the SimpleList.
varNew
The VARIANT to insert.

Include File

<commerce.h>

Return Value

Value | Description
S_OK | The VARIANT was successfully inserted at the specified index.
DISP_E_BADINDEX | The value specified in nIndex is less than zero or larger than the SimpleList.

Related Topic

ISimpleList::put_Item


Writing Custom Components

The Microsoft® Commerce Server version 3.0 pipeline is a software infrastructure that sequentially executes an array of components. Each component is a custom-tailored Component Object Model (COM) object designed to perform operations on some part of the OrderForm or Dictionary. The pipeline coordinates the interaction of pipeline components by passing the OrderForm or Dictionary from one component to another.

Pipeline components are configured to support one of several architectures. The first, the order processing pipeline (OPP), automates order processing in a business-to-consumer scenario. The Clocktower, which is included among the Commerce Server sample stores, illustrates this use. The second, the Commerce Interchange Pipeline (CIP), is intended to facilitate the packaging and transmission of business documents across a network. The Microsoft Market sample site illustrates this use of the pipeline architecture.

Commerce Server 3.0 includes a powerful set of components that can be combined into a pipeline to support either scenario. In addition, you can create your own components to extend the capabilities of the pipeline architecture. This guide explains how to do this, and includes the following topics:

  • υOverview. Explains the basic structure of pipeline components, and introduces the OrderForm and Dictionary objects on which pipeline components operate. In addition, this section introduces some of the software components, such as the Active Template Library (ATL) that you can use to build pipeline components.
  • υThe Active Template Library (ATL) MinMaxShip Component Sample. Illustrates, step by step, how to create, build, and register an OPP component using the ATL.


Overview

A pipeline component is a Component Object Model (COM) server object that implements the IPipelineComponent interface. The following is the definition of this interface that appears in pipecomp.idl:

interface IPipelineComponent : IUnknown
    {
        import "oaidl.idl";

        HRESULT Execute(
                    [in]            IDispatch*  pdispOrder,
                    [in]            IDispatch*  pdispContext,
                    [in]            LONG        lFlags,
                    [out,retval]    LONG*       plErrorLevel
                );

        //
        // By default, a pipeline is in "execution mode", this call is         // used to prepare the pipeline for "design mode" (fEnable ==             //  TRUE) or to go to design mode (fEnable = FALSE).
        //

        HRESULT EnableDesign( [in]    BOOL fEnable );

    };

When the pipeline creates an instance of a component, it requests an interface pointer on the component's IPipelineComponent implementation, then uses this pointer to invoke IPipelineComponent::Execute.

The IPipelineComponent is the only interface that a component must implement to function within the pipeline. However, to enhance a component's usability, or to take advantage of the transaction capabilities of Microsoft Transaction Server, you may also design your component to implement one or more of the following interfaces:

  • υIDispatch. Implementing is optional. It makes it possible for clients to access your component's capabilities from macro languages, such as Microsoft® Visual Basic Scripting Edition (VBScript), Microsoft® JavaScript™ (JScript), or Microsoft® Visual Basic®.
  • υIPipelineComponentAdmin . Inherits from IDispatch, and makes it possible for you to extend your component's capabilities without modifying the interface that implements those capabilities. This interface defines the GetConfigData and SetConfigData methods, to which the caller passes a Dictionary. GetConfigData and SetConfigData write or read this Dictionary to retrieve or set configuration data on the component.
  • υIPipelineComponentDescription. Implementing is optional, but for usability purposes, is highly recommended. When you implement IPipelineComponentDescription, you identify to the Pipeline Editor the OrderForm name/value pairs that your component reads and writes, as well as the pipe context objects that your component uses. When the user double-clicks the node for your component in the Pipeline Editor, the Pipeline Editor displays these name/value pairs in a tab, provided that the component implements IPipelineComponentDescription.
  • υIPersistStreamInit. Makes it possible for the properties on your component to be saved and loaded to and from persistent storage through the Pipeline Editor.
  • υIPersistXML. Makes it possible for your component’s data to be loaded and saved as an XML stream.
Note

If you are designing an object to be used by the Mapping components included in the Commerce Interchange Pipeline (CIP), the component must implement either IPersistStreamInit or IPersistXML.


Sources of Information on COM

Because both of the samples that are used in this section to illustrate component building rely largely on both Microsoft® Visual C++® and the Component Object Model (COM), this section assumes that you have a working knowledge of both.

If you are not familiar with COM, please consult the following resources.

  • υRogerson, Dale. Inside COM, Microsoft Press, 1997.
  • υChappell, David. Understanding ActiveX and OLE: A Guide For Developers and Managers, Microsoft Press, 1996.
Note

This section also assumes that you are using Visual C++ version 5.0 to create your custom components. You can, however, create pipeline components using any build environment that supports the creation of free-threaded COM server objects.


The Active Template Library (ATL) MinMaxShip Component Sample

The MinMaxShip sample component, which is included on the Commerce Server CD, calculates the shipping total for an order by taking the largest list price in an OrderForm object's Items collection, multiplying it by a percentage, and comparing the product to some specified minimum. The larger number in this comparison is then stored in the OrderForm's _shipping_total name/value pair.

This section demonstrates how to use the Active Template Library and the Pipeline Component Wizard to create and implement the MinMaxShip component as an Active Template Library (ATL) object. This tutorial covers the following topics:

  • υCreating a project for the MinMaxShip sample component.
  • υAdding an object to the MinMaxShip project.
  • υAdding properties to the MinMaxShip project.
  • υAdding support for IPersistStreamInit to save the component's properties to storage.
  • υImplementing property pages. A property page is a dialog box-like window that component users can use to set properties on the MinMaxShipping object that the MinMaxShip component implements.
  • υImplementing IPipelineComponent, the interface that an object must implement to be executed by the pipeline.
  • υImplementing IPipelineComponentDescription. Implementing this interface results in the addition of a property page to the property sheet for your component. This property page identifies the pipe context values that your component reads, and the OrderForm values that your component reads and writes.


The Active Template Library

The Active Template Library (ATL) is a collection of C++ templates included in Microsoft® Visual C++® version 5.0. This template library is intended specifically to facilitate the creation of Component Object Model (COM) objects.

Although you can create a pipeline component using any build environment that supports the creation of free-threaded COM servers, the use of ATL is recommended for the following reasons:

  • υSmall, fast code. COM components created using ATL are smaller and faster that other approaches to component creation, including approaches supported by Visual C++. Although you can easily create COM components using the Microsoft® Foundation Classes (MFC) library, you incur significant memory overhead that is occasioned by using a large class library. This overhead is particularly undesirable for shared server components.
  • υGenerous user interface support. The use of ATL makes it possible for you to create pipeline components using features built into the Visual C++ 5.0 user interface. This approach significantly reduces the learning curve that attends learning certain COM implementation details, and also reduces the amount of code you have to write. For example, when you use ATL, the Interface Definition Language (IDL) files for your component’s interfaces are created for you based on the method and property definitions that you specify, and adding new objects to a project can be performed with two or three mouse clicks. This saves you the work of hand-coding modifications to your component's IDL file.

For information about the Active Template Library, see the ATL Tutorial, which is included with Visual C++.


The Pipeline Component Wizard

The Pipeline Component Wizard consists of a group of files that you add to your Visual C++ 5.0 installation to automate the creation of Commerce Server pipeline components. The Pipeline Component Wizard creates the object definition and implementation files that contain the function prototypes for all of the interfaces that you need to implement to create a fully functional pipeline component. In addition, the Pipeline Component Wizard creates a property page for your project, in which you add the controls through which users set component properties.

This tutorial assumes that you will use the Pipeline Component Wizard to create pipeline components.

To install the Pipeline Component Wizard
  1. Copy all the files contained in the \Microsoft Site Server SiteServer\Commerce\SDK \Commerce\Samples\ATLWizard\Template directory into your \Program Files\DevStudio\SharedIDE\Template\ATL directory (not into a subdirectory).
  2. Register the CommerceDLG.dll file, which is located in the \MicrosoftSiteServer\SiteServer\Commerce\SDK
    \Commerce\Samples\ATLWizard\i386 directory. To register this .dll, start the Command Prompt, change directories to the directory that contains the file, and type the following at the command line:
    regsvr32 CommerceDLG.dll


Step One: Creating the Project

The MinMaxShip component is a Component Object Model (COM) object that exposes a set of COM interfaces to the order processing pipeline (OPP). To create this project in Visual C++ 5.0, you use the COM App Wizard.

To create the MinMaxShip project
  1. In the Developer Studio environment, on the File menu, click New , and then click the Projects tab.
  2. Select the ATL COM AppWizard option.
  3. Type MinMaxShip as the project name.

    Your dialog box should look like this:

  4. Click OK. The ATL COM App Wizard presents a dialog box offering several choices to configure the initial ATL project.

  5. Because you are creating a modified ASP component, leave the Server Type as DLL; a control must be an in-process server. All the default options are fine, so click Finish.

    A dialog box appears that lists the main files that will be created. These files are listed in the following table, along with a description of each file that the ATL COM AppWizard generates.
    File | Purpose
    MinMaxShip.cpp, MinMaxShip.h | Contains the implementation of DllMain, DllCanUnloadNow, DllGetClassObject, DllRegisterServer and DllUnregisterServer. Also contains an object map, which is a list of the ATL objects in your project. This is initially blank, because you have not created an object yet.
    MinMaxShip.def | Standard Windows module definition file.
    MinMaxShip.dsw | Project workspace.
    MinMaxShip.dsp | File that contains the project settings.
    MinMaxShip.idl | Interface definition language file, which describes the interfaces specific to your objects.
    MinMaxShip.rc | Resource file, which initially contains the version information and a string containing the project name.
    Resource.h | Header file for the resource file.
    MinMaxShip.mk | Make file that can be used to build a proxy/stub DLL. You will not need to use this.
    MinMaxShipps.def | Module definition file for the proxy/stub DLL.
    StdAfx.cpp | Fill that will #include the ATL implementation files.
    StdAfx.h | File that will #include the ATL header files.

  6. Click OK. The files are created.


Step Two: Adding an Object

After completing Step 1 of this tutorial, you can compile the files that Microsoft® Visual C++® creates for you into a dynamic-link library (DLL). To make this DLL useful, however, you must add support for an object that implements the appropriate pipeline interfaces.

When you use the Pipeline Component Wizard to add an object to your project, the IPipelineComponent interface is implemented by default. In addition, you can choose to implement the ISpecifyPropertyPages, IPersistStreamInit, and IPipelineComponentDescription interfaces.

To add an object to the MinMaxShip Sample
  1. On the Insert menu, click New ATL Object to display the ATL Object Wizard.

  2. In the first ATL Object Wizard dialog box, click Commerce Component as the category of object you want to add to your project. Click Next.

    A set of property pages is displayed to allow you to configure the control you are inserting into your project.

  3. In the Short Name box, type MinMaxShipping. (Do not click OK until configuring the second tab.) The other controls are filled in for you, so that the dialog box now looks like this.

The Class field shows the C++ class name created to implement the control. The .H File and .CPP File show the files created to contain the definition of the C++ class. The CoClass is the name of the component class for the object, and Interface is the name of the interface on which the component will implement its custom properties. The Type is a description for the control, and the ProgID is the readable name that can be used to look up the class ID (CLSID) of the control. Click OK.

  4. Click the Commerce Component tab. This tab displays a list of the optional interfaces that you can implement on a Commerce Server pipeline component.

If your component uses property pages to allow users to set component properties, you should implement ISpecifyPropertyPages. If your component saves and loads its properties to and from a stream, you should implement IPersistStreamInit. If you want your component users to identify the OrderForm, Transport Dictionary, or pipe context values that your component reads and writes, click IPipelineComponentDescription.

The MinMaxShip sample implements all of these interfaces, so you should select all of the check boxes on this tab, and then click OK.

The Pipeline Component Wizard creates the definition and implementation files that implement the necessary pipeline interfaces, and adds these files to the MinMaxShip project.

In addition, the wizard creates a stub implementation for the IMinMaxShipping interface, on which you implement your component’s properties (see Step 3: Adding Properties).

Note

The approach to adding properties illustrated in this section assumes that you do not intend to implement the IPipelineComponentAdmin interface. This interface is defined by Commerce Server as an alternative way to implement properties on an object (see Deciding Which Interface to Expose).


Deciding Which Interface to Expose

Before a component can be configured through a macro language such as Microsoft® Visual Basic Scripting Edition (VBScript) or JavaScript, it must implement the IDispatch interface. Because any interface that you create can inherit from IDispatch, you decide which of the interfaces that you implement will use IDispatch to expose your component's properties and/or methods.

Several options are available. When you add an object to your project, as you did in Step 2 of this tutorial, Visual C++ adds an interface to the object definition that appears in the project's interface definition language (IDL) file. By default, the interface that Microsoft® Visual C++® adds inherits from IDispatch.

You can use this interface, or you can implement the IPipelineComponentAdmin interface. This interface is defined by Commerce Server 3.0 specifically to enable component writers to expose their component properties. The IPipelineComponentAdmin interface defines two methods: GetConfigData and SetConfigData. These methods take a Dictionary as a parameter, and read or write to this Dictionary to retrieve or set the values of a component's properties.

The options described in the preceding paragraphs are mutually exclusive; you cannot implement two IDispatch interfaces on a single object and make both available to Active Server Pages (ASP) clients.

The following lists the advantages to using the Visual C++ user interface to get an IDispatch implementation:

  • υYou do not have to worry about specifically implementing IDispatch::Invoke on your own. By adding properties and methods through the Visual C++ user interface, this work is done for you.
  • υAs you add properties and methods to your object, Visual C++ automatically adds the appropriate entries to the project's IDL, header, and implementation files. Because the added interface is the default interface for the object, a VBScript or JavaScript client that creates an instance of your object using the object's program identifier (Prog ID) gets this interface, and can set the methods and invoke the properties implemented in that interface.

The advantage of implementing IPipelineComponentAdmin is that according to the rules of the Component Object Model (COM), once an interface is published, it cannot be changed. By adding properties to a published object, you necessarily modify the dispatched interface, running the risk that you will break the client code of existing users. Because implementing IPipelineComponentAdmin does not require that your component definition be modified to add support for new properties, your component can evolve over time without requiring the publication of a new interface.

This tutorial illustrates the former approach. The WriteToDb sample, which is included on the Commerce Server compact disc, illustrates how to implement IPipelineComponentAdmin.


Step Three: Adding Properties

When you added the MinMaxShipping object to the MinMaxShip project in Step 2: Adding an Object, the Pipeline Component Wizard added the definition and implementation files for this object to the MinMaxShip project. These files, the MinMaxShipping.h and MinMaxShipping.cpp files define and partially implement the necessary pipeline interfaces: IPipelineComponent, IPipelineComponentDescription, ISpecifyPropertyPages, and IPersistStreamInit.

In addition, the Pipeline Component Wizard added to the MinMaxShipping.h file a definition for IMinMaxShipping, an interface that inherits from IDispatch, and through which the MinMaxShip component exposes the properties that it supports.

The MinMaxShip component supports two properties: MinShipping and Percentage. In this step, you will add these properties to the component's IMinMaxShipping interface so that they can be set or retrieved by a scripting language client.

To add the MinShipping and Percentage properties to MinMaxShip
  1. In the MinMaxShip project window, click the ClassView tab, click the topmost node in the ClassView window, click IMinMaxShipping, and then right-click to display a popup menu.
  2. On the displayed popup menu, click Add Property.

    A dialog box is displayed in which you can specify the name and data type of the property.

  3. In the Property Type box, select long, and then in the Property Name box, type MinShipping.

    The dialog now looks like this.

  4. Click OK to add the property.
  5. Repeat this process, specifying float as the Property Type, and then specifying Percentage as the property name.

If you open up the MinMaxShipping.cpp file, you will notice that Visual C++ has made a few modifications to your component class. This class now includes the following function stubs:

STDMETHODIMP CMinMaxShipping::get_MinShipping(long *pVal)
{
    return S_OK;
}

STDMETHODIMP CMinMaxShipping::put_MinShipping(long newVal)
{
    return S_OK;
}

STDMETHODIMP CMinMaxShipping::get_Percentage(float *pVal)
{
    return S_OK;
}

STDMETHODIMP CMinMaxShipping::put_Percentage(float newVal)
{
    return S_OK;
}

To make these methods functional, declare variables to store these property values internally within the CMinMaxShipping class. In the MinMaxShipping.h file, which contains the class definition for the MinMaxShip component, declare the following variables:

CComVariant m_varMinShipping;
CComVariant m_varPercentage;

You can enable the functions above as follows, taking advantage of the fact that CComVariant overloads the assignment (=) operator:

STDMETHODIMP CMinMaxShipping::get_MinShipping(long *pVal)
{
    *pVal = V_I4(&m_varMinShipping);
    return S_OK;
}

STDMETHODIMP CMinMaxShipping::put_MinShipping(long newVal)
{
    m_varMinShipping = newVal;
    return S_OK;
}

STDMETHODIMP CMinMaxShipping::get_Percentage(float *pVal)
{
    *pVal = m_varPercentage;
    return S_OK;
}

STDMETHODIMP CMinMaxShipping::put_Percentage(float newVal)
{
    m_varPercentage = newVal;
    return S_OK;
}

Given the data type of the arguments passed to these methods (long and float, respectively), you may wonder why one would use the CComVariant class to store their values. The reason for this is that the CComVariant class supports methods that are particularly conducive to storing the property values in a stream (Step 4: Saving Properties).

To test the setting of these properties, you can create a debug executable in Visual Basic. In this executable, use the CreateObject function to create an instance of the MinMaxShipping object using its Prog ID (MinMaxShip.MinMaxShip), and initialize the properties to some value. Specify this executable as the debug executable for the project, and set a breakpoint in any of the method implementations previously listed:

Dim objMinShipping

Set objMinShipping = CreateObject("MinShipping.MinShipping.1")
objMinShipping.Percentage = .05
objMinShipping.MinShipping = 1.00

Debug.Print objMinShipping.Percentage
Debug.Print objMinShipping.MinShipping


Step Four: Saving Properties

Pipeline components save their properties to persistent storage by implementing the IPersistStreamInit interface. When a component implements IPersistStreamInit, both the Win32®-based Pipeline Editor and the pipeline object use the component’s implementation of this interface to load and save the component’s properties.

When you added an object to the MinMaxShip project using the Pipeline Component Wizard (see Step 2: Adding an Object), the wizard added the following definition of IPersistStreamInit to MinMaxShipping.h file that it created:

// IPersistStreamInit
const long  m_lStreamVersionMajor;   // major version number of the
                                    // stream
const long  m_lStreamVersionMinor;   // minor version number of the                                             // stream
STDMETHOD(GetClassID)(CLSID *pClassID);
STDMETHOD(IsDirty)(void);
STDMETHOD(Load)(IStream *pStm);
STDMETHOD(Save)(IStream *pStm, BOOL fClearDirty);
STDMETHOD(GetSizeMax)(ULARGE_INTEGER *pcbSize);
STDMETHOD(InitNew)(void);

The m_lStreamVersionMajor and m_lStreamVersionMinor variables are not part of the interface itself, but the CMinMaxShipping object’s constructor uses these variables to initialize the version of the MinMaxShip component.

CMinMaxShipping():m_lStreamVersionMajor(0),m_lStreamVersionMinor(0)
{
}

In addition to adding the IPersistStreamInit interface definition to the component’s class definition file, the wizard added stub implementations of the interface’s methods to CMinMaxShipping.cpp. To complete the implementation of this interface, you replace the body of these stub implementations with your own.

In the IPersistStreamInit::GetClassID implementation, return the class ID for the CMinMaxShipping object. The default implementation that the Pipeline Component Wizard provides you is fine:

STDMETHODIMP CMinMaxShipping::GetClassID(CLSID *pClassID)
{
    *pClassID = GetObjectCLSID();
    return S_OK;
}

Recall that in Step 3: Adding Properties, you added CComVariant member variables to the CMinMaxShipping class definition to store the values of the MinMaxShip component’s MinShipping and Percentage properties. When you implement IPersistStreamInit::Load and IPersistStreamInit::Save, the use of CComVariant to store these values makes sense; you can use the CComVariant object’s WriteToStream and ReadFromStream methods to write the values of these properties to a persistent stream that the pipeline passes to your Load and Save implementations, as follows:

STDMETHODIMP CMinMaxShipping::Save(IStream *pStm, BOOL fClearDirty)
{
    HRESULT hRes = S_OK;

    hRes = m_varPercentage.WriteToStream(pStm);

    if(FAILED(hRes)){
        return hRes;
    }

    hRes = m_varMinShipping.WriteToStream(pStm);
    if(FAILED(hRes){
        return hRes;
    }
    return hRes;
}

Finally, implement IPersistStreamInit::GetSizeMax to identify the amount of space that the pipeline MinMaxShip component needs to set aside to store the component’s property values. The MinMaxShip component’s GetSizeMax implementation adds the size of the size of the m_varMinShipping and m_varPercentage variables, and returns the sum in the LowPart member of the GetSizeMax method’s pcbSize out-value variable:

STDMETHODIMP CMinMaxShipping::GetSizeMax(ULARGE_INTEGER *pcbSize)
{
    pcbSize->LowPart = sizeof(m_varMinShipping) + sizeof(m_varPercentage);
    pcbSize->HighPart = 0;
    return S_OK;
}


Step Five: Adding Property Pages

Property pages are implemented as separate Component Object Model (COM) objects, which allow property pages to be shared as required. Property pages for a pipeline component usually consists of three tabs. The first identifies general information about your component, the second identifies the OrderForm, Transport Dictionary and pipe context values that it uses, and the third provides component users with a user interface through which they can set the component’s properties.

When you implement a property page in a pipeline component, you create a class that implements the property page, and you implement ISpecifyPropertyPages in your main component class. The ISpecifyPropertyPages::GetPages method returns a pointer to the class in which your property page is implemented.

When you added an object to the MinMaxShip project, the Pipeline Component Wizard added a stub implementation of the ISpecifyPropertyPages interface to the MinMaxShipping.h and MinMaxShipping.cpp files. All you need to do to the stub implementation is to remove the comment marks around the code, and replace the class ID in the sample code with the class ID for the property page you add to the project.

To create a property page, use the ATL Object Wizard to add a property page to the MinMaxShip project. Visual C++ creates a new class for the property page, and adds the definition and implementation files for this class to your project.

Note

To add property pages support to the MinMaxShip project, you must complete all the steps listed in Adding the Property Page, Implementing the Property Page and Implementing ISpecifyPropertyPages.


Adding the Property Page

A property page consists of a dialog resource, and class derived from IPropertyPagesImpl that is designed to manage this resource.

The IPropertyPagesImpl method supports a default implementation of the Activate and Apply methods. The Activate method is called by the Win32®-based Pipeline Editor when the property pages for a component are displayed. The Apply method is called when the user clicks the Apply button on the property pages dialog box.

Using the Visual C++ user interface to add a property page to the MinMaxShip project results in a default implementation of IPropertyPagesImpl.

To add a property page to MinMaxShip
  1. Start the ATL Object Wizard, click Controls, click Property Page, and then click Next.

  2. You again get the dialog box allowing you to type the name of the object. Call the object MinMaxPropPg and type that name in the Short Name edit box.

Notice that the Interface edit box appears dimmed. This is because a property page does not need a custom interface.

  3. Click the Strings tab to set the title of the property page. The title of the property page is the string that appears in the tab for that page. The Doc String is a description that a property frame could use to put in a status line or tool tip. The standard property frame currently does not use this string, but you can set it anyway. You are not going to generate a Helpfile at the moment, so delete the entry in that text box. Click OK, and the property page object will be created.

The following three files are created.

File | Description
MinMaxPropPg.h | Contains the C++ class CMinMaxPropPg, which defines the property page.
MinMaxPropPg.cpp | Includes the MinMaxPropPg.h file, and implements the Apply and Activate functions.
MinMaxPropPg.rgs | The registry script that registers the property page object.

The new property page is added to the object entry map in MinMaxShip.cpp. A reference to the MinMaxPropPg class is added to the MinMaxShip.idl file. The new registery script file, MinMaxPropPg.rgs is added to the project resource. A dialog box template is added to the project resource for the property page. The property strings you specified are added to the resource string table.

Your final step in creating the property page is to open the project’s resource file, display the dialog template for the property page (IDD_MINMAXPROPPG), and add the controls through which the user of the MinMaxShip component will modify the component’s properties.

When you are finished, the dialog template should look like this one.

The edit controls should be given the following resource identifiers, in this order:

IDC_PERCENTAGE, IDC_MINSHIPPING


Implementing the Property Page

In Adding the Property Page, you used the Microsoft® Visual C++® user interface to add a property page to the MinMaxShip project. This task also involved creating the controls for the MinMaxShip component’s properties on the default dialog box that Visual C++ created for you.

When you add a property page to a project, Visual C++ creates the class definition and implementation files for the class that is intended to manage your property page. The class definition and implementation for the MinMaxShip project’s property pages appears in the MinMaxShipPropPg.h and MinMaxShipPropPg.cpp files, respectively.

The MinMaxShipPropPg.h file contains the definition for the CMinMaxShipPropPg class. This class inherits from the IPropertyPagesImpl interface, which supports default implementations of the Apply and Activate methods. The Activate method is called by the Win32®-based Pipeline Editor when the property pages for a component are displayed. The Apply method is called when the user clicks the Apply button. Implementing a property page generally involves overriding the default implementation of these two methods.

If you open CMinMaxPropPg.h, and you see the following stub implementation of the Apply method:

    STDMETHOD(Apply)(void)
    {
        ATLTRACE(_T("CMinMaxPropPg::Apply\n"));
        for (UINT i = 0; i < m_nObjects; i++)
        {
            // Do something interesting here
            // ICircCtl* pCirc;
            // m_ppUnk[i]->QueryInterface(IID_ICircCtl, (void**)&pCirc);
            // pCirc->put_Caption(CComBSTR("something special"));
            // pCirc->Release();
        }
        m_bDirty = FALSE;
        return S_OK;
    }

};

To implement this method for the MinMaxShip component, replace this implementation of Apply with the following:

STDMETHODIMP (Apply)(void)
{

    HRESULT hRes = S_OK;
    ATLTRACE(_T("CMinMaxPropPg::Apply()"));
    CComBSTR bstrMinShipping;
    CComBSTR bstrPercentage;

    VariantInit(&varbstrMinShipping);
    VariantInit(&varbstrPercentage);
    VariantInit(&varMinShipping);
    VariantInit(&varPercentage);

    for(UINT i = 0; i < 1; i++){

    ComQIPtr<IMinMaxShipping,     &IID_IMinMaxShipping>pMinMaxShipping(m_ppUnk[i]);

    GetDlgItemText(IDC_MINSHIPPING, bstrMinShipping.m_str);
    GetDlgItemText(IDC_PERCENTAGE, bstrPercentage.m_str);

    V_BSTR(&varbstrMinShipping) = SysAllocString(bstrMinShipping.m_str);
    V_VT(&varbstrMinShipping) = VT_BSTR;

    V_BSTR(&varbstrPercentage) = SysAllocString(bstrPercentage.m_str);
    V_VT(&varbstrPercentage) = VT_BSTR;

    hRes = VariantChangeType(&varMinShipping, &varbstrMinShipping, 0,                     VT_I4);

    if(FAILED(hRes))
        return hRes;

    hRes = VariantChangeType(&varPercentage, &varbstrPercentage, 0,                         VT_R4);

    if(FAILED(hRes))
        return hRes;

    pMinMaxShipping->put_MinShipping(varMinShipping.lVal);
    pMinMaxShipping->put_Percentage(varPercentage.fltVal);

    VariantClear(&varbstrPercentage);
    VariantClear(&varbstrMinShipping);
    VariantClear(&varMinShipping);
    VariantClear(&varPercentage);

}

    m_bDirty = FALSE;
    return S_OK;
}

The sole purpose of this Apply implementation is to retrieve the values that the user has typed in the dialog box controls that you created in Adding the Property Page, and to write them to the variables in which MinMaxShip stores its property values.

To do this, the code retrieves the new property settings from the dialog box, gets an interface pointer on the component’s IMinMaxShipping implementation, and uses this pointer to call the put_MinShipping and put_Percentage methods that you implemented in Step 3: Adding Propertiescom_writingcomponents_RHDQ.

When you implement the Activate method, you simply perform the same operation in reverse: that is, you use the get_MinShipping and get_Percentage methods to write the component’s properties to local variables, and you display these variable values in the appropriate property page dialog box controls.

Note

Because most components can simply use IPropertyPagesImpl’s default implementation of Activate, Visual C++ does not include a stub implementation of this method in your property pages class when you add the property page to your project. You must add the entire method implementation yourself.

Here is the MinMaxShip component’s Activate implementation.

STDMETHODIMP (Activate)(HWND hWndParent, LPCRECT pRect, BOOL fModal)
{

HRESULT hRes = IPropertyPageImpl<CMinMaxPropPg>::Activate(hWndParent,     pRect, fModal);

if(SUCCEEDED(hRes)){

    ATLTRACE(L"Created object");
    CComQIPtr<IMinMaxShipping,                                                     &IID_IMinMaxShipping>pMinMaxShipping(m_ppUnk[0]);

    VariantInit(&varMinShipping);
    VariantInit(&varPercentage);
    VariantInit(&varbstrMinShipping);
    VariantInit(&varbstrPercentage);

    pMinMaxShipping->get_MinShipping(&m_lMinShipping);
    pMinMaxShipping->get_Percentage(&m_fPercentage);

    V_I4(&varMinShipping) = m_lMinShipping;
    V_VT(&varMinShipping) = VT_I4;

    V_R4(&varPercentage) = m_fPercentage;
    V_VT(&varPercentage) = VT_R4;

    hRes = VariantChangeType(&varbstrMinShipping, &varMinShipping, 0,                 VT_BSTR);

    if(FAILED(hRes))
        return hRes;

    hRes = VariantChangeType(&varbstrPercentage, &varPercentage, 0,                 VT_BSTR);
    ATLTRACE(varbstrPercentage.bstrVal);

    if(FAILED(hRes))
        return hRes;

    SetDlgItemText(IDC_MINSHIPPING, varbstrMinShipping.bstrVal);
    SetDlgItemText(IDC_PERCENTAGE, varbstrPercentage.bstrVal);

    VariantClear(&varbstrMinShipping);
    VariantClear(&varbstrPercentage);
    VariantClear(&varPercentage);
    VariantClear(&varMinShipping);

    }

    return S_OK;
}

Next, you need to include a handler that Microsoft® Windows NT® can notify when the user modifies a value in the property page.

LRESULT OnChange(WORD wNotify, WORD wID, HWND hWnd, BOOL& bHandled);

The OnChange handler is not a member of IPropertyPageImpl. It is included to track the state of the controls in the property page. To enable this handler, add the following entry to the message map for the MinMaxPropPg class:

BEGIN_MSG_MAP(CMinMaxPropPg)
COMMAND_RANGE_HANDLER(IDC_MINSHIPPING, IDC_PERCENTAGE, OnChange);
CHAIN_MSG_MAP(IPropertyPageImpl<CMinMaxPropPg>)
END_MSG_MAP()

When the user changes a value in one of the edit controls on the dialog box previously displayed, Windows NT will invoke this handler. It is then appropriate to call the IPropertyPageImpl template's SetDirty method, as follows, in the CMinMaxPropPg implementation file:

LRESULT CMinmaxPropPg::OnChange(WORD wNotify, WORD wID, HWND hWnd, BOOL& bHandled)
{
    if (wNotify == EN_CHANGE)
        SetDirty(TRUE);
    return 0;
}

Finally, because the methods defined in the property page class need to access the properties of the component class (CMinMaxShip), you should add a reference to MinMaxShip.h in the MinMaxPropPg.h file that defines the property page class.

#include MinMaxShip.h


Implementing ISpecifyPropertyPages

When you add a property page to a project using the Microsoft® Visual C++® user interface, the property page class that manages that property page is a self-contained unit. This means that although all of the code that governs the functionality of the property page is contained in the property page class.

To be displayed by the Win32®-based Pipeline Editor, however, you need to create a link that identifies your property pages class to your component class. At this point in the tutorial, the component class, CMinMaxShipping, has no way of identifying the class in which the property page is implemented.

To provide this identification, you implement the ISpecifyPropertyPages interface in the CMinMaxShipping component class. The ISpecifyPropertyPages interface defines the following method:

ISpecifyPropertyPages::GetPages(CAUUID *pPages)

To implement ISpecifyPropertyPages, you implement the GetPages method by initializing its pPages out-parameter to reference the class ID (CLSID) of the class that implements the component’s property pages. When a user double-clicks the MinMaxShip component in the Win32-based Pipeline Editor, the Pipeline Editor calls QueryInterface on the MinMaxShip component to determine if the component supports ISpecifyPropertyPages. If the component does not, nothing happens. If it does, the Pipeline Editor gets an interface pointer on the component’s ISpecifyPropertyPages implementation, and uses this pointer to call GetPages. If you implement GetPages properly, the Pipeline Editor now has the CLSID of the object that implements the property pages for your component.

In the section, Step Two: Adding an Object, the Pipeline Component Wizard offered you the opportunity to implement the ISpecifyPropertyPages interface. If you opted to implement this interface, the Pipeline Component Wizard added the following stub implementation of GetPages to the MinMaxShipping.h file:

// ISpecifyPropertyPages Methods
//
STDMETHODIMP CMinMaxShipping::GetPages(CAUUID *pPages)
{

if (NULL == pPages)
    return E_INVALIDARG;
// TODO: Uncomment out the line below, and add the CLSID of a custom
// Property Page Control

/*
    pPages->cElems = 1;
    pPages->pElems = (GUID*)CoTaskMemAlloc(1*sizeof(GUID));
    if(!pPages->pElems){
        pPages->cElems = 0;    return E_OUTOFMEMORY;
    }
    memcpy(pPages->pElems, &CLSID_MinMaxShippingPpg, sizeof(GUID));

    return S_OK;
    */
    return E_NOTIMPL;
}

To make this method functional, you generally replace the CLSID referenced in the call to memcpy with the CLSID for the object that implements your property pages. You can locate this CLSID in the class definition file for your property page class.

Because CLSID_MinMaxShippingPpg is the correct CLSID for this tutorial, you can remove the comment delimiters from this code, and compile.


Step Six: Describing the Component's Work

To enhance the usability of your component, you may choose to implement the optional IPipelineComponentDescription interface. This interface defines methods that return SAFEARRAY variables that identify the pipe context elements that a component reads, as well as the OrderForm or Dictionary elements that a component reads and writes.

When a Pipeline Editor user activates the property pages for your component, the Pipeline Editor checks to see if your component implements IPipelineComponentDescription. If it does, the Pipeline Editor invokes your IPipelineComponentDescription method implementations and displays the values that the component reads and writes in a property page like this one.

When you run the Pipeline Component Wizard, the wizard adds a reference to IPipelineComponentDescription to your CMinMaxShipping derivation list, and adds the IPipelineComponentDescription function signatures to the class defintion.

// IPipelineComponentDescription
    STDMETHOD (ContextValuesRead)(VARIANT *pVar);
    STDMETHOD (ValuesRead)(VARIANT *pVar);
    STDMETHOD (ValuesWritten)(VARIANT *pVar);

In addition, the wizard adds stub implementations to the CMinMaxShipping implementation file. The code added by the wizard looks like this:

//
// IPipelineComponentDescription Methods
//
STDMETHODIMP CMinMaxShipping::ContextValuesRead(VARIANT *pVarRead)
{
    // TODO: Add your own values to the array
    int cEntries = 1;
    // allocate the safearray of VARIANTs
    SAFEARRAY*    psa = SafeArrayCreateVector(VT_VARIANT, 0, cEntries);
    // Populate the safearray variants
    VARIANT* pvarT = (VARIANT*)psa->pvData;
    V_BSTR(pvarT) = SysAllocString(L"Example Context Value Read");
    V_VT(pvarT) = VT_BSTR;
    // set up the return value to point to the safearray
    V_VT(pVarRead) = VT_ARRAY | VT_VARIANT;
    V_ARRAY(pVarRead) = psa;
    return S_OK;
}

STDMETHODIMP CMinMaxShipping::ValuesRead(VARIANT *pVarRead)
{
    // TODO: Add your own values to the array
    int cEntries = 1;
    // allocate the safearray of VARIANTs
    SAFEARRAY*    psa = SafeArrayCreateVector(VT_VARIANT, 0, cEntries);
    // Populate the safearray variants
    VARIANT* pvarT = (VARIANT*)psa->pvData;
    V_BSTR(pvarT) = SysAllocString(L"Example Value Read");
    V_VT(pvarT) = VT_BSTR;
    // set up the return value to point to the safearray
    V_VT(pVarRead) = VT_ARRAY | VT_VARIANT;
    V_ARRAY(pVarRead) = psa;

    return S_OK;
}

STDMETHODIMP CMinMaxShipping::ValuesWritten(VARIANT *pVarWritten)
{
    // TODO: Add your own values to the array
    int cEntries = 1;
    // allocate the safearray of VARIANTs
    SAFEARRAY*    psa = SafeArrayCreateVector(VT_VARIANT, 0, cEntries);
    // Populate the safearray variants
    VARIANT* pvarT = (VARIANT*)psa->pvData;
    V_BSTR(pvarT) = SysAllocString(L"Example Value Written");
    V_VT(pvarT) = VT_BSTR;
    // set up the return value to point to the safearray
    V_VT(pVarWritten) = VT_ARRAY | VT_VARIANT;
    V_ARRAY(pVarWritten) = psa;
    return S_OK;
}

This code contains the basic instructions form implementing the interface. The following code illustrates the modifications that you make to the stub implementation to make it accurately reflect that values that the MinMaxShip component actually reads and writes:

STDMETHODIMP CMinMaxShipping::ContextValuesRead(VARIANT *pVarRead)
{
    // allocate the safearray of VARIANTs
    SAFEARRAY*    psa = SafeArrayCreateVector(VT_VARIANT, 0, 0);

    // set up the return value to point to the safearray
    V_VT(pVarRead) = VT_ARRAY | VT_VARIANT;
    V_ARRAY(pVarRead) = psa;

    return S_OK;
}

STDMETHODIMP CMinMaxShipping::ValuesRead(VARIANT *pVarRead)
{
    // allocate the safearray of VARIANTs
    SAFEARRAY*    psa = SafeArrayCreateVector(VT_VARIANT, 0, 1);

    // Populate the safearray variants
    VARIANT* pvarT = (VARIANT*)psa->pvData;
    V_BSTR(pvarT) = SysAllocString(L"item._product_list_price");
    V_VT(pvarT) = VT_BSTR;

    // set up the return value to point to the safearray
    V_VT(pVarRead) = VT_ARRAY | VT_VARIANT;
    V_ARRAY(pVarRead) = psa;

    return S_OK;
}

STDMETHODIMP CMinMaxShipping::ValuesWritten(VARIANT *pVarWritten)
{

    int cEntries = 1;

    // allocate the safearray of VARIANTs
    SAFEARRAY*    psa = SafeArrayCreateVector(VT_VARIANT, 0, cEntries);

    // Populate the safearray variants
    VARIANT* pvarT = (VARIANT*)psa->pvData;
    V_BSTR(pvarT) = SysAllocString(L"order._shipping_total");
    V_VT(pvarT) = VT_BSTR;

    // set up the return value to point to the safearray
    V_VT(pVarWritten) = VT_ARRAY | VT_VARIANT;
    V_ARRAY(pVarWritten) = psa;

    return S_OK;

}
Note

If your component does not read or write values to the OrderForm, you must still return a SAFEARRAY, even though the SAFEARRAY will most likely be empty.


Step Seven: Implementing IPipelineComponent

All pipeline components must implement the IPipelineComponent interface. This interface is defined as follows:

// IPipelineComponent

STDMETHOD (Execute) (
    IDispatch*  pdispOrder,
    IDispatch*  pdispContext,
    LONG        lFlags,
    LONG*       plErrorLevel);

STDMETHOD (EnableDesign) (BOOL fEnable);

When the pipeline creates an instance of a component, it requests an interface pointer on the component’s IPipelineComponent implementation, and then uses that pointer to call the component’s Execute implementation. The pipeline passes the component an IDispatch pointer on the OrderForm or Transport Dictionary being passed through the pipeline, and an IDispatch pointer on the site’s pipe context. The pipe context is a Dictionary that contains references to objects and data that the site stores in the Application object, as well as to the built-in Active Server Pages (ASP) objects.

The IPipelineComponent interface is among the interfaces for which the Pipeline Component Wizard adds method definitions and implementation stubs when you add an object to your project. To implement IPipelineComponent::Execute for the MinMaxShip component, open the MinMaxShipping.cpp file, and modify the default implementation provided by the Pipeline Component Wizard.

For this example, the Execute method iterates through the items SimpleList on the OrderForm, and identifies the maximim list price in the list. The value of the MinShipping property is then compared to product of the maximum _product_list_price, multiplied by the Percentage property value, multiplied by -0.5. The maximum of these two values is then written to the OrderForm's _shipping_total name/value pair:

// IPipelineComponent
STDMETHODIMP CMinMaxShipping::Execute (
                IDispatch*  pdispOrder,
                IDispatch*  pdispContext,
                LONG        lFlags,
                LONG*       plErrorLevel)
{

HRESULT hr = S_OK;

IDictionary *pDictOrder = NULL;
ISimpleList *pListItems = NULL;
IDictionary *pDictItem = NULL;
long nItems;
long iItem;
int nListPrice;
int nMaxListPrice = 0;

long lMinShipping;
float fPercentage;

OPP_ERRORLEV ErrorLevel = OPPERRORLEV_FAIL;

if(pdispOrder == NULL)
    return E_INVALIDARG;

// Get the OrderForm Dictionary.

if(SUCCEEDED(hr=pdispOrder->QueryInterface(IID_IDictionary,     (void**)&pDictOrder)))
{

    VARIANT var;
    VariantInit(&var);

    // Make sure that the _shipping_total is not already set.

    hr = GetDictValue(pDictOrder, L"_shipping_total", &var);

    if(SUCCEEDED(hr) && (V_VT(&var) != VT_NULL))
        goto Out;

}

// Get an ISimpleList pointer on Items collection.

if(SUCCEEDED(hr = GetListItems(pDictOrder, &pListItems)))
    if(SUCCEEDED(hr = GetNumItems(pListItems, &nItems)))
    {

        // Get the largest price in the list.

        for(iItem = 0; iItem < nItems; iItem++)
        {

            if(FAILED(hr = GetNthItem(pListItems, iItem, &pDictItem)))
                goto Out;

            if(SUCCEEDED(GetDictValue(pDictItem, L"_product_list_price",                 &nListPrice)) &&     nListPrice > nMaxListPrice)

                nMaxListPrice = nListPrice;
                hr = S_OK;
        }

        // Get the minimum shipping and percentage from the CComVariant
        // members.

        this->get_MinShipping(&lMinShipping);
        this->get_Percentage(&fPercentage);

        hr = PutDictValue(pDictOrder, L"_shipping_total",
                max(lMinShipping, (int)(((float)nMaxListPrice *                             fPercentage) + 0.5)));

        if(SUCCEEDED(hr))
            ErrorLevel = OPPERRORLEV_SUCCESS;
        }

Out:
    if(plErrorLevel) *plErrorLevel = ErrorLevel;

    if(pDictOrder)
        pDictOrder->Release();

    if(pListItems)
        pListItems->Release();

    if(pDictItem)
        pDictItem->Release();

    return hr;

}

This implementation first queries the IDispatch interface on the OrderForm for an IDictionary pointer, and then passes this pointer to the PutDictValue function. The PutDictValue function is used to write the final shipping price to the OrderForm’s _shipping_total name/value pair.

The PutDictValue method used in this example is contained in the computil.cpp file. This file contains a collection of utility functions that facilitate working with Dictionary and OrderForm objects. When you use the Pipeline Component Wizard to add an object to a project, computil.h and computil.cpp are automatically added to the project for you, and an include directive referencing computil.h is added to your object’s implementation file.


Error Levels

Pipeline components return one of the following values:

  • υ1 = OPPERRORLEV_SUCCESS
  • υ2 = OPPERRORLEV_WARN
  • υ3 = OPPERRORLEV_FAIL

The pipeline keeps track of the worst error returned by a component upstream of now. Attached to each component (actually attached to the stage in the pipeline) is an attribute that indicates the maximum error level the component will tolerate. If the current error level is less than or equal to the maximum error level for this component, the component can then run the IPipelineComponent::Execute method.

The stage information that is passed back and forth between the Pipeline Editor and the pipeline contains a field indicating the error level for each stage.

Note

If a component cannot load in design mode, it should not fail.


Step Eight: Registering the Component

Pipeline component registration involves identifying the component as a pipeline component, identifying the stage or stages with which the component has an affinity, and optionally registering its name and threading model.

Each stage in the pipeline is identified by a globally unique identifier (GUID). GUIDs are defined in the pipe_stages.h file, which you include in the implementation file in which you are registering a component.

To identify the stage or stages with which a component has an affinity, you write the new component's class ID to the \HKEY_CLASSES_ROOT\CLSID\component_classid\implemented categories\stage_clsid key win the Microsoft® Windows NT® Registry, where stage_class_id is the GUID of the stage with which the component will have an affinity, and where component_class_id is the class ID of the component itself.

The code with which you register your component should be invoked in the DLLRegisterServer routine that is created for you when you create the component project in Microsoft® Visual C++®.

The MinMaxShip sample component uses a function called RegisterCATID to register the MinMaxShip component as a pipeline component, and to identify the stage with which the component has an affinity. The RegisterCATID function is defined in computil.h, and is implemented in MinMaxShip computil.cpp file. Both of these files are included in the Microsoft® Commerce Server version 3.0 Software Development Kit (SDK).

To use the RegisterCATID function to register your component, simply copy these files into your component's project directory, and add the computil.cpp file to your project.

The following code, from the MinMaxShip sample component illustrates how to call RegisterCATID. This code registers MinMaxShip as a pipeline component, and then associates the component with the OPP’s Accept stage:

hr = RegisterCATID(CLSID_MinMaxShipping, CATID_MSCSPIPELINE_COMPONENT);

if(FAILED(hr))
    return hr;

hr = RegisterCATID(CLSID_MinMaxShipping, CATID_MSCSPIPELINE_SHIPPING);

if(FAILED(hr))
    return hr;


Common Tasks

This section discusses some of the tasks that are often essential to implementing order processing pipeline (OPP) and Commerce Interchange Pipeline (CIP) components. Topics covered include the following:

  • υThe OrderForm.
  • υThe Error object.
  • υThe Pipe Context.


The OrderForm

When the pipeline invokes a component's implementation of IPipelineComponent::Execute, the pipeline passes the component an IDispatch interface pointer on the object that stores order information. Usually, the object on which this IDispatch is implemented is an OrderForm or a Dictionary.

The OrderForm object is a structured set of Dictionary and SimpleList objects that contains a detailed summary of all or part of one or more shopping sessions. The following figure illustrates the structure of an OrderForm object.

To access any part of an OrderForm within your IPipelineComponent::Execute implementation, call QueryInterface through the IDispatch interface pointer to get an instance pointer on the interface that you need.

For example, the Items collection in an OrderForm is a SimpleList object that contains one or more Dictionary objects. The following sample implementation of IPipelineComponent::Execute demonstrates how to use the Execute method's pdispOrder parameter to get an ISimpleList pointer on this collection:

HRESULT SampleComponentImpl::Execute(IDispatch *pDispOrder, IDispatch *pDispContext, long lFlags, long *pErrorLevel)
{
    HRESULT hr = S_OK;
    IDictionary *pDict = NULL;
    ISimpleList *pListItems = NULL;
    VARIANT var;

    BSTR bstrItems = SysAllocString(L"Items");

    // Call QueryInterface to get the OrderForm Dictionary.

    hr = pDispOrder->QueryInterface(IID_IDictionary, (void**)&pDict);

    if(FAILED(hr)){
        SysFreeString(bstrItems);
        return hr;
    }

    // Get the value of the "Items" Dictionary entry.

    if(SUCCEEDED(hr = pDict->get_Value(bstrItems, &var))){

    if(FAILED(hr)){
        SysFreeString(bstrItems);
        pDict->Release();
        return hr;
    }

    // Make sure that the value of the retrieved item is a COM     //object.

    if(V_VT(var) != VT_DISPATCH && V_VT(var) != VT_UNKNOWN)
        hr = E_UNEXPECTED;
        else
            hr = V_DISPATCH(&var)->QueryInterface(IID_ISimpleList, (void**)&pListItems);

    }

    VariantClear(&var)
    return hr;

}

For information about the IPipelineComponent, ISimpleList, and IDictionary interfaces, see Commerce Server Interfaces


Creating Property Pages for the ASP-Based Pipeline Editor

If you want to enable your component users to edit your component’s properties from within the ASP-based Pipeline Editor, you must create two Active Server Pages to support the component’s configuration.

The first of these pages, the edit page, is the one through which the component user sets the properties on the page. This page consists of HTML form fields that the user can modify to set your component’s properties.

This page must be assigned a name that is a composite of the component’s programmatic identifier (progID), in which the periods that appear in the progID are replaced by underscores (_). For example, the progID for the SQLItemADO component is “Commerece.SQLItemADO.1”. Consequently, the ASP through which this component can be configured is named Commerce_SQLItemADO_1.asp.

The second of these pages, the post page, is the page to which the configured properties are posted. The name of this page is the same as that of the first, except that “_post” is appended to the end of the filename (for example Commerce_SQLItemADO_1_post.asp).

The pages that make up your ASP-based property pages must reside in the \Microsoft Site Server\SiteServer\Admin\Commerce\Pipeline Configuration directory.


Header and Footer Files

Both the edit and post pages for your ASP-based property pages should include header and footer files included with Commerce Server. The files that you include depends upon how your component exposes its properties.

For components that implementing IPipelineComponentAdmin, you must include the pe_edit_header.asp file at the top of the edit page, and include the pe_edit_footer.asp file at the bottom of the edit page. The post page should include pe_global_edit.asp file at the top of the post page, and should include the pe_post_footer.asp file at the bottom of the page.

Components that expose their properties by implementing Automation properties must include the pe_3rd_party_edit_header.asp file that the top of the edit page, and the pe_3rd_party_edit_footer.asp file at the bottom of the edit page. In the post page, include pe_3rd_party_post_header.asp at the top of the page, and pe_3rd_party_post_footer.asp at the bottom of the page.


Sample Templates

A majority of the pipeline components included with Commerce Server 3.0 implement IPipelineComponentAdmin to support setting component properties using a configuration Dictionary. Consequently, for examples of how to build ASP-based property pages for components that implement this interface, you can refer to the ASP source for any of the Commerce Server for examples of how to build the edit and post pages for your component.

If your component exposes its properties by implementing Automation properties, you can use the template.asp and template_post.asp files as examples of how to create your property pages. These files are included in the \Microsoft Site Server\SiteServer\Admin\Commerce\Pipeline Configuration directory.

The following is the text of the template.asp file.

<%@ LANGUAGE = VBScript %>
<% REM############################################################ %>
<% REM                                                                           %>
<% REM   TEMPLATE.ASP                                                            %>
<% REM   Microsoft Commerce Server v3.00                                         %>
<% REM   Commerce Order Pipeline Editor                                          %>
<% REM                                                                           %>
<% REM   Copyright (c) 1996-98 Microsoft Corporation.  All rights <%reserved.      %>
<% REM                                                                           %>
<% REM ############################################### %>

<!--#INCLUDE FILE="pe_3rd_party_edit_header.asp" -->

field: <INPUT TYPE="TEXT" NAME="field" SIZE="70" VALUE="<%= ComponentConfig.field %>">

<!--#INCLUDE FILE="pe_3rd_party_edit_footer.asp" -->

The ComponentConfig object referenced on this page represents an instance of the component being configured, and field represents the name of the component’s dispatched property. For example, the MinMaxShip component dispatches the MinShipping and Percentage properties. To configure this component, the text above might be changed as follows:

field: <INPUT TYPE="TEXT" NAME="MinShipping" SIZE="70" VALUE="<%= ComponentConfig.MinShipping %>">

field: <INPUT TYPE="TEXT" NAME="Percentage" SIZE="70" VALUE="<%= ComponentConfig.Percentage %>">

The template_post.asp simply retrieves the values of the form fields submitted from the template.asp, and assigns the components dispatched properties the appropriate values.

<%@ LANGUAGE = VBScript %>
<% REM ################################################################# %>
<% REM                                                            %>
<% REM   TEMPLATE_POST.ASP
<% REM   Microsoft Commerce Server v3.00                            %>
<% REM   Commerce Order Pipeline Editor                           %>
<% REM                                                            %>
<% REM   Copyright (c) 1996-98 Microsoft Corporation.  All %>
<% REM     rights reserved.

<% REM ############################################################## %>

<!--#INCLUDE FILE="pe_3rd_party_post_header.asp" -->

<%
field = mscsPage.RequestString("field", null, 1, 255)
if IsNull(field) then
    errorList.Add "field must be a string between 1 and 255 characters in length"
else
    ComponentConfig.field = field
end if
%>

<!--#INCLUDE FILE="pe_3rd_party_post_footer.asp" -->


Using the Error Object

The pipeline returns an error message to the browser when a component fails (for example, if the Scriptor component is configured with a non-existent script). When writing a component, you should provide a descriptive error message that is displayed if the component fails for any reason. Because there is only one ERROR object per thread, you should always attempt to obtain the existing object and append your error description to that object before creating a new object. If the call to GetErrorInfo fails, no ERROR object has been created and you can then call CreateErrorInfo. For example:

ICreateErrorInfo*    pCErrInfo = NULL;
IErrorInfo*            pErrInfo = NULL;
HRESULT                hr = S_OK;
BSTR                    oldError = 0;
BSTR                    newError = 0;

if (GetErrorInfo(0, &pErrInfo) == S_OK) {

    hr = pErrInfo->GetDescription(&oldError);
    if (FAILED(hr)) goto error;

    newError = appendError(szDescription, oldError);

    pErrInfo->Release();
}
else {    // Call to GetErrorInfo failed
    newError = SysAllocString(szDescription);
}

hr = CreateErrorInfo(&pCErrInfo);
if (FAILED(hr)) goto error;

hr = pCErrInfo->QueryInterface(IID_IErrorInfo, (LPVOID FAR*) &pErrInfo);
if (FAILED(hr)) goto error;

hr = pCErrInfo->SetDescription(newError);
if (FAILED(hr)) goto error;

hr = pCErrInfo->SetGUID(riidCurrentInterface);
if (FAILED(hr)) goto error;

hr = pCErrInfo->SetHelpContext(dwHelpContext);
if (FAILED(hr)) goto error;

if (szHelpFile) {
    hr = pCErrInfo->SetHelpFile((LPOLESTR)szHelpFile);
    if (FAILED(hr)) goto error;
} else {
    hr = pCErrInfo->SetHelpFile( L"" );
    if (FAILED(hr)) goto error;
}

hr = pCErrInfo->SetSource((LPOLESTR)szSource);
if (FAILED(hr)) goto error;

// Set the structure
hr = SetErrorInfo(0, pErrInfo);

error:

if(pErrInfo) pErrInfo->Release();
if(pCErrInfo) pCErrInfo->Release();

static BSTR appendError(LPCWSTR newError, LPCWSTR oldError)
{
BSTR errorList;

LPOLESTR sep = L"\r\n";
int len = wcslen((LPWSTR)newError) +
    wcslen(sep) +
    SysStringLen((LPWSTR)oldError) + 1;
errorList = SysAllocStringLen(0, len);

wcscpy(errorList, (LPWSTR)newError);
wcscat(errorList, L"\n\r");
wcscat(errorList, (LPWSTR)oldError);
return errorList;
}

Related Topics

For more information, search for the following topics in MSDN:

  • υICreateErrorInfo
  • υIErrorInfo
  • υCreateErrorInfo
  • υGetErrorInfo
  • υSetErrorInfo


The Pipe Context

The PipeContext object is a Dictionary object which is passed through the pipeline as a holder of properties needed by pipeline components. The PipeContext is created as a page-level Dictionary object on the same page that creates the OrderPipeline object.

The PipeContext Dictionary object contains the following properties.

Property | Description
MessageManager | Name of the MessageManager object (created in Global.asa).
DataFunctions | Name of the DataFunctions object (created in Global.asa).
QueryMap | Name of the QueryMap object (created in Global.asa). The QueryMap is a Dictionary object that contains a number of other Dictionary objects, each of which represents a query name and the SQL text of the query.
ConnectionStringMap | A Dictionary object containing connection strings that are available to the site. (This property is copied from the Site Dictionary object.)
DefaultConnectionString | The default connection string for the site. (This property is copied from the Site Dictionary object.)
Language | The name of a message set (defined in the MessageManager object) containing error messages to be used by the pipeline components in the event of an error.
ReceiptStorage | DBStorage object for receipts (needed only if saving receipts).
Shopper | The Active User Object (AUO) representing the customer. A component in the pipeline will use the AUO to load ShopperInfo into the OrderForm.


Executing the Pipeline from an Application

In many situations, and particularly in the case of the Commerce Interchange Pipeline, it is useful to execute a pipeline from within an executable application, rather than within the context of an ASP file.

To do this, you create an OrderPipeline object, and request an IOrderPipeline interface pointer on that object. Then, you use the IOrderPipeline interface pointer to call the LoadPipe and Execute methods.

The following sample code illustrates this process:

// At the top of the file: necessary include directives.

#include "mspu_guids.h"
#include "pipeline.h"

// In the body of the function in which you execute the pipeline.

IOrderPipeline *pOrderPipeline = NULL;
long lErrorLevel = OPPERRORLEV_WARN;        // Tolerate warnings.

WCHAR *pwszPCF = L"c:\\Microsoft Site Server\\Sites\\Commerce\\Market\\SendHTTP.pcf";
HRESULT hResult;

// Initialize the COM library.

hResult = CoInitialize(NULL);

if(FAILED(hResult)){
    AfxMessageBox(IDS_CANT_INIT_COM, MB_OK);
    return;
}

hResult = CoCreateInstance(CLSID_COrderPipeline, NULL, NULL, CLSCTX_INPROC_SERVER, IID_IOrderPipeline, (void**)&pOrderPipeline);

if(FAILED(hResult)){
    AfxMessageBox(IDS_CANT_CREATE_PIPELINE, MB_OK);
    return;
}

hResult = pOrderPipeline->LoadPipe(pwszPCF);

if(FAILED(hResult)){
    AfxMessageBox(IDS_CANT_LOAD_PIPE, MB_OK);
    pOrderPipeline->Release();
    pOrderPipeline = NULL;
    return;
}

hResult = pOrderPipeline->Execute(0, pDispOrder, NULL, 0, &lErrorLevel);

This example assumes that the pDispOrder variable represents a valid IDispatch interface on the Dictionary or OrderForm object that contains the order information.


Commerce Server 3.0 and the Billing API

Microsoft® Site Server version 2.0 included a library (billingapi.lib) that exports the Billing Application Programming Interface (API). The Billing API defines a collection of C-language routines for writing billing events to a file on Site Server.

Site Server 3.0 includes a new version of this library, which has been updated to use the Commerce Server order processing pipeline (OPP). Applications built using the older library need only to re-link to the new one. This library file can be found in \Microsoft Site Server\SiteServer\Commerce\SDK\Commerce\lib\i386.

As currently implemented, the Billing API passes billing events to the OPP. Parameters passed to Billing API routines map to name/value pairs on the OrderForm that is passed to the OPP.

Consequently, in addition to re-linking to the new version of the Billing API library, you need to create the pipeline that processes Billing API events, and to register this pipeline in the Microsoft® Windows NT® system registry by writing the following value to \HKEY_LOCAL_MACHINE\Software\Microsoft\Microsoft Site Server 3.0
\Commerce Server 3.0\. The value that you write to this key should be named PCF, and its value should be a string that evaluates to the fully qualified path to the pipeline configuration file that is used to process billing events.

After you have re-linked your applications to this library, and registered a pipeline to process Billing API events, Billing API routines invoke this pipeline and pass it an OrderForm initialized with name/value pairs that map to parameters passed to the Billing API routines.

The following table describes the name/value pairs on the OrderForm, and the Billing API parameters to which they map.

Name | Parameter | Description
shopper_id | hAcctUid | Unique identifier for member (hAcct).
_billing_event | BeventId | Billing Event ID. Always TRANSACTIONEVENT.
vendor_id | hVendorID | Unique identifier for vendor (hAcct).
Purchase_type | DwEkind | Vendor Event ID (see the Billing API documentation).
Quantity | iNumUnits | Number of units.
MeasureID | Measure | Measure of each unit (see the Billing API documentation).
_oadjust_adjustedprice | dwUnitPrice | Price of each unit.
currencycode | iCurrencyCode | Type of currency used for the billing.
date_begin | dtbegin | End time for member’s actions. Win32® FILETIME data type.
date_end | dtend | End time for member’s actions. Win32 FILETIME data type.
event_desc | lpscDescription | Text description of the event.
_billing_result | Method result. | Return value from the billing system (see the table of return codes for routines defined in the Billing API documentation).
_product_name | lpszProductID | Text name of the product just purchased.
Token | Token | Token that was modified to give access to the product.
TransIPaddr | The dwIPaddr field of the TRANSACTION_ID structure. | IP address of the server that is processing the billing event.
TransTime | The ftUnique (FILETIME) member of the TRANSACTION_ID structure. | Time that the billing event was generated.
payment_method |  | Billing in the case of a BSMS component.
_billing_action |  | Identifies the Billing API 1.0 name of the routine that caused the pipeline to run. See Billing Action Values for a list of these values.


Billing Action Values

When a Billing Application Programming Interface (API) routine invokes the pipeline that you register, the routine identifies itself to the pipeline by writing a string representation of its name to the _billing_action name/value pair on the OrderForm. The following table contains the name/value pairs that Billing API routines write to this name/value pair, and the functions that these strings identify.

Value | Function
BillableEvent | ICPGenerateBillableEvent
CreditEvent | ICPGenerateCreditEvent
AuthBillableEvent | ICPBillAuthorizedUser
ExBillableEvent | ICPGenerateBillableEventEx
ExAuthBillableEvent | ICPBillAuthorizedUserEx
BillableUser | ICPIsUserBillable


Wallet Controls Overview

The Microsoft® Wallet version 2.1 helps shoppers purchase items quickly, easily, and securely at their favorite online stores. In addition, merchants benefit from an enhanced shopper experience through increased sales and shopper traffic at Web store sites.

The Microsoft Wallet 2.1 facilitates electronic transactions using the following tools:

  • υAddress Selector
  • υPayment Selector
Important

The Address Selector and Payment Selector are available as plug-ins for site visitors who use Netscape Navigator and as ActiveX™ controls for site visitors who use Microsoft® Internet Explorer.

The Wallet SDK provides the tools for third parties to extend the Microsoft payment platform with their payment types. The SDK contains the following sample code and documentation for third-party payment providers to develop payment extensions:

  • υSample code for credit card components
  • υSample code for third-party payment types
  • υSample code for Credit Card Payment Builders
  • υSample install .cab files for payment type distribution
  • υInterface technical references
  • υComplete documentation describing how to build and distribute payment types to extend the Microsoft payment platform.

Requirements

The Microsoft Wallet controls require Netscape Navigator version 3.0 or later, or Internet Explorer version 3.0 or later. In addition, the Microsoft Wallet can be used only at merchant sites that have scripted support for the controls on the payment page.

Microsoft Wallet

The Microsoft® Wallet consists of two ActiveX™ controls: an Address Selector and a Payment Selector. These controls facilitate an electronic purchase at a merchant Web site. Aside from providing a convenient method of posting shopper information to a merchant site, the Microsoft Wallet provides the most secure environment for storing credit card information.

A client payment component (CPC) object in the Payment Selector implements a payment method such as credit cards or electronic cash debit cards. The Credit Card CPC that ships with the Microsoft Wallet contains several default payment types, such as Visa, MasterCard, and so on. Using the Wallet SDK, you can create your own CPC to support other payment methods. For information about how to build a CPC, see the section “Sample Client Payment Component.”

You can also create new payment types (such as a department store card) that plug into the default Credit Card CPC. Shoppers can then add, delete, or edit instances of this new payment type in the same way they manage the default payment types. Because the are many varied types of credit cards, this payment type is referred to as the Other Card.

For information about how to build an Other Card payment type, see the section “Sample Other Card Component.”

The following diagram shows how the Payment and Address Selectors function within the Wallet architecture.

Migration from Microsoft Wallet Version 2.0

The Microsoft Wallet is upgraded to the most current version automatically when the shopper uses an outdated Wallet at a site that supports that latest version. Using an outdated Wallet generates a dialog box requesting the user’s approval to install version 2.1 of the Wallet. If the user approves the upgrade, version 2.1 of the Wallet is installed on the client computer transparently. All user data is transferred to the new Wallet storage, and is available to the shopper through the Wallet user interface.

Migration for Other Card Components

Note that version 2.1 of the Other Card components does not enter any information other than necessary registration of Component Object Model (COM) objects in the registry. All of the registry entries defining an Other Card are now created by the Credit Card CPC. In addition, the Wallet’s Credit Card CPC only permits installation of Other Card types that are unique. If a payment type already exists in the Payment Selector, installation of that type stops and an error is returned to the user.

Note

Other Card components created with version 1.0 of the Microsoft Wallet Kit will not work in version 2.1 of the Wallet. You must rebuild them. For information, see the section “Sample Other Card Component.”

Support

If you have any questions or issues about the Microsoft Wallet, contact our product support team at mswallet@microsoft.com.

Signing Controls

If you use the Wallet SDK to build a Client payment component, PIP or Other Card, you must sign the resulting .dll, the associated .cab file, or any other extension to the Wallet before it can be loaded by the Payment Control. Signing your file makes it possible also for Microsoft's Authenticode™ technology identify the publisher of software to users before the user downloads this software from the Internet.

To sign your code
  1. Download the latest version of Microsoft® Internet Explorer version 3.0 from http://www.microsoft.com/ie/download.
  2. Apply for credentials from a Certificate Authority (CA). Go to http://www.microsoft.com/workshop.prog/security/authcode/certs.htm for instructions on how to obtain a Software Publisher's certificate from a CA. After identifying the CA from which you want to obtain a certificate, visit the CA's Web site to fill out an online certificate application.

    Once you have completed this application, it will take approximately one week for the CA to verify your information. Once the CA has verified the information you have provided, the CA will issue you credentials and a private key that you must store securely. You need both the provided credentials and the private key to sign your code.

  3. Get the latest version of the ActiveX™ Software Development Kit (SDK). You can download the latest version of the ActiveX SDK from http://www.microsoft.com/workshop/prog/sdk/. The tools that you use to sign your code are included in the SDK. Consult the code-signing documentation provided in the SDK for additional information on using these tools.
  4. Prepare your files to be signed. If you are building any PE file (.exe, .ocx., .dll, or other), you do not need to do anything special to prepare the files. If you are using a .cab file to distribute your control, you need to add the following entry to your .ddf file before creating the .cab file:

    Set ReservePerCabinetSize=6144

  5. Sign your files. You can now use the ActiveX SDK to sign your .exe, .cab, .ocx, or .dll file. Currently, only 32-bit files can be signed.

    The following is an example of how to use signcode.exe, which is included in the ActiveX SDK, to sign your files:

    signcode -prog myfilename -name displayname -info http://www.mycompany.com -spc mycredentials.spc -pvk myprivatekey.pvk
  6. The following table describes the parts of this example command.
    Command Part | Meaning
    myfilename | Name of the file to sign.
    displayname | Description of the file that will show up in the certificate.
    http://www.mycompany.com | Should provide the user with more information about the file to be downloaded.
    mycredentials.spc | Name of the credentials file obtained from the CA.
    myprivatekey.pvk | Private key that was generated during the application process with the CA.

    Note that if you invoke signcode.exe without any parameters, it will run a wizard that will step you through the signing process.

  7. Test your signature.
    • υTo test a signed .exe, .dll or .ocx file, run chktrust filename.
    • υTo test a signed .cap file, run chktrust -c cabfilename.cab.

If your signing process was successful, running chktrust as described previously will bring up a certificate.

The Wallet and the Protected Store

Microsoft's Protected Store, which is a component of Internet Explorer 4.0, supports securely storing important, private information, such as credit cards, electronic drivers licenses, ATM cards, and electronic cash. The Protected Store stores this information such that no one can access this information without the user's permission. Additionally, the Protected Store allows this information to be securely transmitted to any computer and used with any application through the user of PFX technology.

The Wallet is designed so that if Internet Explorer 4.0 is installed on a system, Payment control data is automatically migrated to the Protected Store.

Address Selector

The Address Selector stores users’ personal and business addresses securely on their computer. To add an address, a user completes a dialog box with business or personal address information that is stored according to a display name or nickname. Shoppers at merchant Web sites that support the Microsoft Wallet can select addresses from the Address Selector by their display name, without having to fill out a series of merchant HTML forms. Address information is stored securely on the client computer and only released to the merchant if the user clicks OK in an Address Security dialog box.

The ten addresses most recently selected by the user are displayed in a drop-down list in the Address Manager. Users can access the remainder of their addresses by clicking the All addresses button, which generates a dialog box that lists all other addresses in the Wallet storage.

The Address Selector is fully integrated with the Windows Address Book (WAB), if the WAB is on the user’s computer. Clicking the Address Book button of the Address Selector allows users to select from addresses in their Windows Address Book and add them to the Address Selector.

Payment Selector

Users can complete online transactions using the Payment Selector to choose a type of payment. The Payment Selector currently contains the VISA, MasterCard, JCB (only in Japan), American Express, and Discover (only in North America) payment types. Other third-party payment providers are developing payment types that extend the Microsoft Wallet payment platform. Third-party payment types range from a bank debit card to an electronic cash card. In addition, merchants who want to offer branded credit cards can easily write components to plug into the Payment Selector interface. The Payment Selector can store any number of credit card types.

The Payment Selector Add Wizard guides Wallet users through establishing a new credit card by entering credit-card information, providing a billing address, and assigning a password to the credit card. The credit-card information is encrypted and stored in the Wallet protected storage on the client computer.

If a merchant site supports the Microsoft Wallet, shoppers can quickly and easily select their preferred type of payment from the Payment Selector without having to complete HTML forms for billing and credit-card information. The ten credit cards most recently used are displayed in a drop-down list. The remainder of credit cards in the Wallet are displayed by clicking the All payment types button. Payment information is stored securely on the client computer and released to the merchant only if the user enters the credit-card password to approve the purchase amount.

Note

A single Payment Selector can store credit cards owned by different people, because each credit card is protected from improper use by a password assigned by the cardholder.

Using the Controls

For information about how to use the Microsoft Wallet controls on a Web page, see Understanding the Script in the Webmaster Kit Samples.

Wallet Security

The Microsoft® Wallet provides shoppers with secure and convenient storage for their payment and address information. Credit-card information is encrypted and stored in the Wallet protected storage.

The Microsoft Wallet also contains a Payment Builder interface that allows third party encryption methods to plug into the Payment Selector’s Credit Card component. This encryption interface supports extensions such as the SET protocol that provide additional security during the payment process. The appropriate encryption protocol can be selected by the Credit Card component based upon the Accepted Types string. The Payment Selector’s Payment Builder interface allows shoppers to conduct electronic transactions using the most secure encryption available for their credit-card information.


Sample Client Payment Component

The sample client payment component (CPC) contains sample source files and accompanying documentation that you can use to build a client payment component that is supported by the Payment Selector control. The CPC object stores instances of your payment type. Instances are added, deleted, and modified using the user interface of the Payment Selector. The Payment Selector user interface also allows the user to choose your payment type from the Payment Selector to make online purchases.

The Payment Manager manages a new CPC using the member functions of the IClientPaymentProvider interface. Your payment option is displayed by the Payment Selector user interface when your CPC registers with the Payment Selector.

The following diagram illustrates how the CPC functions within the Microsoft® Wallet architecture.

CPC in Wallet architecture

A CPC object in the Payment Selector represents a payment method such as credit cards or electronic cash debit cards. Each CPC supports one or more types of that method. For example, a type of a credit card payment method is a VISA card. Each CPC may contain zero or more instances of any type supported by that CPC. Each instance possesses a friendly name that is unique across all CPCs in the Payment Selector.

The Payment Selector provides the consumer with a rich user interface for managing and selecting instances of payment types. Payment types (such as a VISA, bank, or department store card) are stored in the Payment Selector. When a user creates a new instance of an existing payment type (such as a second bank card), that instance is stored by the payment type component. These instances are locally managed according to a friendly name that is assigned by the user. Note that instances of payment types are never shared between different components in the Payment Selector.

After a consumer selects an instance of a payment type from the Payment Selector, a payment instruction (PI) is generated in that payment type component, routed through the Payment Selector, and sent over the browser to the server for the merchant to process payment. The PI may be encrypted and will pass through the Payment Selector as opaque data.

Refer to the “Client Payment Component (CPC) Interfaces” section for a detailed description of the CPC interfaces and function syntax.

Required Tools

Building a CPC consists simply of building an in-process Component Object Model (COM) server that implements the appropriate interfaces. The sample included this chapter illustrates this process.

To build and configure the sample CPC described in this chapter requires the following tools:

  • υSample client payment component files
  • υActiveX™ Template Library 2.1 or later.
  • υMicrosoft® Visual C++® version 5.0
  • υMicrosoft® CABinet Development Kit
Note

All CPCs must be in-process COM objects.

The CPC sample files in the Microsoft® Wallet SDK provide the dialog boxes, registry controls, utility routines, multiple-threading support, and other source files that you need to construct your own component. With these tools and a few modifications to the provided sample code, you can build a CPC that creates and stores instances of its payment type.

The Microsoft CABinet Development Kit, which you can download from http://www.microsoft.com/intdev/cab/tools.htm, provides the compression and decompression tools used to distribute your CPC in easy-to-install cabinet files. With the CABinet Development Kit tools, you can use the sample installation files to distribute your CPC from your Web page.

Creating a CPC

The client payment component (CPC) sample files (located in the \SDK\Wallet\Samples\CPCs\Simple directory) give you the framework to build your CPC by providing dialog boxes, multiple thread support, source files, and installation files. The following diagram explains the process of building a CPC using these sample files.

Note

The Wallet SDK sample CPC, which is named Internet Cash, is designed for a single type of payment. A component supports multiple types, but each type must be unique. For example, the default Credit Card component in the Payment Selector contains three unique types: VISA, MasterCard, and American Express.

Dialog Boxes

The following dialog sample files generate the dialog boxes required by a component.

File name | Function
AddDlg.cpp | Provides the Internet Cash Add dialog box for adding new instances of the sample CPC payment type (ATL Wizard generated).
EntPass.cpp | Enables the Internet Cash Use dialog box that asks the user for a password on any modify operations on an instance of a CPC payment type.
ModDlg.cpp | Provides the Modify Internet Cash dialog box for the user to modify an instance of the CPC payment type.
NewPass.cpp | Adds the Password dialog box. The CPC uses a wizard to step the user through the process of adding a password.
PIPass.cpp | Enables the Password dialog box that prompts the user for a password before posting information. Although this dialog box is not a requirement, you should provide the consumer with some notice when money is about to be spent. You must decide how to handle this prompting; instances such as microtransactions involving a few pennies may not warrant a warning. The Delete operation does not require a password. If a user forgets a password, the method of payment can be deleted and a new instance added.

The source files that enable sample dialog boxes are standard Microsoft Developer Studio™ Wizard creations; they interact with the user to obtain information specific to the CPC, and are not very rich in sample format. The Payment Selector has a certain level of richness in its user interface that you should support when building your own dialog boxes. For example, the Add Card Wizard in the Payment Selector contains instructions for the user to explain the process of adding and using a method of payment. While building your dialog boxes, maintain the same level of richness in the dialog box user interface that the Payment Selector user interface offers.

Building a CPC

You can use the following sample source files (located in the \CPC\sample directory) to set up your component’s DLL, access the component IClientPaymentProvider and IWalletCallback interfaces, and make changes to the registry.

File name | Function
common.h | Header file that sets the macros for checking error codes. Provides entry keys for registering the CPC with the Payment Selector.
cpcinst.cpp | Contains all interfaces used during installation of the CPC.
CPCPlugIn.cpp | ATL-generated file that handles DLLMain integration and MFC CWinApp creation. This file has been modified for MFC threading support.
sdkobj.def | ATL Wizard–created CPC .def file.
cpcbject.mak | Make file generated by the CPC project.
CPCPlugIn.idl | File that defines the CPC object, which is read by the MIDL compiler.
CPCPlugIn.rc | CPC resource file.
CPCObject.cpp | Implements the member functions of the CPC interfaces.
regutil.cpp | Implements a generic registry class that registers the CPC.
utility.cpp | Defines simple utility routines used by the CPC object.

Source File Modifications

common.h

This header file sets the macros for checking error codes and also provides the proper registry entry keys for registering the CPC with the Payment Selector. Use the unique name of your CPC as listed in the \CPCPlugIn directory to register the component.

The file common.h contains the comment MOD TODO in each line requiring modification. Search the file for the MOD TODO string and replace the default sample name Internet Cash with the unique name of your CPC:

// MOD TODO:  You must create a key in the registry that reflects your CPC name.  To do this you must
//    replace "Internet Cash" with the name of your CPC.
//
#define  RV_CCPLUGIN        TEXT("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Internet Shopper\\PlugIns\\Internet Cash")
#define  RV_CPCINSTALL        TEXT("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Internet Shopper\\Install")
#define  RK_CHANGECOUNT        TEXT("ChangeCount")
#define  RK_CPC_STATE        TEXT("State")

Generate new programmatic identifiers (ProgIDs) for your CPC. The Payment Selector uses the ProgID to load the CPC. Note that the CPC ProgID must match the ProgID assigned in CPCPlugIn.cpp:

// MOD TODO:  You must create a unque PROGID that reflects the name of the CPC.  The PROGID is used by the Wallet to load the CPC.  This PROGID must match the PROGID found in sdkplugin.cpp.
#define  RK_PLG_VAL_CCPROGID TEXT("CPCPLUGIN.CPCPlugInObject.1")

Refer to the OLE Programmer’s Reference in the Win32® SDK for information regarding programmatic identifiers.

CPCPlugIn.cpp

This key source file is generated by the ATL Wizard, and handles DLLMain integration and the MFC CWinApp creation.

It is important to note that the sample file provided has been modified to address MFC threading support for the component. If you do not use the sample file, you must devise a way to handle multiple threading and multiple processes on the client payment component level.

CPCPlugIn.def, CPCPlugIn.mak, and CPCPlugIn.rc

The CPCPlugIn.def file is created by the ATL Wizard, the CPCPlugIn.mak file is the make file generated by the sample CPC project, and the CPCPlugIn.rc file is the resource file used by your CPC.

CPCPlugIn.idl

The CPCPlugIn.idl file defines the CPC object. The MIDL compiler reads this file and then generates the type libraries and other linker files.

You should assign new globally unique identifiers (GUIDs) to configure the sample file for the CPC that you build. The file CPCPlugIn.idl contains the comment MOD TODO in each line requiring modification. Search the file for the MOD TODO comment and replace the existing GUID:

import "oaidl.idl";
import "ocidl.idl";

#include "iWalletCB.idl"
#include "iWalletCB2.idl"
#include "icpc.idl"
#include "ipayinst.idl"

// MOD TODO: Change all occurences of MyCPC to <YourCPCName>
//

// MOD TODO: you need to replace the following two uuid's with new generated
//        uuid's.  These are used to identify your object and typelib.

[
    uuid(5AC9D181-EC1A-11D0-BB19-00AA00A13794),
    version(1.0),
    helpstring("MyCPC 1.0 Type Library")
]
library MyCPCLib
{
    importlib("stdole32.tlb");
    importlib("stdole2.tlb");

    [
        uuid(5AC9D18F-EC1A-11D0-BB19-00AA00A13794),
        helpstring("MyCPC Class")
    ]
    coclass MyCPC
    {
        [default] interface IClientPaymentProvider;
        interface IPaymentProviderInstall;
    };
};

Refer to the MAPI Programmer’s Reference in the Win32 SDK for more information on creating new GUIDs.

regutil.cpp

This source file implements a generic registry class that controls registration with the Payment Selector.

CPCObject.cpp

This source file implements the member functions of the IClientPaymentProvider and ISelectorCallback interfaces that are used to create and configure payment types in the consumer’s Payment Selector.

In the CPCObject.cpp file, you will need to modify most of this code to support the CPC you are creating. The file CPCObject.cpp contains the comment MOD TODO in each line requiring modification. You can search the file for the MOD TODO comment to make required changes.

Change the friendly name from the default Internet Cash to the friendly name of your CPC:

// MOD TODO:  This is the Friendly Name of the CPC type. You must change "Internet Cash" to the friendly name of your CPC.
//
#define SDK_TYPE L"Internet Cash"
static CString szType = SDK_TYPE;

Modify the accepted type and short name to reflect the friendly name of your CPC:

// MOD TODO:  This is the Accepted Type (and short name) of the type of this CPC.  You must change "ICash" to the short name of your CPC.
//
#define SDK_ACCEPT_TYPE _T("ICash")
CString szThisType = SDK_ACCEPT_TYPE;

Change the fields PAYMENT_TYPE, PAYMENT_ACCOUNT, and PAYMENT_AMOUNT given in the sample to reflect the fields that are being posted back as part of the payment instruction:

// MOD TODO: You should change this to reflect the fields that are being // posted back as part of the payment instruction. This defines a set of // constants and the names that are found in the post.
//
#define PAYMENT_TYPE        0
#define PAYMENT_ACCOUNT        1
#define PAYMENT_AMOUNT        2
static const cPaymentElements = 3;        // MOD TODO: Should reflect the total number

static OLECHAR *rgszFieldNames[] =
{
    L"Type",
    L"Account",
    L"Amount",
};

To prevent multiple processes from accessing critical sections, you should replace the sample mutex name “ICashSamplePlugin” with the unique name of your CPC:

// MOD TODO:  You need to change the name of the Mutex to something that // reflects the CPC name.
//
    m_hMutex = CreateMutex(
        NULL,                        // No Scurity
        FALSE,                        // initially not owned
        "ICashSamplePluginMutex");    // name of the Mutex
    if (m_hMutex == NULL)
        return;

    do {
        dwWaitResult = WaitForSingleObject(
                m_hMutex,                // handle of mutex
                1000L);                    // Wait for 1 second

Change the sample mapping file name “ICashSamplePlugin” to the unique name of your CPC:

// MOD TODO:  You need to change the name of the Mapping file to something that reflects the CPC name.
//
        if (dwWaitResult ==    WAIT_OBJECT_0) {
            m_hMapObject = CreateFileMapping(
                (HANDLE) 0xFFFFFFFF,        // Use the Paging File
                NULL,                    // No security
                PAGE_READWRITE,            // Read/Write access
                0,                        // size: high 32-bits
                sizeof(InstanceShare),    // size: low 32-bits
                "ICashSamplePluginShare");
            if (!m_hMapObject)
                return;
            fInit = (GetLastError() != ERROR_ALREADY_EXISTS);

Replace the fields “PAYMENT_TYPE,” “PAYMENT_ACCOUNT”, and “PAYMENT_AMOUNT” in the sample code with the fields that will be posted back as part of the payment instruction. The SAFEARRAY will consist of name/value pairs whose names and values are stored as BSTRs:

// MOD TODO:  This section of code will build the SAFEARRAY of name/value pairs that is posted back to the server.
//
    FillVariants(pvar, PAYMENT_TYPE, cPaymentElements, SDK_ACCEPT_TYPE);
    FillVariants(pvar, PAYMENT_ACCOUNT, cPaymentElements, m_pData->m_gData[dwIdx].Name);
    FillVariantsWide(pvar, PAYMENT_AMOUNT, cPaymentElements, bstrTotal);

    hr = S_OK;

Explanation and examples of function syntax are provided in the “Client Payment Component (CPC) Interfaces” section.

utility.cpp

This source file defines a simple utility routine used by the CPC object, and provides a message box. You can modify this program to perform routines on the CPC that you create.

Using Visual C++

After modifying the client payment component (CPC) sample source files, you are ready to build your CPC DLL. The CPCPlugIn.dsw file is a Microsoft® Visual C++® makefile that you can use to build a sample CPC. If you use this makefile to build your CPC DLL, you must change all references to “cpcplgin” to the name of the payment method that you are building. It is recommended, however, that you let Developer Studio create a makefile for you by creating a new Developer Studio project workspace.

To create a new CPC
  1. Copy the files in the Simple directory to the directory in which you want to build your CPC.
  2. Modify the project dependencies that reference the Samples\Common directory.
    • υChange the project options preprocessor includes to reference Samples\Common.
    • υChange the custom build for pmntBuild.idl. The /I..\..\Common should be changed to reference Samples\Common.
    • υRemove and re-add the regutil.cpp and regutil.h files to the project.
    • υOptionally, change the output file specified in the Build Settings /linker flags. If you choose to do this, you must also change the name in the .def file.
  3. Edit the source files (including the .idl and .rgs files). Locate the places in the files that are marked // MOD TODO. These markers identify the places in the source files that need to be changed.
  4. Because comments are not allowed in the .rgs file, you must change the globally unique identifier (GUID) specified in that file to the coclass GUID that you specified in your .idl file. Additionally, change all references to "MyCPC" to the name of your CPC.
  5. Change the base address in the Project Settings/link options/Output. If this is the same as another component's base address it significantly slows down the load process.

If you encounter any problems creating your own version of this sample, or if you lack experience with Visual C++ 5.0, you can create a Component Object Model (COM) object by any means with which you are familiar. This object must implement ICreditCardEncryption2 and IPaymentProviderInstall.

Multiple Threading

The Payment Selector supports single processes with multiple threads and multiple processes with one or more threads. During the Add, Modify, and Delete functions, mutexes in the Payment Selector permit only one thread at a time to modify data. Each component is required to share its data among both multiple threads within a single process and multiple processes. Modifications using one instance of the control must be reflected in all instances. The SDK sample uses shared global memory to implement this requirement. You must ensure that multiple instances of the Create function are thread safe.

The SDK sample uses the following elements to ensure thread safety:

  • υMFC 4.0 (installed with Visual C++ 4.1)
  • υthrdwrap.cpp
  • υthrdwrap.h
  • υthrdchk.h

The MFC CWinApp class captures and transforms the first thread into an MFC thread in the component data structure when the DLL is loaded. The SDK files thrdwrap.cpp and thrdchk.h create the necessary threading structures within MFC to make MFC thread safe within a single process, independent of the shared global data structure. The thrdwrap.cpp file, which includes the thrdwrap.h header file, implements a thread class and checks thread routines to ensure that MFC has the necessary information to perform thread-safe processes. The thrdchk.h header file defines the entry points to the current thread to check whether or not it exists.

Although the majority of multiple-thread and multiple-process support occurs in the Payment Selector, you must provide a mutex for the Create function to ensure that new instances of the component are created in a thread-safe manner.

To verify that your CPC supports multiple threading
  1. Start Internet Explorer version 3.0 or later.
  2. Open your local HTML page containing the Payment Selector control.
  3. On the File menu, click New Window to create a second copy of the control. The second copy of the control is run on a new thread within the original process.
  4. Test the second thread to verify multiple threading in the control.
Note

Do not modify the sample files thrdwrap.cpp and thrdchk.h, because these files support thread-safe processes in MFC.

See the Win32 Programmer’s Reference for additional information on creating a mutex.

Distribution

After you have built your client payment component (CPC), users of your Web site will have to download and register the component. To accomplish this, you can customize the files located in the \CPCPlugIn\download directory.

To enable users of your card to download the Other Card plug-in
  1. Copy the OtherCard.inf file to the directory in which you want to create the .cab file.
  2. Copy your .dll file into the directory in which you have placed the OtherCard.inf file.
  3. Edit the .inf file and BuildCab.bat and replace all references to OtherCard in these files with references to your card.
  4. Run the BuildCab.bat file to make the .cab file, and reference this .cab within the <OBJECT> tag that references your object. For an example of this tag's use, see SDK\Wallet\Samples\Install\OtherCard.htm.

Distribution for Microsoft Internet Explorer

For users of Microsoft® Internet Explorer version 3.0 and later, create a link on your Web page to the .cab file. When users load the Web page, the control and plug-in will be downloaded, installed, and registered automatically. For example:

<html>

<head>
<title>Standard Client Payment Component Install</title>
<meta name="GENERATOR" content="Microsoft FrontPage 1.1">
</head>

<OBJECT id=paySelector classid="clsid:3B23ADA5-E00D-11CF-8EE7-00A0C9054334"
        codebase="http://example.microsoft.com/testpay/cpcplugin/cpcplugin.cab#Version=1,0,0,1135"
        width=300 height=250 >
    <PARAM Name="AcceptedTypes" Value="visa:clear;mastercard:clear;amex:clear;discover:clear" >
    <PARAM Name="Total" Value="134.50" >
</OBJECT>

</html>

You can also create a link that allows the user to explicitly download the CPC:

<BODY>
<h2> <align=center><a href="cpcplugin.cab">Install Client Payment Component DLL</a> </h2>
</body>

</html>

Distribution for Netscape Navigator

The procedure for installing the CPC DLL is somewhat different for users of Netscape Navigator. To support these users, build a self-extracting executable file for download. The program that extracts files from .cab files, EXTRACT.EXE, will automatically extract the files in that .cab file (and any subsequent .cab files) if it has been prefixed to the first .cab file.

To build a self-extracting executable file
  1. Create a .cab file (or set of .cab files) as described previously.
  2. At a command prompt, prefix EXTRACT.EXE to the first .cab file (do not prefix EXTRACT.EXE to any other .cab files in the set).
  3. Distribute the self-extracting .cab file (and any subsequent .cab files).

For example:

C:> diamond /f cpcplugin.ddf        ; Build CAB file set cpcplugin.cab
C:> copy /b extract.exe+cpcplugin.cab cpcplugin.exe        ; cpcplugin.exe is self-extracting

Create a link on your Web page to the self-extracting executable for users to download. For example:

<html>

<head>
<title>Standard Client Payment Component Install</title>
</head>

<BODY>
<h2> <align=center><a href="cpcplugin.exe">Install Client Payment Component DLL</a> </h2>
</body>

</html>

Next, you must create a setup program that installs the files to their appropriate directories and registers them.

For information about .cab files and self-extracting archives, see the following Web site:

http://www.microsoft.com/workshop/java/cab.htm

Code Signing

After you have built your CPC, you should get a digital signature for your component to provide accountability to users downloading from your Web site. Supported in Internet Explorer 3.0, Authenticode™ is Microsoft’s implementation of its code-signing proposal to the W3C. Authenticode uses documented Win32® functionality available to any Microsoft® Windows® 95–based or Microsoft® Windows NT®–based application, and works with Java applets, plug-ins, and ActiveX™ controls to provide accountability for these types of software components. Through Authenticode, end users know who published a piece of software and whether the software has been tampered with, before downloading the software to their PC. Note that Netscape Navigator 3.0 does not support Authenticode or any code-signing technology. For information about code signing, refer to http://www.microsoft.com/intdev/security.

Client Payment Component (CPC) Interfaces

In addition to Credit Card component extensions, the Payment Manager supports instances of client payment components (CPCs) that offer other payment types other than credit cards (such as electronic cash). The following interfaces support a CPC and the installation of a CPC:

  • υIClientPaymentProvider
  • υIWalletCallback (Payment Manager interface)
  • υIPaymentInstall (Payment Manager interface)
  • υIPaymentProviderInstall

Use the functions in the client payment component (CPC) interfaces to offer additional payment types in the Microsoft Payment Selector. The Payment Manager calls methods on the IClientPaymentProvider interface to create and manage instances of a payment type in your CPC. The IWalletCallback interface methods guarantee that instances of payment types have unique names across all components in the Payment Selector. You can use these interfaces to present instances of your payment type (or types) as an option for Payment Selector users during online purchasing transactions. You must implement all the methods in the IClientPaymentProvider interface in order for the Payment Selector to fully support your CPC. In addition, call functions on the IPaymentProviderInstall interface in order to support the installation package for your CPC.

Note

As a COM object, a CPC is responsible for its own memory allocation. When the reference count is zero, the CPC frees memory allocated to that object. All calls may return the E_OUTOFMEMORY (memory allocation failure) value.

A CPC object in the Payment Selector represents a payment method such as credit cards or electronic cash debit cards. Each CPC supports one or more types of that method. For example, a type of a credit card payment method is a VISA card. Each CPC may contain zero or more instances of any type supported by that CPC. Each instance possesses a friendly name that is unique across all CPC modules in the Payment Selector.

The Payment Selector provides the consumer with a rich user interface for managing and selecting instances of payment types. Payment types (such as a VISA, bank, or department store card) are stored in the Payment Selector. When a user creates a new instance of an existing payment type (such as a second bank card), that instance is stored by the payment type component. These instances are locally managed according to a friendly name that is assigned by the user. Note that instances of payment types are never shared between different components in the Payment Selector.

After a consumer selects an instance of a payment type from the Payment Selector, a payment instruction (PI) is generated in that payment type component, routed through the Payment Selector, and sent over the browser to the server for the merchant to process payment. The PI may be encrypted and will pass through the Payment Selector as opaque data.

All individual elements stored inside a CPC are retrieved by an index position. The accessor is treated as a zero-based array. There is no order imposed on the array and elements may move in the array during the lifetime of the object. For example, a delete operation will not leave a hole in the array. The index positions will change only during add or delete operations.

IClientPaymentProvider Interface

The IClientPaymentProvider interface is called from the Payment Selector and provides the following methods to create and modify instances of payment types in a CPC:

  • υCreate
  • υManagePaymentInstance
  • υTerminate
  • υGetBitmap
  • υGetTypeCount
  • υGetTypeBitmap
  • υGetSupportType
  • υExists
  • υGetInstanceCount
  • υGetChangeCount
  • υGetFriendlyName
  • υIsValid
  • υGetInstanceType
  • υIsTypeValid
  • υNewPaymentInstance
  • υGeneratePaymentInformation
  • υDeletePaymentInstance

IClientPaymentProvider::Create

Syntax

HRESULT Create(
IWalletCallback *piCB// in
);

Description

The Create function is the initialization member function, and must be called before any other function is called. All other functions will fail if called before Create.

Parameters

piCB
Interface pointer that permits the CPC to transfer and receive data from the Payment Manager.

Return Value

This function returns one of the following values.

Value | Meaning
S_OK | Success
E_FAIL | Failure
E_OUTOFMEMORY | Out of memory

Remarks

During add and modify operations, the IWalletCallback::Exists function must be called to verify that no instance with the same friendly name exists across Payment Selector components.

Related Topics

  • υIWalletCallback::Exists

IClientPaymentProvider::Terminate

Syntax

HRESULT Terminate(void);

Description

The Terminate function releases resources allocated by the object (the class destructor should also free these resources).

Parameters

None.

Return Value

This function returns the following value.

Value | Meaning
S_OK | Success

IClientPaymentProvider::GetTypeCount

Syntax

HRESULT GetTypeCount(
long *pcRet// out
);

Description

The GetTypeCount function returns the number of types currently enabled in the CPC. All CPCs support at least one type but may have zero or more types disabled by the Payment Manager.

Parameters

pcRet
Pointer to the location where this function will return the count of the number of payment types enabled in the CPC. For example, the return value would be 2 for a Credit Card component that supports VISA and MasterCard, if both are enabled.

Return Value

This function returns one of the following values.

Value | Meaning
S_OK | Success
E_FAIL | Failure

IClientPaymentProvider::GetSupportType

Syntax

HRESULT GetSupportType(
long cIndex// in
BSTR FAR *pRetType// out
);

Description

The GetSupportType function returns the friendly name for a payment type based on the index position. This includes only the enabled types. The friendly name for a type is the string presented to a consumer for identification (for example, “American Express”). Valid values of an index are zero through GetTypeCount minus one.

Parameters

cIndex
Index of the payment instance in the list of instances registered by the CPC.
pRetType
String containing the friendly name for the specified payment type.

Return Value

This function returns one of the following values.

Value | Meaning
S_OK | Success.
E_INVALIDARG | One or more of the arguments is invalid.
E_OUTOFMEMORY | Out of memory.
E_FAIL | Failure.

IClientPaymentProvider::GetInstanceCount

Syntax

HRESULT GetInstanceCount(
long FAR *pcRet// out
);

Description

The GetInstanceCount function returns the total count of instances stored in the CPC, for all of the enabled types. Note that there is no way to check the number of instances of each type other than counting them.

Parameters

pcRet
Pointer to the location where this function will return the count of the number of payment instances created by the user in a given CPC. Any instance of any payment type known to the CPC is counted.

Return Value

This function returns one of the following values.

Value | Meaning
S_OK | Success
E_FAIL | Failure

IClientPaymentProvider::GetFriendlyName

Syntax

HRESULT GetFriendlyName(
long cIndex// in
BSTR FAR *RetName// out
);

Description

The GetFriendlyName function returns the friendly name for an instance based upon index position. Valid values of an index are zero through GetInstanceCount minus one.

Parameters

cIndex
Index of the payment instance in the list of instances registered with the CPC.
RetName
Pointer to the location where this function will return the friendly name of the payment instance at the specified index.

Return Value

This function returns one of the following values.

Value | Meaning
S_OK | Success.
E_INVALIDARG | One or more of the arguments is invalid.
E_OUTOFMEMORY | Out of memory.
E_FAIL | Failure.

IClientPaymentProvider::GetInstanceType

Syntax

HRESULT GetInstanceType(
long cIndex// in
BSTR FAR *pRetType// out
);

Description

The GetInstanceType function returns the friendly name of an instance’s type based upon the index.

Parameters

cIndex
Index of the payment instance in the list of instances registered with the CPC.
pRetType
Pointer to the location where this function will return the name of the type of the payment instance at the specified index.

Return Value

This function returns one of the following values.

Value | Meaning
S_OK | Success.
E_INVALIDARG | One or more arguments is invalid.
E_OUTOFMEMORY | Out of memory.
E_FAIL | Failure.

IClientPaymentProvider::NewPaymentInstance

Syntax

HRESULT NewPaymentInstance(
BSTR bstrType// in
long FAR *pcIdx// out
);

Description

The NewPaymentInstance function adds a new instance to the CPC. When this function is called, the Payment Selector provides the appropriate type of the instance and the CPC returns the index position of the new instance.

Parameters

bstrType
String identifying the payment type of the new instance.
pcIdx
Pointer to the location where this function will return the index to the newly created payment instance.

Return Value

This function returns one of the following values.

Value | Meaning
E_INVALIDARG | One or more of the arguments is invalid.
E_OUTOFMEMORY | Out of memory.
E_FAIL | Failure.
S_FALSE | Cancel by user.
S_OK | Success.

Remarks

During add and modify operations, the IWalletCallback::Exists function must be called to verify that no instance with the same friendly name exists across payment modules.

Related Topic

  • υIWalletCallback::Exists

IClientPaymentProvider::DeletePaymentInstance

Syntax

HRESULT DeletePaymentInstance(
BSTR bstrFriendName// in
);

Description

The DeletePaymentInstance function deletes an instance from the CPC.

Parameters

bstrFriendName
Friendly name of the instance to delete.

Return Value

This function returns one of the following values.

Value | Meaning
E_INVALIDARG | One or more of the arguments is not valid.
E_OUTOFMEMORY | Out of memory.
E_FAIL | Failure.
S_OK | Success.

IClientPaymentProvider::ManagePaymentInstance

Syntax

HRESULT ManagePaymentInstance(
BSTR bstrFriendName// in
long FAR *pcIdx// out
);

Description

The ManagePaymentInstance function allows the user to modify an instance in the CPC. This function identifies an instance by its friendly name and returns its index position to the caller.

When building the CPC, you may choose not to permit modifications to the friendly name of an instance. Note that IClientPaymentProvider::Exists should be called only when the friendly name has changed. If the friendly name has not changed, then you should not call the Exists function.

Parameters

bstrFriendName
Friendly name of the instance to modify.
pcIdx
Index to the newly modified payment instance.

Return Value

This function returns one of the following values.

Value | Meaning
E_VALIDARG | One or more of the arguments is invalid.
E_OUTOFMEMORY | Out of memory.
E_FAIL | Failure.
S_OK | Success.
S_FALSE | Cancel by user.

Remarks

During add and modify operations, the IWalletCallback::Exists function must be called to verify that no instance with the same friendly name exists across CPCs.

Related Topics

  • υIClientPaymentProvider::Exists
  • υIWalletCallback::Exists

IClientPaymentProvider::GetBitmap

Syntax

HRESULT GetBitmap(
long cFriendIdx// in
long fType// in
long *hBitMap// out
);

Description

The GetBitmap function returns a bitmap handle based upon an index of an instance. Large (120 × 79, 16–system color) and small (30 × 18, 16–system color) bitmaps are defined or supported. It is valid to return zero if a bitmap does not exist. Note that this function will not return an E_OUTOFMEMORY value because bitmaps are created during the Create call (which may return an E_OUTOFMEMORY value).

Parameters

cFriendIdx
Index into the list of payment instances for the CPC.
fType
Enumerated type indicating whether the small or large bitmap should be returned.
hBitMap
Pointer to the location where this method returns a handle to a bitmap that is used with the friendly name to represent the payment instance.

Return Value

This function returns one of the following values.

Value | Meaning
E_INVALIDARG | One or more of the arguments is invalid.
E_FAIL | Failure.
S_OK | Success.

IClientPaymentProvider::GetTypeBitmap

Syntax

HRESULT GetTypeBitmap(
BSTR bstrType// in
long fType// in
long *hBitMap// out
);

Description

The GetTypeBitmap function returns a bitmap handle based on a type. Large (120 × 79, 16–system color) and small (30 × 18, 16–system color) bitmaps are defined or supported. It is valid to return zero if a bitmap does not exist. Note that this function will not return an E_OUTOFMEMORY value because bitmaps are created during the Create call (which may return an E_OUTOFMEMORY value).

Parameters

bstrType
Name of the type associated with the bitmap.
fType
Enumerated type indicating whether the small or large bitmap should be returned.
hBitMap
Pointer to the location where this method returns a handle to a bitmap that is used with the friendly name to represent the payment instance.

Return Values

This function returns one of the following values.

Value | Meaning
E_INVALIDARG | One or more of the arguments is invalid.
E_FAIL | Failure.
S_OK | Success.

IClientPaymentProvider::Exists

Syntax

HRESULT Exists(
BSTR bstrFriendName// in
long *plExists// out
);

Description

The Exists function determines whether an instance with the same friendly name as the one being created already exists in the CPC. This function ensures the uniqueness of friendly names (regardless of case) within the CPC.

Parameters

bstrFriendName
Friendly name to compare to other names of instances to determine its uniqueness within the CPC.
plExists
Non-zero if the specified friendly name is already in use.

Return Value

This function returns one of the following values.

Value | Meaning
E_FAIL | Failure
S_OK | Success

Remarks

The IWalletCallback::Exists function determines the uniqueness of a friendly name across all CPCs.

Related Topics

  • υIClientPaymentProvider::ManagePaymentInstance
  • υIWalletCallback::Exists

IClientPaymentProvider::GetChangeCount

Syntax

HRESULT GetChangeCount(
long *plCount// out
);

Description

The GetChangeCount function allows the Payment Selector to test whether any data in the CPC has been changed. This function returns a change count that is a long integer that increments each time a data change (such as add, delete, or modify) is made. The count signifies to the Payment Selector that the contents of a CPC have been changed.

Parameters

plCount
Pointer to the location where this method returns the count of changes made to data in the CPC.

Return Value

This function returns one of the following values.

Value | Meaning
E_FAIL | Failure
E_OK | Success

IClientPaymentProvider::IsValid

Description

HRESULT IsValid(
BSTR bstrFriendname// in
BSTR bstrAcceptTypes// in
long *plResult// out
);

Description

The IsValid function determines whether the instance is valid given the accepted types string. The Payment Manager calls this function to determine whether the specified instance supports any of the payment types listed in the bstrAcceptTypes string. The IsValid function is used by the user interface to indicate whether an instance of a payment type is accepted at a merchant’s site. Instances that are not accepted at a merchant’s site appear shaded.

Parameters

bstrFriendName
Friendly name of the instance to verify as valid.
bstrAcceptTypes
List of accepted types provided by the merchant. See the “Remarks” section for a description of the payment information property that returns accepted types of credit-card payment.
plResult
Pointer to a long that is a Boolean.

Return Value

This function returns one of the following values.

Value | Meaning
E_FAIL | Failure.
E_INVALIDARG | One or more of the arguments is invalid.
S_OK | Success.

Remarks

The AcceptedTypes payment information property returns the types of credit-card payment that a merchant accepts for payment. The :clear value assigned to accepted credit card names signifies a clear text representation (no encryption).

This payment information property takes as a parameter bstrTypes, which is a string containing a list of name/value pairs. Note in the following example that the type name (Visa, MasterCard, Amex) and the encryption value (clear) are separated by colons:

"Visa:clear;MasterCard:clear;Amex:clear"

IClientPaymentProvider::IsTypeValid

Syntax

HRESULT IsTypeValid(
BSTR bstrType// in
BSTR bstrAcceptTypes// in
long *plResult// out
);

Description

The IsTypeValid function determines whether a type is valid given the accepted types string. This function is used by the user interface to indicate which payment types are accepted at a merchant’s site. Payment types that are not accepted at a merchant’s site appear shaded.

Parameters

bstrType
String identifying the payment type of the instance.
bstrAcceptTypes
List of accepted types provided by the merchant. See the “Remarks” section of IClientPaymentProvider::IsValid.
plResult
Pointer to a long that is a Boolean.

Return Value

This function returns one of the following values.

Value | Meaning
E_FAIL | Failure.
E_INVALIDARG | One or more of the arguments is invalid.
S_OK | Success.

Related Topics

  • υIClientPaymentProvider::IsValid

IClientPaymentProvider::GeneratePaymentInformation

Syntax

HRESULT GeneratePaymentInformation(
BSTR bstrFriendname// in
BSTR bstrTotal// in
BSTR bstrHashOrder// in
BSTR bstrAcceptTypes// in
SAFEARRAY (VARIANT) *ppsa// out
);

Description

The GeneratePaymentInformation function returns a payment instruction (PI) based upon the instance.

If you are using a third-party CPC, the HTML (or .asp) page needs to handle the fields that the CPC returns from the GeneratePaymentInformation call. To do this, these fields need to be added to the hidden form on your HTML page in order to get posted. You should also add the lines to initialize these form fields to their appropriate values.

Note

When this function is called, a dialog box should be displayed to the consumer warning that a specific instance of a payment type is being charged for a shopping transaction.

Parameters

bstrFriendName
Friendly name of the instance upon which the PI is based.
bstrTotal
Total amount that the user is being asked to verify. This amount should be presented to the user for confirmation of the order.
bstrHashOrder
Cryptographic hash of the contents of the order. Some protocols package this into the payment instruction. Each CPC determines what is allowed in this field.
bstrAcceptTypes
List of the accepted types provided by the merchant.
ppsa
Pointer to a two-dimensional safe array of name/value pairs whose names and values are stored as BSTRs. Name/value pairs contain the name of a field and the value assigned to that field.

Return Value

This function returns one of the following values.

Value | Meaning
E_FAIL | Failure.
E_INVALIDARG | One or more of its arguments is invalid.
E_OUTOFMEMORY | Out of memory.
S_OK | Success.

IWalletCallback Interface (Payment Manager)

The IWalletCallback interface guarantees the uniqueness of friendly names across all components in the Payment Selector. Friendly names are assigned by the user to each instance of a payment type to distinguish between multiple instances of a payment type. For example, if a user has two Visa credit cards, the first card might have the friendly name Main Visa and the second card Emergency Visa.

The IWalletCallback interface is an IDispatch interface provided for the IClientPaymentProvider::ManagePaymentInstance and the IClientPaymentProvider::NewPaymentInstance functions.

The IWalletCallback interface contains the following methods:

  • υExists
  • υGetWindowHandle

IWalletCallback::Exists

Syntax

HRESULT Exists(
BSTR bstrFriendName// in
long *plExists// out
);

Description

The Exists function must be called during add (IClientPaymentProvider::NewPaymentInstance) and modify (IClientPaymentProvider::ManagePaymentInstance) operations before an instance can be created or a friendly name modified. This function ensures that the friendly name being added or modified is unique across all components in the Payment Selector. A warning flag will be returned indicating whether the friendly name already exists. If so, this instance must not be created; the user should be prompted to enter a new friendly name.

Parameters

bstrFriendName
Friendly name of the instance that must be verified as unique across all components in the Payment Selector.
plExists
Non-zero if the specified friendly name is already in use.

Return Value

This function returns one of the following values.

Value | Meaning
S_OK | Success
E_FAIL | Failure

Remarks

Note that this interface is exposed to the CPC during the IClientPaymentProvider::Create function, which is called before all other functions. Therefore, the CPC must save the interface pointer to use during add and modify operations.

Related Topics

  • υIClientPaymentProvider::Create
  • υIClientPaymentProvider::ManagePaymentInstance
  • υIClientPaymentProvider::NewPaymentInstance

IWalletCallback::GetWindowHandle

Syntax

HRESULT GetWindowHandle(
long *hWind// out
);

Description

The GetWindowHandle function returns the window handle of the Payment Selector's window. This handle can be used in calls to Microsoft® Windows® API functions such as MessageBox.

Parameters

hWind
Handle to the window being called.

Return Value

This function returns the following value.

Value | Meaning
S_OK | Success

CPC Installation

The methods in the following interfaces support the installation of the client payment component (CPC) with the Payment Manager:

  • υIPaymentInstall (Payment manager)
  • υIPaymentProviderInstall (CPC)

IPaymentInstall Interface (Payment Manager)

Use the IPaymentInstall interface to install and uninstall CPCs and additional payment types in the Payment Manager. This top-level install interface consists of the following methods:

  • υInstall
  • υUninstall

IPaymentInstall::Install

Syntax

HRESULT Install(
long lType// in
IPaymentProviderInstall *ipInst// in
);

Description

Call the Install function to access the IPaymentProviderInstall interface that installs the CPC’s new payment type with the Payment Manager.

Parameters

lType
Payment type to install in the Payment Selector. A value of 1 indicates that it is a new CPC; a value of 2 indicates that it is a new type within an existing CPC.
ipInstall
Pointer to the IPaymentProviderInstall interface to initialize the installation process.

Return Value

This function returns one of the following values.

Value | Meaning
S_OK | Success
E_FAIL | Failure

IPaymentInstall::Uninstall

Syntax

HRESULT Uninstall(
IPaymentProviderInstall *ipInst// in
);

Description

This method is called when the IPaymentProviderInstall interface uninstalls a payment type. Note that removing a type from an existing CPC is not supported.

Parameters

ipInst
Pointer to the IPaymentProviderInstall interface to initialize the uninstallation process.

Return Value

This function returns one of the following values.

Value | Meaning
S_OK | Success
E_FAIL | Failure

IPaymentProviderInstall Interface (CPC)

The IPaymentProviderInstall interface allows you to build an installation package that installs and registers your payment type with the Payment Manager. This interface consists of the following methods:

  • υInitInstall
  • υSupportInstall
  • υComponentInfo
  • υGetFullTypeCount
  • υGetTypeInfo
  • υSetTypeActivity
  • υInstanceCount
  • υInstall
  • υUninstall
  • υSelfUninstall

IPaymentProviderInstall::InitInstall

Syntax

HRESULT InitInstall(void);

Description

The InitInstall function initializes the installation process for a CPC that will be installed. Note that this is a new CPC to be installed.

Parameters

None.

Return Value

This function returns one of the following values.

Value | Meaning
S_OK | Success
E_FAIL | Failure

IPaymentProviderInstall::SupportInstall

Syntax

HRESULT SupportInstall(void);

Description

The SupportInstall function initializes the Payment Manager to support the installation of a new CPC. The Payment Manager queries all existing CPCs to determine the status of their types before installing the new CPC.

Note that IPaymentProviderInstall::InitInstall is called for the new CPC after SupportInstall is called on all existing CPCs. This interface is used both to install new CPCs and to enable or disable payment types in existing CPCs and to support the installation of new CPCs.

Parameters

None.

Return Value

This function returns one of the following values.

Value | Meaning
S_OK | Success
E_FAIL | Failure

IPaymentProviderInstall::ComponentInfo

Syntax

HRESULT ComponentInfo(
long *plCount// out
BSTR *pbstrName// out
BSTR *pbstrSource// out
BSTR * pbstrProgID// out
);

Description

The ComponentInfo function returns information about the CPC being installed into the Payment Selector.

Parameters

plCount
Number of payment types in the CPC. Each CPC must contain at least one payment type. This count does not reflect the enable or disable status; it is the full count.
pbstrName
Name of the CPC.
pbstrSource
Name of the originator of the CPC. For example, the source of an electronic cash card would be the company that holds the electronic cash accounts.
pbstrProgId
Programmatic identification number of the CPC.

Return Value

This function returns one of the following values.

Value | Meaning
S_OK | Success
E_FAIL | Failure

IPaymentProviderInstall::GetFullTypeCount

Syntax

HRESULT GetFullTypeCount(
long *plCount// out, retval
);

Description

The GetFullTypeCount function returns the number of payment types in the CPC. This number does not depend on what payment types are enabled or disabled.

Parameters

plCount
Number of payment types in the CPC. Each CPC must contain at least one payment type.

Return Value

This function returns one of the following values.

Value | Meaning
S_OK | Success
E_FAIL | Failure

IPaymentProviderInstall::GetTypeInfo

Syntax

HRESULT GetTypeInfo(
long cIndex// in
BSTR *pbstrType// out
long *plActive// out
);

Description

Call the GetTypeInfo function to retrieve information about the status of the payment type in the Payment Selector.

Parameters

cIndex
Index of the payment type entry.
pbstrType
Name of the payment type installed by the CPC.
plActive
Pointer to the status of the payment type. The Payment Manager supports interfaces that turn payment types on or off and resolves type conflicts by forcing types to be turned on or off. A value of one (1) indicates that the payment type is turned on; zero (0) indicates that it is turned off.

Return Value

This function returns one of the following values.

Value | Meaning
S_OK | Success
E_FAIL | Failure

IPaymentProviderInstall::SetTypeActivity

Syntax

HRESULT SetTypeActivity(
BSTR bstrType// in
long lActive// in
long fPersist// in
);

Description

Call the SetTypeActivity function to set the activity status of a payment type within a CPC.

Parameters

bstrType
Payment type to set to active status.
lActive
Status of the payment type. A value of one (1) indicates that the payment type is turned on; zero (0) indicates that it is turned off. If a payment type is turned off (inactive) by the user, the payment type bitmap disappears from the Payment Selector user interface until the payment type is turned on (active) again.
fPersist
Flag that indicates whether or not the status change should be persistent.

Return Value

This function returns one of the following values.

Value | Meaning
S_OK | Success
E_FAIL | Failure

IPaymentProviderInstall::InstanceCount

Syntax

HRESULT InstanceCount(
BSTR bstrType// in
long *plCount// out
);

Description

Call the InstanceCount function to count the instances for a payment type in the CPC.

Parameters

bstrType
Payment type of the instances to count.
plCount
Pointer to the count of instances of the specified payment type.

Return Value

This function returns one of the following values.

Value | Meaning
S_OK | Success
E_FAIL | Failure

IPaymentProviderInstall::Install

Syntax

HRESULT Install(void);

Description

Call the Install function to install the CPC into the Payment Selector. This requires the CPC to save its state information.

Parameters

None.

Return Value

This function returns one of the following values.

Value | Meaning
S_OK | Success
E_FAIL | Failure

IPaymentProviderInstall::Uninstall

Syntax

HRESULT Uninstall(void);

Description

Call the Uninstall function to uninstall the CPC from the Payment Selector. This function is called from the Payment Manager when the CPC is uninstalled.

Parameters

None.

Return Value

This function returns one of the following values.

Value | Meaning
S_OK | Success
E_FAIL | Failure

IPaymentProviderInstall::SelfUninstall

Syntax

HRESULT SelfUninstall(void);

Description

The CPC calls the SelfUninstall function to remove the CPC DLL from the Payment Selector. This function is called from the CPC DLL during the unregister process.

Parameters

None.

Return Value

This function returns one of the following values.

Value | Meaning
S_OK | Success
E_FAIL | Failure


Sample Other Card Component

In addition to the client payment component (CPC), which stores and manages a third-party payment method, the Wallet SDK supports the creation of credit cards other than the three standard types (Visa, MasterCard, American Express) that are available in the Payment Selector. In addition to these standard credit card types, the Payment Selector provides the same user interface and payment selection for the management of any other custom credit card (such as a department store charge card). The sample included with the SDK is referred to as the Other Card. This section discusses how to create a custom credit card using the Other Card sample files.

Overview

Other Card instances can be created and configured as payment options in the Payment Selector using the methods of the ICreditCardOtherCard interface. Refer to the “Credit Card Component (Other Card) Interfaces” section for a detailed description of the Other Card interfaces and function syntax.

The Other Card component is a plug-in to the standard Credit Card component. As such, it uses the Credit Card component’s user interface and multiple-threading support.

The following diagram illustrates how the Other Card component functions within the Payment Selector architecture.

Note

Other Card components are Automation (IDispatch) objects.

Required Tools

As a standard ActiveX™ object, the sample Other Card DLL included with this SDK can be built using the following required tools:

  • υOther Card sample files
  • υActiveX Template Library (ATL) version 2.1 or later.
  • υMicrosoft® Visual C++® version 5.0
  • υMicrosoft® CABinet Development Kit, (located at http://www.microsoft.com/intdev/cab/tools.htm)

The Microsoft CABinet Development Kit, which you can download from http://www.microsoft.com/intdev/cab/tools.htm, provides the compression and decompression tools used to distribute your Other Card component in easy-to-install .cab files. With the CABinet Development Kit tools, you can use the sample installation files to distribute your Other Card plug-in from your Web page.

The Other Card sample files in the SDK provide the source files that you need to construct your own Other Card component. With these tools and a few modifications to the provided sample code, you can build an Other Card credit card type. Using the default Credit Card component, you can then create and store instances of your credit card type in the registry.

Creating an Other Card Component

To help you build an Other Card DLL, the following sample files are provided in the \SDK\Wallet\Samples\OtherCards\VolcanoCoffee subdirectory in the Microsoft® Wallet version 2.1 installation:

  • υOtherCard.idl
  • υOtherCard.rc
  • υOtherCard.cpp
  • υOtherCard.mak
  • υOtherCard.def
  • υMyCard.h
  • υMyCard.cpp
  • υregutil.cpp
  • υutility.cpp

You can set up an Other Card component that interfaces with the Payment Selector by using the required tools and modifying the sample source files. You can then test your component by using the Payment Selector control, which you can download and install from http://www.microsoft.com/wallet.

Multiple-Threading Issues

The Payment Selector supports single processes with multiple threads and multiple processes with one or more threads. Because the Other Card component is a plug-in to the standard Credit Card component, which is multiple thread safe, the Other Card component also supports multiple threads.

Sample Source Files

This section describes the sample files included in the SDK for implementing an Other Card component. It also details what modifications, if any, must be made to each file to customize it. Many of the following files contain the comment MOD TODO to indicate each line that requires modification. Search each file for the MOD TODO comment to customize the files for your Other Card.

Note

Comments are not allowed in the MyCard.rgs file, so that file has no MOD TODO comments, even though changes are required. See this section for more information.

OtherCard.cpp

This key source file is generated by the ATL Wizard, and handles DLLMain integration. This file requires no changes.

MyCard.h

This header file handles the declaration of the COtherCardObject class.

Modify the ProgID to reflect the name of your Other Card. In the following strings, change the VCCard string to match the name of your custom credit card:

// MOD TODO:  This is the program id of the other card being created.  Change
// the four occurrences of VCCard to <YourCardName> This    must be modified to
 // reflect the naming of your Card.
#define OtherProgID "VCCard.VCCard.1"
#define WideOtherProgID    L"VCCard.VCCard.1"

// MOD TODO: Change &CLSID_VCCard to &CLSID_<YourCardName>
// MOD TODO: Change both occurrences of &LIBID_VCCardLib to &LIBID_<YourCardName>Lib
public CComCoClass<CVCCard, &CLSID_VCCard>,
public IDispatchImpl<ICreditCardOtherCard, &IID_ICreditCardOtherCard, &LIBID_VCCardLib>,
public IDispatchImpl<IPaymentCCTypeInstall, &IID_IPaymentCCTypeInstall, &LIBID_VCCardLib>

MyCard.cpp

This source file implements the member functions of the ICreditCardOtherCard interface that is used to create and configure credit cards in the consumer’s Payment Selector. Use the provided interface functions GetBitmap, IsValid, and GetMask to manage instances of the Other Card. Explanation and examples of function syntax are provided in the “Credit Card Component (Other Card) Interfaces” section.

The file MyCard.ccp contains the comment MOD TODO to indicate each line that requires modification. Search the file for the MOD TODO comment to customize the file for your Other Card.

The sample Other Card implementation contains two credit cards: Microsoft Card and Microsoft Gold Card. In the following section, change the name of the accepted credit card type from the default MSCard or MSGCard to the short name of your Other Card. Also, change the display (friendly) names to the display names of your cards. You can also change the names of the constants, but if you do, change all occurrences in the file.

You can also indicate the maximum number of credit cards allowed for this type:.

// MOD TODO:  Change the number of cards you are installing here (cMaxCards).
// MOD TODO: Change the two card name strings, = L"VCCard"; to = L"<YourCardName>";
// MOD TODO: Change the two friendly name strings, = L"Volcano Coffee Card" to
//    = L"<Your Friendly Card Name>";
static const int cMaxCards = 2;
static const OLECHAR* szVCName = L"VCCard";
static const OLECHAR* szVCGName = L"VCGCard";
static const OLECHAR* szVCFName = L"Volcano Coffee Card";
static const OLECHAR* szVCGFName = L"Volcano Coffee Gold Card";

Next, change the credit-card number mask to reflect the configuration of numbers on your card. Change the following section:

// MOD TODO: These are the masks that are returned to the Add/Modify you can only
//        use n = numeric and a = alpa and x = alph/numeric
//
static const OLECHAR* szVCNameMask = L"nnn-aaa-nnn";
static const OLECHAR* szVCGNameMask = L"nnn-a-nnn";
static const unsigned int cVCCard = 9;
static const unsigned int cVCGCard = 7;

For example, if your card uses four groups of four digits (for example, 1111 1111 1111 1111), change the previous code to the following:

static const OLECHAR* szMask = L"nnnn-nnnn-nnnn-nnnn";
static const unsigned int cLength = 16;
Note

Make sure that the credit-card mask for your Other Card number does not exceed 20 digits (not including spaces).

Modify the following string to identify the cards being installed as a group:

// MOD TODO: The following string is used to identify the cards being installed as a group. If there is a single name then this should reflect the TYPE.
//
static const OLECHAR* wszAcceptName = L"Microsoft Cards";

You can modify the following string to reflect the name of the company or organization that creates the card:

// MOD TODO: The following string reflects the entity creating the card
//
static const OLECHAR* wszSource = L"Microsoft";

// MOD TODO:  This structure just make it easier to grab the above definitions it should reflect the cMaxCards size. Comment out any extra cards.
//
static const CardDescription gCards[cMaxCards] = {
    {szMSName,szMSFName},
    {szMSGName,szMSGFName}
};

Load the bitmaps for your card by changing the following section. In this example, each card uses two bitmaps: a large and a small representation of the card:

// MOD TODO: Load the bitmaps into memory and hold onto them
//    until the object is destroyed.
//
COtherCardObject::COtherCardObject()
{
    if (dwBitRefCnt++ == 0) {
        hSBitmap = Load256Bitmap(IDB_SMMSCRD);
        hLBitmap = Load256Bitmap(IDB_MSCARD);
        hSGBitmap = Load256Bitmap(IDB_SMMSGCRD);
        hLGBitmap = Load256Bitmap(IDB_MSGOLDCARD);
    }
}

Provide card number validation by changing the following section (the code is too long for this document, see the following header in MyCard.cpp):
// MOD TODO: Edit this routine to validate your specific card numbers.
//        Note: If you have no validation checks, just return S_OK.
//

OtherCard.def

This is the module definition file created by the ATL Wizard. Change the following line to match the name of your Other Card DLL:

;MOD TODO: Change "OtherCard.DLL" to "<YourCardName>.DLL"

LIBRARY      "OTHERCARD.DLL"

OtherCard.mak

This is the Microsoft® Visual C++® makefile for the sample Other Card project. It is recommended that you let Developer Studio™ create a makefile for you by creating a new Developer Studio project workspace (see the section “Using Visual C++”). This file requires no changes.

OtherCard.rc

This is the resource file used by your Other Card component. Change the following line to match the name of your Other Card DLL:

// MOD TODO Change this occurrence of 1 TYPELIB ""OtherCard.tlb""\r\n" to

// 1 TYPELIB ""<YourCardName>.tlb""\r\n"

//

"1 TYPELIB ""Othercard.tlb""\r\n"

You can also change the following lines to customize the version information in your Other Card DLL:

BLOCK "StringFileInfo"
    BEGIN
        BLOCK "040904b0"
        BEGIN
            VALUE "CompanyName", "Microsoft Corporation\0"
            VALUE "FileDescription", "OtherCard Module\0"
            VALUE "FileVersion", "1, 0, 0, 1\0"
            VALUE "InternalName", "OTHERCARD\0"
            VALUE "LegalCopyright", "Copyright © 1995\0"
            VALUE "OriginalFilename", "OTHERCARD.DLL\0"
            VALUE "ProductName", "Example Credit Card Extension\0"
            VALUE "ProductVersion", "1, 0, 0, 1\0"
        END

OtherCard.idl

This .idl file defines the Other Card object. It is read by the MIDL compiler, which generates the type libraries. You must create two new globally unique identifiers (GUIDs) and insert them at the following locations:

// MOD TODO: Change three occurrences of VCCard to <YourCardName>

// MOD TODO: you need to replace the following two uuid's with new
// generated uuid's. These are used to identify your object and
// typelib.
[
    uuid(130AF030-E8B9-11d0-BB16-00AA00A13794),
    version(1.0),
    helpstring("VCCard 1.0 Type Library")
]
// MOD TODO: Change VCCardLib to <YourCardName>Lib
library VCCardLib
{
    importlib("stdole32.tlb");
    [
        uuid(130AF031-E8B9-11d0-BB16-00AA00A13794),
        helpstring("VCCard Class")
    ]
    coclass VCCard
    {
        [default] interface ICreditCardOtherCard;
        interface IPaymentCCTypeInstall;
    };
};

MyCard.rgs

Because comments are not allowed in the .rgs file, you’ll find no MOD TODO comments. However, you must change the GUID specified in that file to the coclass GUID (the second GUID) that you specified in your OtherCard.idl file. Additionally, change all references to VCCard to <YourCardName>.

{
    VCCard.VCCard.1 = s 'VCCard Class'
    {
        CLSID = s '{130AF031-E8B9-11d0-BB16-00AA00A13794}'
    }
    VCCard.VCCard = s 'VCCard Class'
    {
        CurVer = s 'VCCard.VCCard.1'
    }
    NoRemove CLSID
    {
        ForceRemove {130AF031-E8B9-11d0-BB16-00AA00A13794} = s 'VCCard Class'
        {
            ProgID = s 'VCCard.VCCard.1'
            VersionIndependentProgID = s 'VCCard.VCCard'
            ForceRemove 'Programmable'
            InprocServer32 = s '%MODULE%'
            {
                val ThreadingModel = s 'Apartment'
            }
        }
    }
}

regutil.cpp

This source file implements a generic registry class that controls registration with the Payment Selector. This file requires no changes.

Using Visual C++

After modifying the files previously listed, you are ready to build your own Other Card DLL. The OtherCard.mak file is a MVisual C++ makefile that you can use to build a sample Other Card component. If you use this makefile to build your Other Card DLL, you must change all references to OtherCard to the name of the credit card you are building. It is recommended, however, that you let Developer Studio create a makefile for you by creating a new Developer Studio project workspace.

To create a makefile
  1. Copy the files in the Simple directory to the directory in which you want to build your other card.
  2. Modify the project dependencies that reference the Samples\Common directory.
    • υChange the project options preprocessor includes to reference Samples\Common.
    • υRemove and re-add the regutil.cpp and regutil.h files to the project.
    • υOptionally, change the output file specified in the Build Settings /linker flags. If you choose to do this, you must also change the name in the .def file.
  3. Change the base address in the Project Settings/link options/Output. If this is the same as another component's base address it significantly slows down the load process.

If you encounter any problems creating your own version of this sample, or if you lack experience with Visual C++ 5.0, you can create a COM object by any means with which you are familiar. This object must implement ICreditCardOtherCard and IPaymentCCTypeInstall.

Installation

After you have built your Other Card component, users of your payment-enabled Web site will have to download and register the component. To accomplish this, you can customize the files located in the \SDK\Wallet\Samples\Install directory.

These files include the CabArc.exe, OtherCard.inf, OtherCard.dll and BuildCab.bat file. You use these files to build the .cab file that will referenced by the <OBJECT> tag for your plug-in.

To enable users of your card to download the Other Card plug-in
  1. Copy the OtherCard.inf file to the directory in which you want to create the .cab file.
  2. Copy your .dll file into the directory in which you have placed the OtherCard.inf file.
  3. Edit the .inf file and BuildCab.bat and replace all references to OtherCard in these files with references to your card.
  4. Run the BuildCab.bat file to make the .cab file, and reference this .cab within the <OBJECT> tag that references your object. For an example of this tag's use, see SDK\Wallet\Samples\Install\OtherCard.htm.

Distribution for Microsoft Internet Explorer

For users of Microsoft® Internet Explorer version 3.0 and later, create a link on your Web page to the .cab file. When users load the Web page, the control and plug-in will be downloaded, installed, and registered automatically. To create a .cab file, download the CAB tools and enter the following at a command prompt:

diamond /f OtherCard.ddf

Next, modify the HTML on your Web page. For example:

<html>

<head>
<title>Standard Other Card Install</title>
</head>

<OBJECT id=paySelector classid="clsid:9DAE9125-0C35-11D0-8EEA-00A0C9054334"
        codebase="http://servername/othercard.cab#Version=1,0,0,0001"
        width=300 height=250 >
    <PARAM Name="AcceptedTypes"
        Value="visa:clear;mastercard:clear;amex:clear;othercard:clear" >
    <PARAM Name="Total" Value="134.50" >
</OBJECT>

Alternatively, create a link that allows the user to explicitly download the Other Card plug-in:

<BODY>
<h2> <align=center><a href="othercard.cab">Install Other Card DLL</a> </h2>
</body>

</html>

Distribution for Netscape Navigator

The procedure for installing the Other Card DLL is somewhat different for users of Netscape Navigator. To support these users, build a self-extracting executable file for download. The program that extracts files from .cab files, EXTRACT.EXE, will automatically extract the files in that .cab file (and any subsequent .cab files) if it has been prefixed to the first .cab file.

To build a self-extracting executable file
  1. Create a .cab file (or set of .cab files) as previously described.
  2. At a command prompt, prefix EXTRACT.EXE to the first .cab file (do not prefix EXTRACT.EXE to any other .cab files in the set).
  3. Distribute the self-extracting .cab file (and any subsequent .cab files).

For example:

C:> diamond /f othercard.ddf        ; Build CAB file set othercard.cab
C:> copy /b extract.exe+othercard.cab othercard.exe        ; othercard.exe is self-extracting

Create a link on your Web page to the self-extracting executable file for users to download. For example:

<html>

<head>
<title>Standard Other Card Install</title>
</head>

<BODY>
<h2> <align=center><a href="othrcard.exe">Install Other Card DLL</a> </h2>
</body>

</html>

Next, you must create a setup program that installs the files to their appropriate directories and registers them.

For information about .cab files and self-extracting archives, see the following Web site:

http://www.microsoft.com/workshop/default.asp

Code Signing

After you have built your Other Card, you should get a digital signature for your component to provide accountability to users downloading from your Web site. Supported in Microsoft® Internet Explorer version 3.0, Authenticode™ is Microsoft’s implementation of its code-signing proposal to the W3C. Authenticode uses documented Win32® functionality available to any Microsoft® Windows® 95–based or Microsoft® Windows NT®–based application, and works with Java applets, plug-ins, and ActiveX™ controls to provide accountability for these types of software components. Through Authenticode, end users know who published a piece of software and whether the software has been tampered with, before downloading the software to their PC.

Note that Netscape Navigator 3.0 does not support Authenticode or any code-signing technology. As such, Navigator does not recognize and alert users to unsigned plug-ins or other unsigned executable files.

For information about code signing, refer to http://www.microsoft.com/intdev/security/.

Credit Card Component (Other Card) Interfaces

The Other Card component is a plug-in to the standard Credit Card component, and allows merchants to offer credit card payment types other than VISA, MasterCard, and American Express. These OtherCards use the following interfaces to support payment instances and installation of payment instances:

  • υICreditCardOtherCard
  • υIPaymentOtherCardInstall
  • υIPaymentCCTypeInstall

As a plug-in to the default Credit Card component, the Other Card component shares the default component’s support for multiple thread safety and the Payment Selector user interface (including the Add Card Wizard). The Credit Card component calls methods on the ICreditCardOtherCard interface to add and modify instances of the payment type, and obtain bitmaps to display in the Payment Selector user interface. Use the IPaymentOtherCardInstall and IPaymentCCTypeInstall interfaces to install and integrate payment types into a consumer’s Payment Selector. The IPaymentCCTypeInstall and IPaymentOtherCardInstall interfaces define a set of methods that add an Other Card DLL to the Credit Card component. Calls to methods of the ICreditCardOtherCard interface plug the Other Card component into the Credit Card component, thereby integrating the Other Card payment type into the Payment Selector user interface.

ICreditCardOtherCard Interface

The ICreditCardOtherCard interface allows the Credit Card component to support Other Card components. This interface contains the following methods:

  • υGetBitmap
  • υGetMask
  • υIsValid

ICreditCardOtherCard::GetBitmap

Syntax

HRESULT GetBitmap(
BSTR bstrType// in
long fType// in
long *hBitMap// out
);

Description

The GetBitmap function returns a bitmap handle based upon the type of the instance. Large (120 × 79, 16–system color) and small (30 × 18, 16–system color) bitmaps are defined or supported. It is valid to return zero if a bitmap does not exist. In this case, the default bitmap for the Payment Selector is used.

Parameters

bstrType
String identifying the payment type. The name of the payment type must be unique.
fType
Value of the type long, indicating whether the small or large bitmap should be returned.
hBitMap
Address where this function returns a handle to a bitmap that is used to represent the payment type.

Return Value

This function returns one of the following values.

Value | Meaning
E_FAIL | Failure
S_OK | Success

ICreditCardOtherCard::GetMask

Syntax

HRESULT GetMask(
BSTR bstrType// in
LONG *expDate// out
BSTR *bstrMask// out
);

Description

The GetMask function returns a string containing the mask for a specified payment type. There is no default mask; therefore, if a zero (0) is returned, this is an error. A mask is required in order for a credit-card number to appear in the Add dialog box. A flag is also returned that indicates whether or not the card contains an expiration date.

Parameters

bstrType
String identifying the payment type.
expDate
Address where this function returns a flag indicating whether or not the card contains an expiration date. A value of one (1) indicates that an expiration date is supported; a value of zero (0) indicates that the card has no expiration date.
bstrMask
Address where this function returns a string for the mask associated with the payment type. The mask defines how the credit-card number is formatted in the dialog box of the client payment module. The mask may contain the following characters, separated by spaces or hyphens:
  • υa to require the entry of alphabetic characters only
  • υn to require the entry of numeric characters only
  • υx to require the entry of alphanumeric characters

Characters in the mask can be in uppercase or lowercase. The mask should not exceed 20 characters in length (excluding spaces).

If you specify constants for the mask, these are displayed in the dialog box presented to the consumer by the Payment Selector. Notice that, for purposes of transactions, these constants will not be posted as part of the consumer’s card number ; instead, only the characters entered by the consumer are posted.

Return Value

This function returns one of the following values.

Value | Meaning
E_FAIL | Failure
E_OUTOFMEMORY | Insufficient memory
S_OK | Success

ICreditCardOtherCard::IsValid

Syntax

HRESULT IsValid(
BSTR bstrType// in
BSTR bstrNumber// in
long *fValid// out
);

Description

The IsValid function determines whether the instance is valid based on the credit-card number entered by the consumer for the mask. You can include your own validation algorithm to perform further validation on the credit-card number.

Parameters

bstrType
String identifying the payment type.
bstrNumber
String identifying the credit-card number entered.
fValid
Pointer to a value of type long where this function returns a Boolean value.

Return Value

This function returns one of the following values.

Value | Meaning
E_FAIL | Failure
E_OUTOFMEMORY | Insufficient memory
S_OK | Success

Other Card Installation

An Other Card DLL can be added to the Credit Card component using the following installation interfaces:

  • υIPaymentOtherCardInstall (Credit Card CPC)
  • υIPaymentCCTypeInstall (Other Card DLL)

The Other Card DLL supports an Automation interface (IPaymentCCTypeInstall) that is called during registration. The IPaymentCCTypeInstall interface then obtains a pointer to a Credit Card component interface (IPaymentOtherCardInstall). The Credit Card CPC only installs an Other Card if it is unique. These two interfaces determine whether the Other Card to be installed has unique types before installing the Other Card’s types into the Payment Selector.

Note that the Credit Card component drives the actual installation process. The member functions of the IPaymentCCTypeInstall interface are support functions called by the Credit Card component to query the information necessary to install the Other Card DLL. The Credit Card CPC interacts with the Payment Manager during the install process.

The Credit Card DLL manages the installation process through the IPaymentCCTypeInstall interface of the Other Card DLL. During DLL registration, the Other Card writes a value into the registry informing the Credit Card CPC that it needs to be installed. The registry value is HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Shopper\Install CreditCard\“ProgID.” The first time the Credit Card CPC runs, it will then install the Other Card.

Note that the Other Card installation process enforces type uniqueness across all CPCs by turning on and off types that conflict with other types. The Payment Manager determines the status of on or off for each type. For example, a new type may be turned off if the type conflicts with a type in another CPC installed in the Payment Manager.

IPaymentOtherCardInstall (Credit Card CPC)

Implemented by the Credit Card component, the IPaymentOtherCardInstall interface is obtained when an existing Other Card DLL is uninstalled, usually during unregistration of the DLL. This removes the Other Card DLL and all data associated with it.

This interface contains the following method:

  • υUninstallType

IPaymentOtherCardInstall::UninstallType

Syntax

HRESULT UninstallType(
BSTR bstrProgID// in
);

Description

The UninstallType function uninstalls the Other Card DLL of the deleted payment type.

Parameters

bstrProgID
BSTR containing the programmatic identifier (ProgID) of the Other Card DLL to be deleted.

IPaymentCCTypeInstall (Other Card DLL)

The Other Card DLL file implements the CPC installation interface IPaymentCCTypeInstall to install the Other Card’s unique type. This interface contains the following methods:

  • υGetInstallInfo
  • υGetTypeInfo
  • υSelfUninstall
  • υUninstall

IPaymentCCTypeInstall::GetInstallInfo

Syntax

HRESULT GetInstallInfo(
long *plCount// out
BSTR *pbstrName// out
BSTR *pbstrSource// out
);

Description

The Credit Card component calls the GetInstallInfo function to obtain general information about the Other Card DLL being installed.

Parameters

plCount
Pointer to a value of type long where this function returns the count of types supported by the Other Card DLL.
pbstrName
Pointer to a BSTR value that indicates the name of the DLL to be installed.
pbstrSource
Pointer to a BSTR value that indicates the source (manufacturer) of the DLL being installed.

Return Values

This function returns one of the following values.

Value | Meaning
E_FAIL | Failure
E_OUTOFMEMORY | Insufficient memory
S_OK | Success

IPaymentCCTypeInstall::GetTypeInfo

Syntax

HRESULT GetInstallInfo(
long cIndex// in
BSTR *pbstrType// out
BSTR *pbstrFriendName// out
);

Description

The GetTypeInfo function obtains information about a unique type supported by the Other Card DLL. The Credit Card component uses this information (which is accessed as a zero-based array) to track the types stored in the Other Card DLL.

Parameters

cIndex
Index value that identifies the type of information sought by the Credit Card component.
pbstrType
Pointer to a BSTR where this function returns the type corresponding to the index value. This type must be unique within the Credit Card component. Types that already exist in the Credit Card component will not be reinstalled.
pbstrFriendName
Pointer to a BSTR where this function returns the friendly name of the type.

Return Values

This function returns one of the following values.

Value | Meaning
E_FAIL | Failure
E_OUTOFMEMORY | Insufficient memory
S_OK | Success

IPaymentCCTypeInstall::SelfUninstall

Syntax

HRESULT SelfUninstall(void);

Description

The SelfUninstall function is called from the Other Card DLL to delete itself from the Microsoft® Wallet.

Parameters

None.

Return Values

This function returns one of the following values.

Value | Meaning
E_FAIL | Failure
E_OUTOFMEMORY | Insufficient memory
S_OK | Success

IPaymentCCTypeInstall::Uninstall

Syntax

HRESULT Uninstall(void);

Description

The Credit Card component calls the Uninstall function to uninstall the Other Card DLL. The Other Card DLL should unregister itself so that it will not be recognized by the system.

Parameters

None.

Return Values

This function returns one of the following values.

Value | Meaning
E_FAIL | Failure
E_OUTOFMEMORY | Insufficient memory
S_OK | Success


Payment Builder Interface

The Credit Card client payment component (CPC) supports a Payment Builder plug-in component that implements the following interfaces:

  • ICreditCardEncryption2
  • ICreditCardEncryption2_CallBack

The Payment Builder interfaces allow third-party encryption and payment instruction (PI) building methods to plug into the CPC in the Microsoft® Wallet.

Encryption Protocols

The Microsoft® Wallet implements the clear text protocol, which is built into the Credit Card client payment component (CPC) and supports the type CCPMNT and all of the additional fields that contain the credit-card and billing information.

All other protocols are installed into the Credit Card CPC by registry entries in the /Credit Card/Protocol/Install registry key. When a protocol is installed, it writes its program identifier (ProgID) of the Component Object Model (COM) object that implements ICreditCardEncryption2 to this key.

When a user attempts some action that affects a given protocol, the Wallet retrieves the protocol’s ProgID from the Registry and uses it to create an instance of the affected protocol’s ICreditCardEncryption2 implementation. The Wallet then calls the appropriate interface method. Thus, for example, when a user attempts to delete a Credit Card through the Payment control interface, the Wallet calls the affected protocol’s implementation of ICreditCardEncryption2::PreDelete.

For a given payment protocol, some of the payment information stored in the Wallet (such as a credit-card number), must remain constant for the protocol to work. For example, with SET, the certificate must be valid, and that certificate is dependent on the card number and the expiration date. As such, if the shopper is able to change this information, it will invalidate the certificate for use in subsequent purchases. Using the ICreditCardEncryption2 interface, the Payment Builder is notified when the shopper is changing information about the credit card, prior to the change, and should display a warning as to the results of choosing to proceed. The Payment Builder also needs an opportunity to tell the shopper that this is happening.

The ICreditCardEncryption2_CallBack interface implements callback methods that return pointers to credit card and billing information, replacing the GetCreditCard and GetAddress function pointers in the old ICreditCardEncryption::GenPayInstruction method. Additionally, ICreditCardEncryption2_CallBack defines two methods, GetExtensionProperty and SetExtensionProperty, that the protocol can use to set or query the custom property values for the affected Credit Card.

Note

The ICreditCardEncryption interface is no longer supported. You need to port existing code to use the ICreditCardEncryption2 interface.

Selection of Encryption Protocols

The Credit Card CPC selects an encryption protocol based upon the accepted types string. The string is evaluated from left to right, comparing the payment method and protocol until a match is found.

For example, if the string “Visa:SET;Visa:Clear;MasterCard:Clear;AMEX:SET” is the accepted types string, when the user selects a Visa card, SET will be used because it is the match that is located the farthest to the left. If a MasterCard is selected, Clear will be used because it is the only protocol defined for MasterCard. If AMEX is selected, SET will be used. Matches are done left to right and the first match found is used. A merchant can move the strongest encryption protocols or preferred protocols to the left side of less preferred protocols. If the first matching protocol fails, the next matching protocol is used.

ICreditCardEncryption2 Interface

The ICreditCardEncryption2 interface allows the payment instruction (PI) to be use security protocols that the client can install in the Microsoft® Wallet. This interface consists of the following functions:

  • CreateProtocol
  • GetType
  • Add
  • PreModify
  • Modify
  • PreDelete
  • Delete
  • GenPayInstruction

The encryption protocol used to create the payment instruction is selected based upon the AcceptedTypes payment property specified by the merchant. The AcceptedTypes payment property defines which payment types a merchant accepts in an electronic transaction. A protocol is responsible for the creation of the PI. The PI is posted back to the server as if the information were entered in an HTML form. The PI may contain one or more fields. The information is returned as a two-dimensional SAFEARRAY of name/value pairs. All PIs should contain a “TYPE” field along with all additional fields.

ICreditCardEncryption2::CreateProtocol

Syntax

HRESULT CreateProtocol(
ICreditCardEncryption2_Callback *pCallBack// in
);

Description

The Wallet calls the CreateProtocol method to pass an instance of the ICreditCardEncryption2_Callback interface to the Payment Builder's implementation of ICreditCardEncryption2.

The ICreditCardEncrypt2_Callback interface implements methods that support setting and retrieving information about the Credit Card, including its current property values. Typically, the Payment Builder's ICreditCardEncryption2 stores the ICreditCardEncryption2_Callback interface pointer, so that the callback interface's methods can be called by ICreditCardEncryption2 interface methods.

This is the first method called when a protocol is instantiated.

Parameters

pCallBack
A valid ICreditCardEncryption2_Callback interface pointer. This interface pointer is initialized by the Wallet.

ICreditCardEncryption2::GetType

Syntax

HRESULT GetType(
BSTR*pbstrType// out
);

Description

The Wallet calls the GetType method upon loading the protocol to retrieve the encryption protocol type. This type appears on the left hand side of each payment method accepted by the merchant. The Credit Card component implements the type “clear”. If the AcceptedTypes property value string is “Visa:Clear”, Visa is the payment type and Clear the protocol type.

Parameters

pbstrType
Pointer to a BSTR where this function returns the type to the Credit Card component.

ICreditCardEncryption2::Add

Syntax

STDMETHOD Add(
HWND hWnd// in
CREDITCARDINFO *pCCInfo// in
BYTE ** ppBlob// in, out
long *cLen// in, out
);

Description

The Wallet calls the Add method when a new payment instance is being added. The Wallet's call to this method allows the plug-in protocol to query information from the user, which is then stored for later use by the Credit Card CPC.

Parameters

hWnd
Window handle to the parent window.
pCCInfo
Pointer to the credit-card information.
ppBlob
Address where this function returns a pointer to a blob that will be stored by the Credit Card CPC and given to the protocol when a payment instruction is generated. The ppBlob value should be NULL if the protocol does not need to store any information. If the protocol does store a value, it must be returned in dynamically allocated memory, using CoTaskMemAlloc, and this memory will be freed by the Credit Card CPC.
cLen
The address to which this method returns the length of the blob.

ICreditCardEncryption2::PreModify

Syntax

STDMETHOD PreModify(
long hWnd// in
CREDITCARDINFO *pOldCCInfo// in
CREDITCARDINFO *pNewCCInfo// in
BYTE ** ppBlob// out
long *cLen// out
BSTR*pbstrErrMsg// out
);

Description

The Wallet calls the Payment Builder's implementation of PreModify to notify the payment builder that a payment instance is being changed. This notification provides the payment builder an opportunity to warn the user in the event that the modification will affect the use of the protocol. The Payment builder provides this notification by returning S_FALSE, and by storing the text of the warning in pbstrErrMsg. The Wallet then displays this message to the user.

If the user chooses to cancel the modification, the Modify method is not called.

Parameters

hWnd
Window handle to the parent window.
pOldCCInfo
Pointer to the credit-card information.
pNewCCInfo
Pointer to the changed credit-card information.
ppBlob
Address where this function returns a pointer to a blob that will be stored by the Credit Card component and given to the protocol when a payment instruction is generated. The ppBlob value should be NULL if the protocol does not need any information to be stored. **ppBlob is the blob originally stored when the card was added or last modified. If the blob is changed, the protocol must call CoTaskMemFree to free the original blob and call CoTaskMemAlloc to dynamically allocate a new blob. This memory will be freed by the Credit Card CPC.
cLen
Length of the blob.
pbstrErrMsg
The address to which the PreModify method returns a warning that the Wallet displays to the user.

Return Value

The CPC displays the message contained in pbstrErrMsg to the user only if PreModify returns S_FALSE.

ICreditCardEncryption2::Modify

Syntax

STDMETHOD Modify(
HWND hWnd// in
CREDITCARDINFO *pOldCCInfo// in
CREDITCARDINFO *pNewCCInfo// in
BYTE ** ppBlob// out
long *cLen// out
);

Description

The Wallet calls the Payment Builder's implementation of the Modify method to modify the payment instance.

Parameters

hWnd
Window handle to the parent window.
pOldCCInfo
Pointer to the original credit-card information.
pNewCCInfo
Pointer to the changed credit-card information.
ppBlob
Address where this function returns a pointer to a blob that will be stored by the Credit Card component and given to the protocol when a payment instruction is generated. The ppBlob value should be NULL if the protocol does not need any information to be stored. **ppBlob is the blob originally stored when the card was added or last modified. If the blob is changed, the protocol must call CoTaskMemFree to free the original blob and call CoTaskMemAlloc to dynamically allocate a new blob. This memory will be freed by the Credit Card CPC.
cLen
Length of the blob.

ICreditCardEncryption2::PreDelete

Syntax

STDMETHOD PreDelete(
HWND hWnd// in
CREDITCARDINFO *pOldCCInfo// in
BYTE ** ppBlob// out
long *cLen// in, out
BSTR *pbstrErrMsg// out
);

Description

The PreDelete method is called when a payment instance is to be deleted. The Wallet calls this method to give the Payment Builder a chance to warn the user in the event that the deletion will affect the user of the protocol. The Payment Builder provides this warning by returning S_FALSE, and by storing the text of the warning in the pbstrErrMsg out parameter.

If the shopper opts not to continue the deletion, the Delete method is not called.

Parameters

hWnd
Window handle to the parent window.
pOldCCInfo
Pointer to the original credit-card information.
ppBlob
Address where this function returns a pointer to a blob that will be stored by the Credit Card component and given to the protocol when a payment instruction is generated. The ppBlob value should be Null if the protocol does not need any information to be stored. **ppBlob is the blob originally stored when the card was added or last modified. If the blob is changed, the protocol must free the original blob and dynamically allocate a new blob. This memory will be freed by the Credit Card CPC.
cLen
Length of the blob.
pbstrErrMsg
The address to which the method returns a status message that the Wallet displays to the user.

Return Value

The CPC displays the message contained in bstrErrMsg to the user only if PreDelete returns S_FALSE.

ICreditCardEncryption2::Delete

Syntax

STDMETHOD Delete(
HWND hWnd// in
CREDITCARDINFO *pCCInfo// in
BYTE ** ppBlob// out
long *cLen// in, out
);

Description

If the user confirms the deletion of a credit card, the Wallet calls the Delete method to delete the payment instance.

Parameters

hWnd
Window handle to the parent window.
pCCInfo
Pointer to the credit-card information to delete.
ppBlob
Address where this function returns a pointer to a blob that will be stored by the Credit Card component and given to the protocol when a payment instruction is generated. The ppBlob value should be Null if the protocol does not need any information to be stored. **ppBlob is the blob originally stored when the card was added or last modified. If the blob is changed, the protocol must call CoTaskMemFree to free the original blob and dynamically allocate a new blob by calling CoTaskMemAlloc. The Credit Card CPC will later call CoTaskMemFree to free the memory allocated by this call.
cLen
Length of the blob.

ICreditCardEncryption2::GenPayInstruction

Syntax

STDMETHOD GenPayInstruction(
HWND hWnd// in
BYTE *pvarBlob// in
long cLen// in
BSTR bstrFriendlyName// in
BSTR bstrTotal// in
BSTR bstrHashOrder// in
ICreditCardEncryption2_CallBack *
pCallBack// in
VARIANT *pvarNameValueArray// in
);

Description

The GenPayInstruction method generates a payment instruction (PI) and returns the PI as a set of name/value pairs.

Parameters

hWnd
Window handle to the parent window.
pvarBlob
Blob that was stored when the card was added.
cLen
Length of the blob.
bstrFriendlyName
BSTR value containing the friendly name of the credit card selected.
bstrTotal
BSTR value containing the amount of the purchase, received from the merchant.
bstrHashOrder
BSTR value containing the order hash information received from the merchant.
pCallBack
Pointer to the ICreditCardEncryption2_CallBack interface implemented by the Credit Card CPC. This interface contains methods that return the credit card and billing information as a structure to the encryption protocol.
pvarNameValueArray
Name/value VARIANT built by the encryption protocol and returned to the merchant. The encryption protocol produces this VARIANT.

ICreditCardEncryption2_Callback Interface

The ICreditCardEncryption2_Callback Interface supports methods that return the credit card and billing address information in a CREDITCARDINFO structure, and allows the Payment Builder to set and retrieve custom properties. An interface pointer on ICreditCardEncryption2_Callback is passed to the Payment Builder's implementation of ICreditCardEncryption when the Wallet calls ICreditCardEncryption::CreateProtocol.

The ICreditCardEncryption2_Callback interface supports the following methods:

  • GetCreditCard
  • GetBillAddress
  • GetExtensionProperty
  • SetExtensionProperty

The ICreditCardEncryption2::GenPayInstruction method requires a pointer to this interface.

CREDITCARDINFO Structure

The CREDITCARDINFO structure is defined as follows:

typedef struct
{
    FRIENDLYNAME    szFriendlyName;         // friendly name of the card
    DWORD           dwFlags;
    CARDNUMBER      szCreditCardNumber;
    EXPDATE         szCreditExpiration;
    DWORD           dwCreditCardType;       // the credit card type
    CREDITCARDNAME  szCreditCardName;       // the name of the card
    CUSTOMERNAME    szCustomerName;         // customer name, may be distinct from billing address name
    ADDRFRIENDNAME  szAddrFriendName;       // Friendly name of the address
} CREDITCARDINFO, *PCREDITCARDINFO;

ICreditCardEncryption2_Callback::GetCreditCard

Syntax

HRESULT GetCreditCard(
BSTR bstrFriendname, // in
BSTR bstrTotal// in
CREDITCARDINFO *pCreditCard// out
);

Description

The GetCreditCard method returns a pointer to the credit-card information in a CREDITCARDINFO structure. The user is always asked for a password before the credit card is returned. A Payment Builder must handle a failure on this routine by returning the result back to the Credit Card component.

Parameters

bstrFriendname
The display name for the credit card.
bstrTotal
String representing the total, passed to the encryption protocol.
pCreditCard
Pointer to the CREDITCARDINFO structure that will have the value returned if the user successfully enters the password.

ICreditCardEncryption2_Callback::GetBillAddress

Syntax

STDMETHOD GetBillAddress(
BSTR bstrAddrFriendName, // in
BSTR bstrPrefix// in
VARIANT *psa// out
);

Description

The GetBillAddress function returns a pointer to the billing address that is associated with a credit card. The credit-card information must be retrieved before this method is called, because this method requires the friendly name of the Billing Address entry.

Parameters

bstrPrefix
Prefix that will be added to all of the billing address friendly names. It may be Null.
lCount
ppsa
Pointer to a SAFEARRAY returned from the Address Selector. This array contains the address information.

ICreditCardEncryption2_Callback::GetExtensionProperty

Syntax

HRESULT GetExtensionProperty(
BSTR bstrPropertyNamej// in
BSTR *pbstrPropertyValue// out
);

Description

The GetExtensionProperty function is a callback function that retrieves the value of a specified property from the script.

If the payment builder needs extra information to generate its payment instruction (the merchant name or identifier, for example), these properties can be set from JavaScript using the IPaySlideSelector's SetExtension property. The payment builder can then use ICreditCardEncryption2_Callback's GetExtensionProperty to retrieve this value.

Parameters

bstrPropertyName
Contains the name of the property for which the value should be retrieved.
pbstrPropertyValue
The address of a BSTR variable in which to store the retrieved value.

ICreditCardEncryption2_Callback::SetExtensionProperty

Syntax

HRESULT SetExtensionProperty(
BSTR bstrPropertyNamej// in
BSTR pbstrPropertyValue// out
);

The SetExtensionProperty function sets the value of the specified property. This property value can then be retrieved in JavaScript by means of the IPaySlidSelector's GetExtensionProperty method.

Parameters

bstrPropertyName
Contains the name of the property for which the value should be retrieved.
pbstrPropertyValue
The address of a BSTR variable in which to store the retrieved value.


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.


Legal Information

This document is provided for informational purposes only and Microsoft Corporation makes no warranties, either express or implied, in this document. The entire risk of the use or the results of the use of this document remains with the user. The names of companies, products, people, characters, and/or data mentioned herein are fictitious and are in no way intended to represent any real individual, company, product, or event, unless otherwise noted. Complying with all applicable copyright laws is the responsibility of the user. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, without the express written permission of Microsoft Corporation. If, however, your only means of access is electronic, permission to print one copy is hereby granted.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.

ActiveX, BackOffice, DirectX, JScript, Microsoft, Microsoft Press, MS, MS-DOS, Visual Basic, Visual C++, Windows, Win32, Win32s, and Windows NT are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. OS/2 is a registered trademark licensed to Microsoft Corporation.

Java is a trademark of Sun Microsystems, Inc.

Silicon Graphics is a registered trademark and OpenGL is a trademark of Silicon Graphics, Inc.

Other product and company names mentioned herein may be the trademarks of their respective owners.


(Untitled)

Microsoft Site Server 3.0 SDK

Microsoft® Site Server is a comprehensive Web site environment that works with Microsoft® Windows NT® Server and Microsoft® Internet Information Server (IIS) version 4.0. It enables you to build cost-effective Web solutions for the advanced management and targeted delivery of information. This SDK describes the COM/Automation objects provided by the Site Server system.

You can also access this SDK on the Web, part of the Microsoft Platform SDK, to get late breaking information and updates.

To get an understanding of the essential architectures, concepts, and terms, developers should first read about the components they want to work with in the main Site Server documentation. This SDK assumes a familiarity with VBScript, or JScript, and Microsoft Windows® Scripting Host. The primary language used for syntax and examples is VBScript.

The components of this SDK are as follows:

Component | Description
Content Deployment | Program content replication involving content deployment, Internet retrieval, and component deployment.
Push | Program the Microsoft Active Channel Server to automate the process of information delivery using channels.
Personalization and Membership | Program the management of customer relationships, memberships, and personalized information.
Search | Program the building of search catalogs used for searches on your Web site.
Ad Server | Commerce Edition Only—Program the delivery of advertisements to dynamically built web pages.
Commerce and Wallet | Commerce Edition Only—Program custom order processing components, and client payment components for the Microsoft® Wallet control.

Next in Contents


(Untitled)

Interface Type Information

Type libraries contain data type information about interfaces. You can get type information about interfaces by accessing a type library using the VB Object Browser or the VC++ OLE/COM Object Viewer.

Site Server Search Administration 1.0 Type Library

This type library contains information about the Search administrative interfaces and is available as a resource in NLAdmin.dll.

Site Server Indexer Type Library

This type library contains information about the Search schema interfaces and is available as a resource in nlindex.dll.

Site Server Gatherer Type Library

This type library contains information about the Search Gatherer interfaces and is available as a resource in gather.dll.

Site Server Gathering Service Type Library

This type library contains information about the Search Gatherer service interfaces and is available as a resource in gthrsvc.exe.

Type Library Interface Listing

The following table lists each Search interface and indicates in which type library the interface information can be found.

Interface | Site Server Search Administration 1.0 Type Library | Site Server Indexer Type Library | Site Server Gatherer Type Library | Site Server Gathering Service Type Library
IBuildCatalog |  |  |  |
IBuildCatalogs |  |  |  |
IBuildServer |  |  |  |
ICatalogProperties |  |  |  |
ICatalogSearchServerList |  |  |  |
IColumn |  |  |  |
IColumns |  |  |  |
IExtension |  |  |  |
IExtensions |  |  |  |
IGatherLog |  |  |  |
IGatherLogs |  |  |  |
IGatherNotify |  |  |  |
IIndexDs |  |  |  |
IMapping |  |  |  |
IMappings |  |  |  |
IProtocol |  |  |  |
IProtocols |  |  |  |
ISearchAdmin |  |  |  |
ISearchCatalog |  |  |  |
ISearchCatalogs |  |  |  |
ISearchSchema |  |  |  |
ISearchServer |  |  |  |
IServer |  |  |  |
IServers |  |  |  |
ISitePath |  |  |  |
ISitePaths |  |  |  |
ISiteRestriction |  |  |  |
ISiteRestrictions |  |  |  |
IStartPage |  |  |  |
IStartPages |  |  |  |
IStoplist |  |  |  |
IStoplists |  |  |  |