Click here to Skip to main content
Click here to Skip to main content

Recycling IIS 6.0 application pools programmatically

By , 27 May 2008
 

Introduction

The need for programmatically executing an application pool recycle can arise for a number of reasons. It happened to me while I was managing lots of similar ASP.NET web applications, hosted on multiple IIS 6.0 web servers, and I had to find a way to reset their cache in a quick and easy way. In particular, I was using the WebSettings mechanism for storing my ASP.NET application configuration settings and, due to the number of web apps to be contacted on many web servers, the multiple calls to GetWebSetting("", True) were becoming unmanageable. I found a "quick and easy way" to recycle application pools (hence, also, to reset the ASP.NET cache) through the DirectoryEntry .NET Framework class, and now I'm sharing this with you.

Recycling the web from the web

I was looking for a way to recycle application pools without the need to connect to the web server (via a Terminal Server connection, or connecting remotely from my local IIS MMC console); as stated, this was useful, especially considering the lots of application pools distributed on more than ten web servers... My first thought was to develop a Windows Forms application (one of my famous "tools"), capable of interacting in some way with IIS or with its metabase, in order to execute an AppPool recycle with a single click. But, then I realized it was more natural to create this piece of code directly inside an ASP.NET application. So, I wrote a single, very "light", ASP.NET page.

This web page needs an XML data file (let's name it ApplicationPoolsList.xml) where the names and paths of all the desired application pools are listed; in fact, my goal was to recycle, at once, a set of "similar" AppPools. This is a sample of the XML data file:

<?xml version="1.0" encoding="utf-8" ?>
<AppPoolsList>
  <AppPool>IIS://SERVER00123/W3SVC/AppPools/Northwind</AppPool>
  <AppPool>IIS://SERVER00123/W3SVC/AppPools/Acme</AppPool>
  <AppPool>IIS://SERVER00125/W3SVC/AppPools/Northwind</AppPool>
  <AppPool>IIS://SERVER00125/W3SVC/AppPools/Acme</AppPool>
</AppPoolsList>

Each "AppPool" node contains the full path of an application pool to be recycled, including the web server machine name and the AppPool name as it appears on the IIS management console.

For example, in "IIS://SERVER00123/W3SVC/AppPools/Northwind":

  • "SERVER00123" is the web server machine name (as returned by System.Environment.MachineName when run on that machine);
  • "Northwind" is the AppPool name as it appears on the IIS management console when looking at AppPools hosted on SERVER00123.

The ASP.NET page that does the magic is very simple, and it is coded as follows:

<%@ Page Language="vb" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Management" %>
<%@ Import Namespace="System.DirectoryServices" %>
<%
  ' Utility page for AppPool recycling (by Alberto Venditti, 20/05/2008)
  Response.Write("<HTML><HEAD></HEAD><BODY>")

  Dim AppPoolsList As New XmlDocument
  AppPoolsList.Load(Server.MapPath("ApplicationPoolsList.xml"))
  Dim AppPool As XmlNode
  For Each AppPool In AppPoolsList.SelectNodes("AppPoolsList/AppPool")
    Dim AppPoolFullPath As String = AppPool.InnerText
    ' AppPoolFullPath must be in the form of: "IIS://" + machine + _
    '       "/W3SVC/AppPools/" + appPoolName
    Try
      Dim w3svc As New DirectoryEntry(AppPoolFullPath)
      w3svc.Invoke("Recycle", Nothing)
      Response.Write(AppPoolFullPath & "<br />")
    Catch
      Response.Write(AppPoolFullPath & " [error]<br />")
    End Try
  Next
 
  Response.Write("<p />-- done --")
  Response.Write("</BODY></HTML>")
%>

That's all.

The heart of the execution consists of a call to the Invoke method on the DirectoryEntry class (be aware that this call could suffer restrictions depending upon the permission level of the ASP.NET account). I know: it's not a great and wonderful piece of code, but I found it very, very useful to reset the ASP.NET Cache of multiple applications on multiple servers.

Interesting note: you can also use this page to recycle the AppPool that hosts the web application that is serving the page itself. The AppPool is recycled immediately, after the execution of the page terminates.

License

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

About the Author

Alberto Venditti
Technical Lead
Italy Italy
Member
I was born in 1970.
 
I studied Electronic Engineering (graduated in 1997).
 
Subsequently, I passed some Microsoft exams, and currently I'm certified as:
MCP, MCT, MCDBA, MCSD, MCAD, MCSD for .NET (early achiever).
 
My first computer experience dates back to early 80s, with a Sinclair ZX81.
From that time on, as many "friends" say, my IT-illness has increased year by year.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionAccess is denied.memberccheeseman30 Jun '11 - 9:09 
Thanks for the script. I'm getting an Access is denied error which from your notes looks like an ASP.Net permission issue. Where do I set these permissions for this to work? I've tried setting the permissions for the folder the site is contained but that does not seem to work. Thank you for any help you can offer.
 
[UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))]
 
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.DirectoryServices.DirectoryEntry.Invoke(String methodName, Object[] args) +238
ASP.recycle_aspx.__Render__control1(HtmlTextWriter __w, Control parameterContainer) +238
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +256
System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19
System.Web.UI.Page.Render(HtmlTextWriter writer) +29
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99
System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1266
AnswerRe: Access is denied.memberAlberto Venditti3 Jul '11 - 22:29 
The error appears to be on the Invoke method, not in the file system access.
Then: verify the identity of the AppPool executing the ASP.NET page, and be sure that user's permissions allows him to execute an AppPool recycle (even testing this interactively, if needed).
AV
GeneralThe RPC server is unavailable.memberTsetsE12 Apr '11 - 3:07 
Hi,
 
