Search
Wednesday, August 20, 2008 ..:: Articles ::.. Register  Login
  
Web site administration using .NET DirectoryServices Namespace
by Sai Panyam Last Updated:18 Oct 2004 View Count:242 Rating:( 7.00/ 9 ) from 1 Vote(s)
Summary

The System.DirectoryServices namespace provides users with the ability to do some basic web site administration tasks programatically. The classes in this namespace can be used with the Active Directory(AD) service providers. These classes can accomplish common web site administration tasks like creating, verifying, deleting and setting properties of virtual directories on IIS programatically. This article briefly describes what the different AD service providers are, how to access AD through .NET and finally the code to create and delete virtual directories on IIS.We will go through how to connect to the default Web site, create a virtual directory, set a series of properties on the directory, and subsequently delete the directory.

Artifacts can be downloaded from here.
InetManager.zip (35.4 kb)
Accessing Active Directory Service Providers

Some of the Active Directory(AD) Service Providers that we can access using DirectoryServices namespace are

  • Internet Information Services (IIS)
  • Windows NT version 5.0, Windows 2000, or Windows XP
  • Lightweight Directory Access Protocol (LDAP)
  • Novell NetWare Directory Service
  • Novell Netware 3.x

For the purposes of this article we will restrict ourselves to IIS AD.

The key to understanding how to access IIS AD object is to first understand the components of the IIS metabase path. The metabase is a hierarchical structure that mirrors the IIS installation. Each node of the metabase (called a key) has associated configuration values (called metabase properties). Changing these properties corresponds to changing the IIS configuration values of the associated IIS elements.

A typical metabase path for websites is: IIS://ServerName/WebService/Server/Root/VirtualDirectoryName

IIS:// - Indicates to the DirectoryEntry object that we are dealing with a IIS AD as opposed to LDAP or WinNT Ads.

ServerName - The name (or IP Address) of the machine on which the web server is hosted. If we are working on a local instance the value for this will be localhost.

WebService - This component of the metabase path indicates whether we are dealing with a web site service or an FTP service. For web sites the value will be W3SVC and for FTP it will be MSFTPSVC.

Server – If there are multiple web servers on the same machine, the value for this (of integer type) will indicate which web server to access. For most cases the value for this will be 1.

Root - The root of the web server.

VirtualDirectoryName -The name of our Virtual Directory.

Creating a Virtual Directory Programatically

Now that we understand the IIS metabase path, we can get our hands dirty by writing some code that will actually create the virtual directory.

First we need to put a reference to the System.DirectoryServices namespace to access the DirectoryEntry object. Then we define a class (InetMgr)which encapsulates the functionality that is needed. The relavent portions of the code will be disccussed in this article. For full working sample, you can download the zip file from the artifact section of this article.

We need to connect to the IIS server instance, so we declare an object of DirectoryEntry type. We can get a reference to the web server instance by passing in the metabase path of the server to this DirectoryEntry object.

public void Connect()                                                                                                           
     {                                                                                                                                     
         try                                                                                                                               
         {                                                                                                                                 
             mIISServer =new DirectoryEntry("IIS://" + mServerName + "/W3SVC/1") ;            
             DirectoryEntry rootFolder =mIISServer.Children.Find("Root", VirDirSchemaName);
                mIISRootPath=rootFolder.Path;                                                                           
            }                                                                                                                              
         catch (Exception ex)                                                                                                    
         {                                                                                                                                 
             throw new Exception("Error while trying to connect to IIS server" + mIISServer,ex);
         }                                                                                                                                 
     }                                                                                                                                     

Now that we have a reference to the IIS server object we can now start creating the virtual directory. We first start by getting a reference to the root node of the web server by using the Children.Find method on the IIS server DirectoryEntry object.

To create a virtual directory we need to add to this root node a new node, which will be our virtual directory. Remember that all ADs are a hierarchical representation, so we can traverse it like a tree. We use the Children.Add method to add the virtual directory.

public void CreateVirtualDirectory(string alias, string directoryPath)                                   
     {                                                                                                                                 
         //Get a reference to the root of the IIS Server                                                           
         DirectoryEntry rootFolder =mIISServer.Children.Find("Root", VirDirSchemaName);
                                                                                                                                          
         try                                                                                                                           
         {                                                                                                                             
             rootFolder.RefreshCache();//Refresh the cache to commit  any pending changes    
             string virDirPath =mIISRootPath + "/" + alias + "/";                                               
             //Create a Virtual Directory                                                                                  
             DirectoryEntry newVirDir =rootFolder.Children.Add(alias,VirDirSchemaName);  
                                                                                                                                         
                //Set the properties for this node                                                                          
             newVirDir.Properties["AccessRead"][0]=true   ;                                                    
             newVirDir.Properties["AccessScript"][0]=true;                                                     
             newVirDir.Properties["Path"][0]=directoryPath  ;                                                 
                                                                                                                                         
             //Create an Application                                                                                        
             newVirDir.Invoke("AppCreate2",2);                                                                    
                                                                                                                                        
             newVirDir.CommitChanges() ;                                                                             
             rootFolder.CommitChanges() ;                                                                             
             newVirDir.Close() ;                                                                                               
             rootFolder.Close() ;                                                                                             
             mIISServer.CommitChanges() ;                                                                            
             mIISServer.Close() ;                                                                                           
                                                                                                                                         
         }                                                                                                                               
         catch (Exception ex)                                                                                                  
         {                                                                                                                              
             throw new Exception("Error Creating Virtual Directory "+ alias +                           Environment.NewLine + ex.Message,ex) ;                                                                         
         }                                                                                                                              
     }                                                                                                                                  

Next we need to set the various properties for this node. The properties in the above code represent the settings for running an ASP.NET web site. We also need to make the virtual directory function as an application. The hitch is the IIS objects do not enable us to call their underlying methods directly. The ADSI DirectoryEntry representation of IIS doesn't enable us to use their full functionality. However we can get to those methods through the Invoke method of the DirectoryEntry object. But we need to understand the IIS object functions and order and type of parameters. For a full list of functions and parameters see the References section of this article. For creating an application we use the AppCreate2 function with a parameter of 2 which indicates that it should be run in a pooled process.

Finally Commit all changes to the nodes and the server and close all connections. The deletion of virtual directories is similar. (See the implementation in the code sample download).

 

Conclusion
As you have seen it is relatively easy to create and modify websites using .NET System.DirectoryServices namespace classes programatically. You can take this article as a starting point and develop a full scale administration tool for your IIS servers infact to any of the ADs listed.
References

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/iissdk/iis/ref_prog_iaorefiwvd.asp

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemDirectoryServices.asp

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon/html/vbconwhatyouneedtoknowaboutactivedirectoryadsi.asp

 

Please rate the quality of this article
Poor
Outstanding
Tell me why you rated this content this way. (optional)
 
Rating Spread

  

Copyright 2002-2005 Sai Panyam   Terms Of Use  Privacy Statement