asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search








Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Web site Administration with ADSI and the .NET DirectoryServices Namespace
By Tony Caudill
Rating: 3.9 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Introduction

    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:

    IIS://ComputerName/WebService/Server/Root/VirtualDirectoryName

    IIS:// 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:
    
    		oVirDir = odc.Add(sVirDirName, oDE.SchemaClassName.ToString())
    
    
    Commit the changes to the IIS Metabase.
    
    oVirDir.CommitChanges()
    
    

    Setting and Updating Any of the Properties on IIS

    We additionally need to assign a physical path to this new virtual directory, using a straightforward property-setting approach:

    
    			oVirDir.Properties("Path")(0)= sPhysicalPath
    			oVirDir.CommitChanges()
    
    
    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:

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/iisref/html/psdk/asp/aore8v5e.asp

    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.

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Other Articles
    Jul 30, 2002 - Accessing Active Directory Through the .NET Framework
    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]
    Jan 30, 2002 - Add to Your ADSI Code Library
    Remie Bolte has put together a collection of ADSI scripts for some of the more common Windows administration tasks.
    [Read This Article]  [Top]
    Nov 27, 2001 - Learning ADSI - Part 2: Editing Users and Administering Groups
    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]
    Oct 5, 2001 - Learning ADSI - Part 1: Adding Users To W2K
    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]
    Mar 16, 1998 - ADSI Part II: Configuring NTLM with ADSI
    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]
    Mar 4, 1998 - Programming IIS 4.0 with ADSI
    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.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
    Microsoft Article: 7.0, Microsoft's Lucky Version?
    Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Windows Server 2008
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES