Pratidhwani

Echo from the Tech Sphere

<December 2008>
SuMoTuWeThFrSa
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910


Navigation

My Blogs

My Articles

Subscriptions

Article Categories



My Articles

My Articles
Create a Virtual Directory and Edit its Properties in IIS using C#

Back when I was working at Qwest Communications (Summer of ’02 precisely), I was given the task to create a virtual directory for reports on every server at my hand. The path was local to each computer and all the authentication requirements were identical. I could as well have gone to IIS Administrative console on each machine but I thought to take a shot at C#.

First, I’d to dig thro the bitmask values for the properties of a virtual directory on the IIS server. I’d to look no further than the following Microsoft documentation online (http://www.microsoft.com/windows2000/en/server/iis/default.asp?url=/windows2000/en/server/iis/htm/asp/apro1cms.htm ). Based on my requirements I created an XML config (WebSettings.Config) file which looks as follows:

WebSettings.Config

<?xml version="1.0" encoding="utf-8" ?>

<WebSettings>

      <!-- Directory to be set for virtual folder -->

      <ActualDirectory>E:\logs\imaedi\REPORTS</ActualDirectory>

      <ServerName>localhost</ServerName>

      <IISRootPath>IIS://</IISRootPath>

      <VirtualDirectorySchemaName>IIsWebVirtualDir</VirtualDirectorySchemaName>

      <WebServicePath>/W3SVC/1</WebServicePath>

      <ActiveDirectoryRootPath>Root</ActiveDirectoryRootPath>

      <VirtualDirectoryName>DRBINTRFCRPRTS</VirtualDirectoryName>

     

      <!--

            Authentication Bitmask Values

Constant          Value       Description

MD_AUTH_ANONYMOUS 0x00000001  Anonymous authentication available.

MD_AUTH_BASIC     0x00000002  Basic authentication available.

MD_AUTH_NT        0x00000004  Windows authentication schemes available.

      -->

      <AuthFlagValue>0x00000001</AuthFlagValue>

      <DefaultLogonDomain>YourCorporatePDC</DefaultLogonDomain>

     

      <!--

            Access Bitmask Values

Constant                      Value       Description

MD_ACCESS_READ                0x00000001  Allow read access.

MD_ACCESS_WRITE               0x00000002  Allow write access.

MD_ACCESS_EXECUTE             0x00000004  Allow file execution (includes script permission).

MD_ACCESS_SOURCE              0x00000010  Allow source access.

MD_ACCESS_SCRIPT              0x00000200  Allow script execution.

MD_ACCESS_NO_REMOTE_WRITE     0x00000400  Local write access only.

MD_ACCESS_NO_REMOTE_READ      0x00001000  Local read access only.

MD_ACCESS_NO_REMOTE_EXECUTE   0x00002000  Local execution only.

MD_ACCESS_NO_REMOTE_SCRIPT    0x00004000  Local host access only.

      -->

      <AccessFlagValue>0x00000205</AccessFlagValue>

     

      <!--

            SSL Bitmask Values

Constant                Value       Description

MD_ACCESS_SSL           0x00000008  SSL permissions required.

MD_ACCESS_NEGO_CERT     0x00000020  Client certificate optional.

MD_ACCESS_REQUIRE_CERT  0x00000040  Client certificate required.

MD_ACCESS_MAP_CERT      0x00000080  Server will map client certificate to Windows account.

MD_ACCESS_SSL128        0x00000100  SSL permissions with 128-bit key required.

      -->

      <AccessSSLFlagValue>0x00000000</AccessSSLFlagValue>

     

      <DefaultDocument>default.asp</DefaultDocument>

     

      <!-- 

            Directory Browsing Bitmask Values

Constant                      Value       Description

MD_DIRBROW_SHOW_DATE          0x00000002  Show date.

MD_DIRBROW_SHOW_TIME          0x00000004  Show time.

MD_DIRBROW_SHOW_SIZE          0x00000008  Show file size.

MD_DIRBROW_SHOW_EXTENSION     0x00000010  Show file name extension.

MD_DIRBROW_LONG_DATE          0x00000020  Show full date.

MD_DIRBROW_LOADDEFAULT        0x40000000  Load default page, if it exists.

MD_DIRBROW_ENABLED            0x80000000  Enable directory browsing.

      -->

      <DirBrowseFlagValue>0xC000003E</DirBrowseFlagValue>

     

      <!--

            For details of these properties and their bit mask values visit

            http://www.microsoft.com/windows2000/en/server/iis/default.asp?url=/windows2000/en/server/iis/htm/asp/apro1cms.htm

      -->

</WebSettings>

The beauty of bitmask values is that you can add them to have your own custom requirements. For example, if I want to have both Anonymous authentication (bitmask: 0x00000001) and Integrated Windows authentication (bitmask: 0x00000004), I can set the AuthFlagValue to 0x00000005. Similarly when I am setting AccessFlagValue to 0x00000205, I am allowing script execution (bitmask: 0x00000200), file execution (bitmask: 0x00000004) and read access (bitmask: 0x00000001). Quite neat. Huh?

The next task was to have a class that can hold the values read from the config file. There are several ways to do this but it is out of the scope of the present discussion. In the meanwhile, you may look at the following skeleton and have your own constructor implementation to populate from the config file.

WebSettings.cs

using System;

using System.IO;

using System.Xml;

using System.Globalization;

namespace WebHosting {

  public class WebSettings {

    // Private  variables defined

    //

    public string actualDirectory = null;

    public string serverName = null;

    public string iisRootPath = null;

    public string virtualDirectorySchemaName = null;

    public string webServicePath = null;

    public string activeDirectoryRootPath = null;

    public string virtualDirectoryName = null;

    public int authFlagValue = 0;

    public string defaultLogonDomain = null;

    public int accessFlagValue = 0;

    public int accessSSLFlagValue = 0;

    public string defaultDocument = null;

    public int dirBrowseFlagValue = 0;

    public WebSettings() {

      // Populate from the Xml Config File

      //

    }

  }

}

The last and the most important task was to tell the IIS somehow about our intentions. “Active Directory” came to the rescue here. .NET provides a System.DirectoryServices namespace which gives us a way to control Active Directory objects. As Microsoft puts “The System.DirectoryServices namespace provides easy access to Active Directory from managed code. The namespace contains two component classes, DirectoryEntry and DirectorySearcher, which use the Active Directory Services Interfaces (ADSI) technology.”

So I had the HostWeb.cs file, which contained the entry point of the console application. When run, it looks for the virtual directory and if not found, creates one. Then it sets the properties specified in the config file in terms of the bitmask values and commits the changes. If in future, you need to change some of the properties, you can change it in the config file and rerun the application to apply the new values.

HostWeb.cs

using System;

using System.IO;

using System.DirectoryServices;

namespace WebHosting {

  public class HostWeb {

    [STAThread]

    public static void Main(string[] args) {

      WebSettings ws = null;

                 

      try {

        ws = new WebSettings();

      }

      catch (Exception e) {

        // Your exception handling

        return;

      }

      // Create web service

      //

      try {

        createVirtualDirectory(ws);

      }

      catch (Exception e) {

        // Your exception handling

      }

      return;

    }

    public static void createVirtualDirectory (WebSettings ws) {

      DirectoryEntry iisWebService = null;

      DirectoryEntry webServiceRoot = null;

      DirectoryEntry virDir = null;

      try {

        iisWebService = new DirectoryEntry(ws.iisRootPath + ws.serverName + ws.webServicePath);

        webServiceRoot = iisWebService.Children.Find(ws.activeDirectoryRootPath, ws.virtualDirectorySchemaName);

      }

      catch (Exception e) {

        throw new Exception("Could not connect to " + ws.serverName + " or its child " + ws.activeDirectoryRootPath + " in schema " + ws.virtualDirectorySchemaName, e);

      }                

      // Find the virtual directory, if not found, create it

      //

      try {

        virDir = webServiceRoot.Children.Find(ws.virtualDirectoryName, ws.virtualDirectorySchemaName);

      }

      catch (System.IO.DirectoryNotFoundException) {

        virDir = webServiceRoot.Children.Add(ws.virtualDirectoryName, ws.virtualDirectorySchemaName);

        virDir.CommitChanges();

      }

      catch (Exception e) {

        Console.WriteLine(e.ToString());

        return;

      }

      // Set Access depending on bit mask values

      //

      if (virDir != null) {

        try {    

          // Authentication

          //

          virDir.Properties["AuthFlags"].Value = ws.authFlagValue;

          virDir.Properties["DefaultLogonDomain"].Value = ws.defaultLogonDomain;

          // Access Type

          //

          virDir.Properties["AccessFlags"].Value = ws.accessFlagValue;

          // Set SSL

          //

          virDir.Properties["AccessSSLFlags"].Value = ws.accessSSLFlagValue;

          // Default Path and Page to be displayed

          //

          virDir.Properties["Path"].Value = ws.actualDirectory;

          virDir.Properties["DefaultDoc"].Value = ws.defaultDocument;

          // Directory Browsing

          //

          virDir.Properties["DirBrowseFlags"].Value = ws.dirBrowseFlagValue;

          // Commit Changes

          //

          virDir.CommitChanges();

          webServiceRoot.CommitChanges();

          iisWebService.CommitChanges();

        }

        catch (Exception e) {

          Console.WriteLine(e.ToString());

          throw new Exception("Virtual Directory " + ws.virtualDirectoryName + " can not be created or updated", e);

        }

      }

    }

  }

}

Summary: In this article, we learned how to create a virtual directory in IIS server from .NET environment using ADSI technology. We used classes from System.DirectoryServices namespace and used the Microsoft documentation to set the properties of the virtual directory in terms of bitmask values.

N.B.: All the code above was fully tested in .NET 1.0 environment. If you find any difficulty running the above code, kindly set a note to the author and he’ll correct the code with all the due appreciation to the sender.

Ram Dash is a freelance ASP.NET, C# developer and can be reached at “ram underscore dash at fastmail dot fm”. If you wish to reprint this article, a note with the link to the author would suffice.

posted Wednesday, August 11, 2004 5:19 PM by rpdash with 1 Comments




Powered by Dot Net Junkies, by Telligent Systems