The release of the .NET Framework delivers numerous incredibly functional classes that make life easier for developers. The System.DirectoryServices namespace provides access to the Active Directory. The classes in this namespace can be used with any of the Active Directory service providers including Internet Information Services (IIS), the Lightweight Directory Access Protocol (LDAP), the Novell Directory Services in NetWare (NDS), and WinNT.
These classes make it possible to do the following Web-site administration tasks programmatically:
Verifying that a virtual directory exists
Creating and deleting virtual directories
Setting and updating any of the properties on IIS
Invoking any of the IIS-specific methods
This article will address a a standard set of activities that any Web administrator may want to automate or handle programmatically. We will attach to the default Web site, create a virtual directory, set a series of properties on the directory, and provide the option of subsequently deleting the directory.
Required
In order to run these examples, you will need to have installed the following:
.NET Framework SDK Beta 2 or higher
IIS 5.1 or higher
Administrative access to the Web server
Verifying a Virtual Directory Exists
First create a new file named ADSI.aspx using Notepad. Next you will need to import the System.Directory Services Namespace so that you can access the Active Directory Services Interfaces.
<%@ Page Language="vb" %>
<%@ Import Namespace="System"%>
<%@ Import Namespace = "System.DirectoryServices"%>
<HTML>
<HEAD>
<SCRIPT language="vb" RUNAT="server">
Sub Page_Load(Sender as Object, E as EventArgs)
End Sub
Now let's build the functions that will do all of the heavy lifting. We will start by doing a simple check to determine if a Virtual Directory with the desired name specified by the user exists. So we create a function called VirDirExists, which will except a Virtual Directory Name and return True if it already exists and False otherwise.
Function VirDirExists(ByVal IISPath As String) As Boolean
Try
Dim oDE As System.DirectoryServices.DirectoryEntry
Return oDE.Exists(IISPath)
Catch
label1.text = label1.text & "VirDirExists Failure: " & err.Description
End Try
End Function
We will need to use this function regularly throughout the following examples to avoid raising errors as we go through the process of creating, deleting, and modifying virtual directories.
The core of this simple function is creating an instance of the DirectoryEntry object. This object can be used to manipulate any Active Directory Entry stored in an IIS, LDAP, NDS, or NT Metabase. The DirectoryEntry has a method, Exists, which allows you to determine if an entry exists prior to binding to it.
In order to understand the syntax for binding to IIS objects, you need to understand the components of the paths to the IIS Metabase. The metabase is organized in a hierarchical structure that mirrors the structure of your IIS installation. Each node in the metabase structure is called a key, and each key can contain one or more IIS configuration values, called metabase properties. The IIS Metabase keys correspond to the elements of IIS, and each key contains properties that affect the configuration of its associated element.
Let's look at the following IIS Metabase path and break it down into its key components:
Lets the DirectoryEntry Object know that we are dealing with an IIS directory rather than an LDAP or NDS entry.
ComputerName
Simply reflects the Web server we will be accessing. This can be a name or IP address.
WebService
Can be W3SVC which indicates that we are dealing with the Web service or MSFTPSVC which would indicate we wanted to use the FTP service.
Server
Is typically an integer value that allows us to attach to different Web servers on the same server, each with its own unique IP:Port Address combination. Typically the default Web server has a value of 1.
VirtualDirectoryName
Is the name of our virtual directory.
Creating Virtual Directories
To create a new virtual directory, add a new subroutine to our ADSI.aspx page and start it as follows:
Function CreateVirDir(ByVal sHost As String, ByVal sServer as String, ByVal sPhysicalPath As String, ByVal sVirDirName as String) as Boolean
Try
Dim oDE As System.DirectoryServices.DirectoryEntry
Dim oDC As System.DirectoryServices.DirectoryEntries
Dim oVirDir As DirectoryServices.DirectoryEntry
Dim sIISPath As String
sIISPath = "IIS:\\"& sHost & "\W3SVC\" & sServer.ToString() & "\Root"
This dimensions the DirectoryEntry's and DirectoryEntries objects we will need, as well as dynamically builds the IISPath to the root of the target computer/server. We then check to make sure that this root directory exists, using the VirDirExists Function. Assuming it exists, we bind our DirectoryEntry object, oDE, to this root using:
If VirDirExists(sIISPath) Then
oDE = New DirectoryServices.DirectoryEntry(sIISPath)
We obtain a collection of all of the children virtual directories under this root object using:
oDC = oDE.Children
Add a new member to this collection and bind it to a new DirectoryEntry object, oVirDir, thus creating a new virtual directory with:
And do the last clean-up steps to finish off the error handling.
End If
Return True
Catch
Return False
End Try
End Function
Using the example above, any valid property that is updateable at runtime can be set, so we could update any of the following virtual directory properties as shown in the examples below:
Virtual Directory Setting You Wish To Set
Example Code
Read Access
.Properties("AccessRead")(0) = True
Write Access
.Properties("AccessWrite")(0) = True
Execute Access
.Properties("AccessExecute")(0) = True
Anonymous Access
.Properties("AuthAnonymous")(0) = False
Basic Authentication
.Properties("AuthBasic")(0) = False
NTLM Authentication
.Properties("AuthNTLM")(0) = True
Indexing of Content
.Properties("ContentIndexed")(0) = False
Enabling Directory Browsing
.Properties("EnableDirBrowsing")(0) = True
This is only a partial listing of the most frequently used. A full listing of property settings you can set using this approach are available at:
In the code example supporting this article, we use a subroutine, SetVirDirSettings, that illustrates in detail how to set these properties.
Invoking Any of the IIS-Specific Methods
To handle the deletion of virtual directories we have to learn how to invoke a method of these IISObjects using the Active Directory Server Interfaces (ADSI). The ADSI Container Object we have been working with above is the IIsWebVirtualDir. The ADSI DirectoryEntry generic representation of the underlying IIS Server does not make full availability of all underlying functionality. This is especially true of the methods available for the underlying objects. We can, however, gain access to these methods by using the Invoke method of the DirectEntry object. To use the Invoke method you must understand the underlying functions, and the order and types of parameters which need to be passed. In the following example we will illustrate how to invoke the Delete method and pass the parameters required to delete a virtual directory.
We start off by creating a new sub DeleteVirDir that accepts the root path to the Web server and the virtual directory name to delete.
Sub DeleteVirDir(ByVal sIISPath as String, ByVal sVirDirName as String)
Try
We establish the variables we will need, including a ParamArray with 2 items, which will hold the ADSI object to delete, IIsWebVirtualDir and the name of the virtual directory to delete.
Dim oParams as object() = {"IISWebVirtualDir", sVirDirName.ToString()}
Dim oDE As System.DirectoryServices.DirectoryEntry
Next we validate the existence of the root path, then bind the oDE DirectoryEntry object to the IIS Metabase root path, and we can invoke the underlying delete method and pass the required parameters as follows.
If VirDirExists(sIISPath) Then
oDE = New DirectoryServices.DirectoryEntry(sIISPath)
oDE.Invoke("Delete", oParams)
End If
Finally, we simply do cleanup.
label1.text = label1.text & "Delete of Virtual Directory Succeeded"
Catch e as exception
label1.text = label1.text & "Delete of Virtual Directory Failed: " & e.message
End Try
End Sub
The full file can be downloaded here: adsi.aspx (must choose view source if using IE).
About the Author
Mr. Caudill is a principal consultant at PricewaterhouseCoopers LLP. Tony has written and deployed custom Microsoft solutions for Fortune 500 companies to support the integration of SAP, Siebel, and other Enterprise Resource Planning (ERP) and Customer Relationship Management (CRM) applications. When not managing system-implementation projects, he avidly pursues surfing in southern California at his favorite beaches and tackles skiing at Big Bear. He can be reached at Tony_Caudill@hotmail.com.
In this article, Robert Chartier shows how to use the System.DirectoryServices Class for some simple User and Group administration tasks with impersonation. [Read This Article][Top]
In this article, Remie Bolte further demonstrates the power of ADSI with code that renames users, changes user properties, changes user boundaries, and creates, populates, and removes user groups. [Read This Article][Top]
Remie Bolte uses his popular Adding Users to W2K code sample as a basis for introducing and exploring Microsoft's Active Directory Services Interface. [Read This Article][Top]
ADSI Part II describes and demonstrations the power of ADSI by showing how to manipulate the NTLM database. Examples in this article show how to add a user to a domain, delete the user, add a group, and add the user to the group. There is also a discussion on security and an overview of the Group, User and Domain ADSI objects. [Read This Article][Top]
Have you wanted to add virtual roots through VBScript? Create ISAPI server extensions that install themselves in IIS 4.0? Or script the installation of your entire web site including user permissions? You can do this and more with ADSI. [Read This Article][Top]
Mailing List
Want to receive email when the next article is published? Just Click Here to sign up.