Click here to Skip to main content
15,883,705 members
Articles / Web Development / IIS
Tip/Trick

IIS Application Pool Operations via C#

Rate me:
Please Sign up or sign in to vote.
3.33/5 (3 votes)
11 Dec 2015CPOL2 min read 35.8K   11   3
A simple article which describes how to control IIS application pool operations via C#

Introduction

There are situations where we would need to restart IIS application pools remotely via C#. This tip aims to achieve that with any IIS installed destination server.

Background

There are many ways to check status, stop, start the application pools on remote servers. Even though System.DirectoryService.DirectoryEntry method provides simple 3 lines of code to do that, still we are in need of a cleaner code which can perform the action under restricted environments as well.

WMI provides us vast methods to accomplish the task. This code uses both C# and WMI methods to provide a robust application which will work in 99.99% of environments (0.1% exception may exist on very highly secured environments).

IIS and Application Pool Concept

Internet Information Services, IIS is an extensible web server created by Microsoft for use with Windows family. IIS supports HTTP, HTTPS, FTP, FTPS, SMTP and NNTP.

We can separate different Web applications and Web sites into groups known as application pools. An application pool is a group of one or more URLs that are served by a worker process or set of worker processes. Any Web directory or virtual directory can be assigned to an application pool.

Use multiple application pools when you want to help ensure that applications and Web sites are confidential and secure. For example, an enterprise organization might place its human resources Web site and its finance Web site on the same server, but in different application pools.

IIS WMI Provider

Like other options like services, computer details, processes, etc., IIS can also be controlled by WMI. Classes are implemented by the IIS WMI provider in the MicrosoftIISv2 namespace. Starting Windows XP and Windows server 2003 SP1, any script that uses WMI to access IIS remotely, must encrypt the connection, else it will fail with WBEM_ACCESS_DENIED error. This authentication property must be set during the call.

Code # 1

The below code contains two functions: one to determine the status of an application pool:

C#
private bool IsApplicationPoolRunning(string servername, string strAppPool)
        {
            string sb = ""; // String to store return value

            // Connection options for WMI object
            ConnectionOptions options = new ConnectionOptions();

            // Packet Privacy means authentication with encrypted connection.
            options.Authentication = AuthenticationLevel.PacketPrivacy;

            // EnablePrivileges : Value indicating whether user privileges 
            // need to be enabled for the connection operation. 
            // This property should only be used when the operation performed 
            // requires a certain user privilege to be enabled.
            options.EnablePrivileges = true;

            // Connect to IIS WMI namespace \\root\\MicrosoftIISv2
            ManagementScope scope = new ManagementScope(@"\\" + 
            	servername + "\\root\\MicrosoftIISv2", options);

            // Query IIS WMI property IISApplicationPoolSetting
            ObjectQuery oQueryIISApplicationPoolSetting = 
            	new ObjectQuery("SELECT * FROM IISApplicationPoolSetting");

            // Search and collect details thru WMI methods
            ManagementObjectSearcher moSearcherIISApplicationPoolSetting = 
            	new ManagementObjectSearcher(scope, oQueryIISApplicationPoolSetting);
            ManagementObjectCollection collectionIISApplicationPoolSetting = 
            				moSearcherIISApplicationPoolSetting.Get();

            // Loop thru every object
            foreach (ManagementObject resIISApplicationPoolSetting 
            	in collectionIISApplicationPoolSetting)
            {
                // IISApplicationPoolSetting has a property called Name which will 
                // return Application Pool full name /W3SVC/AppPools/DefaultAppPool
                // Extract Application Pool Name alone using Split()
                if (resIISApplicationPoolSetting
                	["Name"].ToString().Split('/')[2] == strAppPool) 
                {
                    // IISApplicationPoolSetting has a property 
                    // called AppPoolState which has following values
                    // 2 = started 4 = stopped 1 = starting 3 = stopping
                    if (resIISApplicationPoolSetting["AppPoolState"].ToString() != "2")
                    {
                        return false;
                    }
                }
            }
            return true;
        }

Code Explanation

  1. Add System.Management reference to the code
  2. First, we need to configure connection options for WMI
  3. Authentication level is set to PacketPrivacy to enable authentication with encryption
  4. As needed, set EnablePriviliges to true (IIS operations don't need this, but in case web server is highly secured, sometimes we might need this)
  5. Connect to MicrosoftIISv2 namespace with the WMI options
  6. Query IIS WMI property IISApplicationPoolSetting which will contain application pool name and its status
  7. As needed, interpret the properties Name and AppPoolState to get the result.

Code # 2

C#
public void performRequestedAction(String servername, String AppPoolName, String action)
        {
            StringBuilder sb = new StringBuilder();
            ConnectionOptions options = new ConnectionOptions();
            options.Authentication = AuthenticationLevel.PacketPrivacy;
            options.EnablePrivileges = true;
            ManagementScope scope = new ManagementScope(@"\\" + 
            	servername + "\\root\\MicrosoftIISv2", options);

            // IIS WMI object IISApplicationPool to perform actions on IIS Application Pool
            ObjectQuery oQueryIISApplicationPool = 
            	new ObjectQuery("SELECT * FROM IISApplicationPool");

            ManagementObjectSearcher moSearcherIISApplicationPool = 
            	new ManagementObjectSearcher(scope, oQueryIISApplicationPool);
            ManagementObjectCollection collectionIISApplicationPool = 
            	moSearcherIISApplicationPool.Get();
            foreach (ManagementObject resIISApplicationPool in collectionIISApplicationPool)
            {
                if (resIISApplicationPool["Name"].ToString().Split('/')[2] == AppPoolName)
                {
                    // InvokeMethod - start, stop, recycle can be passed as parameters as needed.
                    resIISApplicationPool.InvokeMethod(action, null);
                }
            }
        }

Code Explanation

  1. Here, we use IISApplicationPool just to retrieve the name of the application pool and invoke methods like start, stop, recycle the application pool as needed.
  2. Other code explanations are the same as above:
C#
// Is any result other that started
if (!IsApplicationPoolRunning("localhost","DefaultAppPool"))
{
    // stop and start the pool
    performRequestedAction("localhost", "DefaultAppPool", "stop");
    performRequestedAction("localhost", "DefaultAppPool", "start");
}

Replace localhost with any remote machine and DefaultAppPool with any application pool as needed.

References

  1. Packet Privacy and other DCOM config details - https://support.microsoft.com/en-us/kb/176799
  2. IIS WMI - https://msdn.microsoft.com/en-us/library/ms525265(v=vs.90).aspx

History

  • 1st revision - 12-Dec-2015

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionUnauthorizedAccessException. Pin
Member 171130119-Jun-19 12:19
Member 171130119-Jun-19 12:19 
PraiseGreat Article Pin
subbu_aa23-Feb-16 5:29
subbu_aa23-Feb-16 5:29 
PraiseRe: Great Article Pin
rvjagadheesh23-Feb-16 6:02
professionalrvjagadheesh23-Feb-16 6:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.