I create this project in vs 2010 targeting framework version 2.0. The code is exactly the same as described here, didn't change one single line of code.
 
Im getting the following exception: The RPC server is unavailable.
 
Windows 2003 server web edition. It's the local machine (not the production server). The application pool is set to framework 2.0.
 
Any ideia why I am getting this exception? It's in the following line of code: w3svc.Invoke("Recycle", Nothing)
 
Thanks in advance for your help.
 
Joao
GeneralRe: The RPC server is unavailable.memberTsetsE12 Apr '11 - 3:08 
Not the application pool that is set to 2.0 but the virtual directory created. Also iis 6. Thanks again
GeneralRe: The RPC server is unavailable.memberAlberto Venditti14 Apr '11 - 0:09 
Hi.
This error could indicate insufficient permission for executing the Invoke method (see my note about "permission level of the ASP.NET account" into the article).
So, my suggestion is to verify the identity of the AppPool executing the ASP.NET page itself.
Hope this helps.
Cheers, AV
GeneralProblems with codememberchmodlf2 Sep '09 - 13:00 
I am using VS 2008/Framework 3.5. In the following code it is erroring.
 
Dim w3svc As New DirectoryEntry(AppPoolFullPath)
w3svc.Invoke("Recycle", Nothing)
 
It does not like directoryentry. It should be part of the system.directoryservices class. However when I look on MSDN it says that system.directoryservices.directoryentry with invoke method exists.
 
I have added the following to my web.config
<add namespace="System.DirectoryServices"/>
<add namespace="System.Management"/>
<add namespace="System.XML"/>
 
This is a bit confusing. Any help would be appreciated.
GeneralRe: Problems with codememberAlberto Venditti2 Sep '09 - 21:53 
You're absolutely right: we are using a valid method of the correct class (see: http://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentry.invoke(VS.80).aspx[^]).
Are you sure you're not getting the error because of too low privileges associated to the process actually executing the Invoke (and - then - the Recycle)?
 
AV
Generaliis 7.0memberesrah26 Feb '09 - 23:55 
is it different to invoke recycling in iis 7.0 or same as the 6.0
GeneralRe: iis 7.0memberAlberto Venditti27 Feb '09 - 0:39 
Hi.
Unfortunately, I have not yet run tests on IIS 7.0. Hopefully its behavior is backward compatible...
AV
GeneralRe: iis 7.0memberesrah27 Feb '09 - 0:41 
when i used this code i get "access denied"...error message ????

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 27 May 2008
Article Copyright 2008 by Alberto Venditti
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid