:::: MENU ::::

Wednesday, April 29, 2009

Just thought of sharing a some useful IIS App pool functions I wrote long back in C#.  Requirement was to play around with IIS v5.0/6.0 and do all settings dynamically -

Note : You must have administrator priveledge to perform all IIS actions.

Namespace Required

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.IO;
using System.Diagnostics;
using IISOle; // IISOle requires a reference to the Active Directory Services.
using System.Reflection;
using System.Configuration;
using System.Text.RegularExpressions;

Functions

public static bool RecycleAppPool(string serverName, string adminUsername, string adminPassword, string appPoolName)
        {
            DirectoryEntry appPools = new DirectoryEntry("IIS://" + serverName + "/w3svc/apppools", adminUsername, adminPassword);
            bool status = false;
            foreach (DirectoryEntry AppPool in appPools.Children)
            {
                if (appPoolName.Equals(AppPool.Name, StringComparison.OrdinalIgnoreCase))
                {
                    AppPool.Invoke("Recycle", null);
                    status = true;
                    break;
                }
            }
            appPools = null;
            return status;
        }

 

/// <summary>
        /// Creates AppPool
        /// </summary>
        /// <param name="metabasePath"></param>
        /// <param name="appPoolName"></param>
        public static bool CreateAppPool(string metabasePath, string appPoolName)
        {
            //  metabasePath is of the form "IIS://<servername>/W3SVC/AppPools"
            //    for example "IIS://localhost/W3SVC/AppPools"
            //  appPoolName is of the form "<name>", for example, "MyAppPool"
            DirectoryEntry newpool, apppools;
            try
            {
                if (metabasePath.EndsWith("/W3SVC/AppPools"))
                {
                    apppools = new DirectoryEntry(metabasePath);
                    newpool = apppools.Children.Add(appPoolName, "IIsApplicationPool");
                    newpool.CommitChanges();
                    newpool = null;
                    apppools = null;
                    return true;
                }
                else
                    throw new Exception(" Failed in CreateAppPool; application pools can only be created in the */W3SVC/AppPools node.");               
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Failed in CreateAppPool with the following exception: \n{0}", ex.Message));
            }
            finally
            {
                newpool = null;
                apppools = null;
            }
        }

        /// <summary>
        /// Assigns AppPool to Virtual Directory
        /// </summary>
        /// <param name="metabasePath"></param>
        /// <param name="appPoolName"></param>
        public static bool AssignVDirToAppPool(string metabasePath, string appPoolName)
        {
            //  metabasePath is of the form "IIS://<servername>/W3SVC/<siteID>/Root[/<vDir>]"
            //    for example "IIS://localhost/W3SVC/1/Root/MyVDir"
            //  appPoolName is of the form "<name>", for example, "MyAppPool"
            //Console.WriteLine("\nAssigning application {0} to the application pool named {1}:", metabasePath, appPoolName);

            DirectoryEntry vDir = new DirectoryEntry(metabasePath);
            string className = vDir.SchemaClassName.ToString();
            if (className.EndsWith("VirtualDir"))
            {
                object[] param = { 0, appPoolName, true };
                vDir.Invoke("AppCreate3", param);
                vDir.Properties["AppIsolated"][0] = "2";
                vDir = null;
                return true;
            }
            else
                throw new Exception(" Failed in AssignVDirToAppPool; only virtual directories can be assigned to application pools");
        }

 

  /// <summary>
        /// Delete AppPool
        /// </summary>
        /// <param name="metabasePath"></param>
        /// <param name="appPoolName"></param>
        public static bool DeleteAppPool(string serverName, string adminUsername, string adminPassword, string appPoolName)
        {
            //  metabasePath is of the form "IIS://<servername>/W3SVC/AppPools"
            //  for example "IIS://localhost/W3SVC/AppPools"
            //  appPoolName is of the form "<name>", for example, "MyAppPool"

            DirectoryEntry appPools = new DirectoryEntry("IIS://" + serverName + "/w3svc/apppools", adminUsername, adminPassword);
            bool status = false;
            foreach (DirectoryEntry AppPool in appPools.Children)
            {
                if (appPoolName.Equals(AppPool.Name, StringComparison.OrdinalIgnoreCase))
                {
                    AppPool.DeleteTree();
                    status = true;
                    break;
                }
            }
            appPools = null;
            return status;
        }

Hope you folks find it useful. If you need any other help related to IIS, just post me your requirement.

        public static void AddHostHeader(string serverName, string adminUsername, string adminPassword, string websiteName, string hostHeader)

        {

            string siteID = GetSiteID(serverName, adminUsername, adminPassword, websiteName);

            DirectoryEntry root = new DirectoryEntry("IIS://" + serverName + "/W3SVC/" + siteID, adminUsername, adminPassword);

            PropertyValueCollection serverBindings = root.Properties["ServerBindings"];

            //Add the new binding        

            serverBindings.Add(hostHeader);

            //Create an object array and copy the content to this array     

            Object[] newList = new Object[serverBindings.Count];

            serverBindings.CopyTo(newList, 0);

            //Write to metabase

            root.Properties["ServerBindings"].Value = newList;

            root.CommitChanges();

            root.Close();

            root.Dispose();

        }

 

        public static string GetSiteID(string serverName, string adminUsername, string adminPassword, string websiteName)

        {

            DirectoryEntry root = new DirectoryEntry("IIS://" + serverName + "/W3SVC", adminUsername, adminPassword);

            string siteID = "0";

            foreach (DirectoryEntry e in root.Children)

            {

                if ((e.SchemaClassName == "IIsWebServer") && (e.Properties["ServerComment"][0].ToString() == websiteName))

                {

                    siteID = e.Name;

                }

            }

            root.Close();

            root.Dispose();

            return siteID;

        }