Robin Kedia

Web Architect

Playing around with IIS Application Pool using C#

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.

Posted: Apr 28 2009, 03:45 PM by worldclasscoders | with 19 comment(s) |
Filed under: ,

Comments

INeedADip said:

This is great....I've been looking for some simple code examples on how to interact with IIS.  

If you've got time...we would like to add and remove IIS host headers for a website.  We let our users use their own domain for private label features, but right now it shoots us an email and we have to setup the headers manually on all the web servers in our farm (small farm...but still).

Everytime we look into automating the processes it appears that the code ends up being very complicated and a little overwhelming, any pointers would be GREATLY appreciated.

# April 28, 2009 12:00 PM

worldclasscoders said:

Sure enjoy -  /// <summary> /// Adds a host header value to a specified website.  /// </summary> /// <param name="hostHeader">The host header. Must be in the form IP:Port:Hostname </param> /// <param name="websiteID">The ID of the website the host header should be added to </param> 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;       }

 

# April 28, 2009 12:10 PM

INeedADip said:

Thanks a ton!

# April 28, 2009 12:13 PM

gOODiDEA.NET said:

.NET C# COM Object for Use In JavaScript / HTML, Including Event Handling Show me the memory: Tool for

# April 29, 2009 10:35 PM

gOODiDEA said:

.NETC#COMObjectforUseInJavaScript/HTML,IncludingEventHandlingShowmethememory...

# April 29, 2009 10:38 PM

satalaj said:

Nice code.

It can be used to recycle the IIS application pool remotely.

# April 30, 2009 2:11 AM

Zero said:

.Children.Find(apppool,"IIsApplicationPool").Invoke("Recycle", null);

# July 2, 2009 11:58 PM

vinay said:

Hi,

I need a method or script which will help in finding the status of Application Pool and if any specified application pool is in stopped/stuck state that needs to be recycled automatically. Im totally new to IIS.

If you have any script for this can you please update me. You can contact me at vinay_prasad01@yahoo.co.in

# August 18, 2009 2:38 AM

SK said:

Hi... I need to find if an app pool is running before calling Recycle function. How can I check the status of an app pool?

Thanks for the article... very informative.

# September 28, 2009 7:42 PM

Ericbojo@gmail.com said:

I want to use similar code but boiled down to 2 lines to recycle a website remotely.

DirectoryEntry objDirEntry = new DirectoryEntry(@"IIS://" + serverIP + @"/W3SVC/AppPools/" + AppPoolName);                        

objDirEntry.Invoke("Recycle", null);

But i keep getting the exception message:

Exception has been thrown by the target of an invocation.

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

How do I assign administrator's rights.  This is running in an .aspx page..

# October 16, 2009 1:05 PM

MikeM said:

I inserted your code into a simple test app to create appPools on Server 2008 and it works fine.  However, when I insert the same code into our real app it throws a Com exception.  Any ideas would be greatly appreciated.

# October 23, 2009 7:35 PM

Bosshog said:

Hi all, thanks for this great code,

another way to assign administrator rights is to use impersonation in web.config.

Add this in your web.config:

<system.web>

<identity impersonate="true" userName="Administrator" password="your admin password"/>

I have used this code within a web.config on my Webservice dedicated to manage IIS remotly.

Have fun

# November 5, 2009 12:10 PM

Bosshog said:

To use impersonation, dont forget to remove all userName and password entry of the C# code.

like this:

public static bool RecycleAppPool(string serverName, string appPoolName)

       {

           DirectoryEntry appPools = new DirectoryEntry("IIS://" + serverName + "/w3svc/apppools");

           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;

       }

Instead of this:

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;

       }

# November 5, 2009 12:14 PM

NotSick (play on my last name) said:

Excellent article.  Thanks.

# December 22, 2009 10:27 AM

Rakesh K Sharma said:

To know the status of Application pool wheter its running or stopped....

string appPoolName = listAppPool[i].ToString();

string appPoolPath = @"IIS://" + System.Environment.MachineName + "/W3SVC/AppPools/" + appPoolName;

           //Getting Status of Applicaiton Pools

           try

           {

               DirectoryEntry w3svc = new DirectoryEntry(appPoolPath);

               switch (w3svc.Properties["AppPoolState"].Value)

               {

                   case 2:

                       Response.Write("Started");

                       break;

                   case "4":

                       Response.Write("Stopped");

                       break;

                   default:

                       Response.Write("UNKNOWN");

                       break;

               }

           }

           catch (Exception ex)

           {

           }

# April 8, 2010 8:41 AM

pkw versicherungen im vergleich said:

Murder Her,value media knowledge estimate blow bag human neck confirm large male necessary error head rural good look payment severe conclusion control climb nice within brain fair sell practical direct protect hard expense widely team technique point experience programme may period building eat study wear work before recognition elsewhere flow intention cover entitle total help payment attract yourself plant effort vast doctor plan information point audience actually cost show effect merely deny possible walk award track light approve candidate arrive enemy temperature hospital operation condition help set family supply reveal magazine wash

# October 10, 2011 7:32 AM

fat loss said:

This post could not be more on the money!

# November 11, 2011 9:29 PM

Neeraj said:

How to check application pool flag for enable32bitapplication?

# March 15, 2012 5:12 AM

sudharshan said:

Hi I am getting some runtime com exeption could you please help

Thanks

# March 27, 2012 9:30 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)