Tag Archives: Iis

IIS Security – Past and Present

This topic has been covered many times both by Microsoft and non-Microsoft employees. However, I’ve recently been asked what the main features of IIS 7 are and have seen a great deal of misinformation about IIS security on twitter, blog posts and forums.

I think, therefore, the issue deserves yet another look. In this post, I’m going to go over security in the past for IIS and then move on to talk about security features in IIS 7. These are not in any particular order. This post is not meant to diminish the many thoughtful works already created by others – both complimentary and critical. This is just meant to bring the subject back up for discussion again in hopes that you can be properly equipped with the decision making information you may need.

Ghosts of IIS Security Past

The reason for so much misinformation about the current state of security in IIS is likely due to the earned reputation the product had in versions previous to IIS 6.0. A quick search on the web for IIS 5 security vulnerabilities may be like a walk down memory lane for some of the more veteran administrators and IT staff across the globe. The search results are littered with critical vulnerabilities related to buffer overflows, ISAPI extensions, exploits on rarely-used features, or features that were available by a default installation. We are haunted by names like “Code Red” and “Nimda”. I don’t know about you, but those very names send shivers down my spine. I was consulting as a developer and web administrator for a very large property management company when these hit. We were lucky enough to avoid these as we had patched our services. That said, many whom I did business with on a regular basis were not very happy. So, to be clear, I feel the misinformation that is spread today is built on an element of experience with previous versions. Secunia reports 16 advisories and 6 vulnerabilities with IIS 5.  And so started the reputation , perhaps deservedly so, that IIS was not secure unless you really knew what you were doing with security.

Bill Gates was apparently visited by the ghosts of security past, present and future when he laid his head on his pillow January 14th, 2002. I say that because on January 15th, 2002 Mr. Gates sent out the now-famous trustworthy computing memo to every employee at Microsoft.  This set off a major revamp of products from the ground up. Standards were set for test planning and testing. Writing Secure Code was mandatory reading for every Microsoft developer and tester. The results have been staggering.

Security drastically improved in Microsoft products over the years, and IIS was definitely no exception to this. IIS 6 saw 5 security advisories and 4 vulnerabilities reported since 2003. Not to get ahead of myself, but IIS 7 has exactly 1 advisor and 1 vulnerability from Secunia. Compare this against Apache 2.0.x which has had 39 advisories and 23 vulnerabilities (4 of which are still unpatched as of this writing) and Apache 2.2.x which has had 10 advisories and 16 vulnerabilities (2 of which are still unpatched as of this writing) in the same period.  Now I have seen attempts ([1], [2]) to quantify or otherwise explain these numbers further. You can read those articles for yourself and determine how much weight you want to give them. However you skew it, the facts should speak for themselves – IIS has dramatically improved and taken a leadership roll in security in IIS 6 and 7. Our ghost of IIS past still haunts the product’s reputation today, despite obvious strides taken. Even if you feel you like Apache better I think it is only fair to give credit where it is due.

Improvements in IIS 6

The IIS team took the four tenants of Microsoft’s Trustworthy Computing initiative to heart: Secure by Design, Secure by Default, Secure in Deployment and Secure Communication. Since we are already on the next version, I won’t spend a great deal of time talking about the security improvements in the last version other than a brief overview so you know how they relate to changes in our current version, IIS 7.

IIS 6 took vast strides to improve security. During upgrade installations, IIS 6 was disabled by default if the previous server had not been secured by the IIS lockdown tool. The architecture was completely revamped to separate kernel-mode HTTP listening from user-mode application execution. Changes were made to application pools, authentication, access control, encryption and certificate handling, auditing, logging and patch management that made the product far superior to its predecessors. You can find a detailed list of these features on TechNet.  SecurityFocus did a comparison of these features in March of 2004.Server Watch wrote an article in December of 2003. By most accounts, everything accomplished in IIS 6 was a huge step in the right direction.

Despite the massive steps already taken in IIS6, IIS 7 took these all a bit further. Let’s go ahead and investigate these now.

Improvements in IIS 7.x

Customizable Installation

Continuing with the tenant of being secure in deployment, IIS 7 has made installation a wonder to behold. In IIS 6, you could reduce your attack surface by disabling features native to web server. However, these features were still loaded into the process. This carried not only a security factor, but also a performance and memory footprint issue.  IIS 7 has a completely modular architecture. That means that features which you do not want are not only NOT loaded into the process, you can leave the bits for those features off of your disk completely.

Limitable Attack Surface

This is a bit dubious and is essentially part of the customizable installation. By reducing the modules that are available on disk or loaded into a process, you significantly reduce the attack surface for your specialized web servers. If all you intend to do is serve static content with caching and no default documents, you can simply install the static file handler and caching module and leave the rest of the IIS modules off of your server. Additional controls and limitations will also reduce your attack surface and I’ll cover those below.

IUSR account

Anyone who has tried to migrate an IIS installation from one machine to another or attempted to recover your installation on a new machine, previous to IIS 7, has likely run into an issue with the local “IUSR_” account.  IIS 7 now uses a built-in IUSR account that allows you to easily copy your security settings from one machine to the next. This is great news for those using distributed configuration in web farms, recovery, restoration, or replication.


IIS 6 introduced the IIS_WPG group. Application pool security identities had to be assigned to this group in order to host the w3wp.exe process. Like the IUSR account, IIS 7 now creates a built-in security group (IIS_IUSRS) and assigns application pool identities to the group automatically. You can find more information about the built-in user and built-in group for IIS 7 on IIS.NET (Understanding the Built-In User and Group Accounts in IIS 7.0).

ASP.NET / IIS Unified Security Architecture

Previous versions of IIS did not provide a unified approach to security with ASP.NET. The IIS 7 unified request pipeline that supports both Windows and non-Windows principals and provides one place to do all authentication and authorization. Apart from simplification and performance improvements, this also reduces the attack surface and allows for greater flexibility in authentication / authorization scenarios with custom modules.

Request Filtering / URL Rewriting

IIS 7.0 includes a request filtering module that is based on the URLScan ISAPI Filter for IIS 6.0. The module helps you tighten security of your Web servers.

The IIS team has also released an add-on URL rewrite module for IIS 7.0, which provides functionality for rule-based URL manipulation. Even though the primary purpose of the URL rewrite module is to rewrite URL paths for requests, the rewrite module can also be used as a security enforcement tool that helps prevent access to Web site content.

Application Pool Identities

On top of Application Pool Isolation, IIS introduces a new security feature in Service Pack 2 of Windows Server 2008 and Windows Vista. It’s called Application Pool Identities. Application Pool Identities allows you to run Application Pools under an unique account without having to create and manage domain or local accounts. The name of the Application Pool account corresponds to the name of the Application Pool.

Kernel mode SSL

The implementation of SSL has changed from IIS 6.0 to IIS 7.0.  On Windows Server 2003, all SSL configuration was stored in the IIS metabase and encryption/decryption happened in user mode (required a lot of kernel/user mode transitions).  On Windows Vista and Windows Server® 2008, HTTP.sys handles SSL encryption/decryption in kernel mode, resulting in up to 20% better performance for secure connections. 

Configuration Improvements

IIS 7.0 allows locking and unlocking configuration settings in various levels and scopes. Locking down configuration means that it cannot be overridden (or set at all) at lower levels in the hierarchy. Unlocking configuration can only be done at the level where it was locked. This is useful, for example, when creating different configuration for different sites or paths, and only some of sites and paths are allowed to override it. Locking can be done at the section level or for specific elements, attributes, collection elements and collection directives within sections.

Dynamic IP Restriction

IIS 7 provides a new module that allows dynamic, temporary IP address restriction. This module prevents brute force attacks and HTTP clients that make unusually high number of concurrent requests or a large number of requests over a short period of time.


A verbose list of security features in IIS 6 and IIS 7 might be nearly impossible. Apart from the obvious features, there were numerous improvements to code made over these two versions that make the product far more secure than IIS 5 and earlier. That said, this should give you a summary start on information. I’ve listed some reference documents that may help you understand these features better.  In general, I would encourage you to ask questions of the product team and or other users on the IIS.NET forums if you hear something that sounds negative regarding IIS. If the feedback is true, the product team has the benefit of improving the next release. If the feedback is unfounded, the product team has the benefit of helping you find the information you need to make an informed decision.

See Also

Installing CakePHP on IIS 7

Recently I spoke with someone on Twitter who was having issues running CakePHP on IIS. With all the talk about ASP.NET MVC on IIS, folks forget that the MVC pattern works in other languages as well. CakePHP provides MVC  development on PHP. That said, I wanted to dive in and see what the issues were involved in getting this project up and running on IIS 7. I managed to get it installed pretty quickly, but it does take a little tweaking to get you up and running. I’ve chronicled my adventures with CakePHP below in case anyone else is having issues. That said, I must first say that I am not an expert working with CakePHP. This was my first experience with the project, so this information is provided “as-is” and should be taken with a grain of salt. With this demo, I’ll be walking through the “Cake Blog Tutorial” offered on cakephp.org, and modifying it as needed to work with IIS 7. That said, let’s get started.


Yes, there ARE a lot of Prerequisites, but these are pretty typical for any MVC app on any platform.

Assumptions / Conventions

For the purposes of this post, I will use the convention/assumption that you have unzipped CakePHP to c:inetpubCakePHP . You should have the following paths now:

  • c:inetpubCakePHP
    • app
    • cake
    • vendors
    • .htaccess
    • index.php
    • version.txt

I will also use the assumption that this is being installed on the “Default Web Site”. This is unlikely what you are doing, so you’ll want to replace the “Default Web Site” instances in the steps below with your site or application path.

Lastly, I will assume that you are using and have already installed MySQL. You may use another database if you please, but this blog will reference MySQL.

Installing the Blog Sample

Pointing IIS to the cake document root

First, you’ll need to configure your website to point to the correct location. Using the assumptions above, the correct location would be c:inetpubCakePHPappwebroot .

Creating a Blog Database

Second, configure your database connection. To do this, you’ll need to create a blog database, and then point your configuration to that new catalog.

Start by creating a new MySQL Catalog using your favorite tool. I used MySQL Administrator. Simply right click in the catalogs and click “create new schema.”

Create a schema named “CakeBlog”. Once the schema is created, click on the “Tools” menu and select “MySQL Query Browser” and execute the following script:

/* First, create our posts table: */
     title VARCHAR(50),
     body TEXT,

/* Then insert some posts for testing: */
INSERT INTO posts (title,body,created)
      VALUES ('The title',
                  'This is the post body.', NOW());
INSERT INTO posts (title,body,created)
      VALUES ('A title once again',
                  'And the post body follows.', NOW());
INSERT INTO posts (title,body,created)
      VALUES ('Title strikes back',
                  'This is really exciting! Not.', NOW());

* This SQL code copied verbatim from tutorial found here:

You’ve now created your database and a blog posts table with some default posts. Time to configure CakePHP to read from the database:

Cake Database Configuration

We’ll need to let CakePHP know where the database is. Copy database.php.default in c:inetpubCakePHPappconfig to database.php

Open c:inetpubcakephpappconfigdatabase.php and change the $default variable to point to your database:

var $default = array( 'driver'    => 'mysql',
                      'connect'   => 'mysql_connect',
                      'host'      => 'localhost',
                      'login'     => 'CakeBlog',
                      'password'  => 'c4ke-1z-k00l',
                      'database'  => 'CakeBlog',
                      'prefix'    => '' );

* This PHP code copied nearly verbatim from tutorial found here:

You should now be able to open your browser to your application and see the default cake configuration page.

Setting up Rewriting Rules

CakePHP uses mod_rewrite, but also provides the ability to use Cake’s built-in ‘pretty URLs’. We’ll be importing the mod_rewrite rules from the .htaccess files from the default cakephp installation into the IIS URL Rewrite module. We’ll then have to modify those rules.

Start this process by opening the IIS Management Console. Open your application path. In this instance, we are using “Default Web Site”.

  1. Click on the “Default Web Site
  2. Open the “URL Rewrite” module
  3. Click on “Import Rules…” in the Actions pane
  4. Click the “” button next to the “Configuration file” textbox.
  5. Select the c:inetpubcakephp.htaccess file and click “OK
  6. Click the “Import” button
  7. Click the “Apply” button in the “Actions” pane
  8. Repeat steps 4, 5, 6 and 7 for c:inetpubcakephpapp.htaccess and c:inetpubcakephpappwebroot.htaccess files.

The rules are imported, but now you’ll need to edit the rules.

  1. Click the “Back to Rules” button in the “Actions” pane
  2. Edit the two rules with the action starting with “webroot/
  3. Remove the “webroot” portion of the “Rewrite URL”. Your paths should now look as follows:

Creating your MVC Application

The remainder of your application setup should follow the steps found in the original “Cake Blog Tutorial”. There is nothing different between IIS and Apache at this point, so copying the steps would be a bit redundant. Start with the step named “Create a Post Model”. Much like ASP.NET MVC, Cake provides an MVC pattern for developing PHP applications.

Once you have completed the steps, you should have a default site that looks something like the following:


Installing CakePHP on IIS is actually not much different from installing on Apache. The main difference lies in the implementation of mod_rewrite on Apache vs URL Rewriter in IIS. Obviously the installation of PHP differs from Apache. IIS makes the installation of PHP simple with Web Application Installer. If you are using CakePHP on IIS, I would be interested to hear if your experience was different than mine.

A matter of pixels

I’ve been sick a lot lately. In fact, in my entirely life, I don’t ever remember being this sick for this long. It’s been weeks with the same cold – months if you consider the on-again/off-again problems I’ve been having. I guess it could be my fault. I’ve never been a big fan of drugs or doctors.

During my sick time, I try to do some work and often find myself barely able to concentrate. You know how it is, your head feels like its floating, and then you cough or sneeze and you feel as though your body has shaken apart into a million pieces. I’ve always equated that feeling with the visualization of my head becoming pixilated or snowy. That brings me, ever so strangely, to my current topic.

It’s been years since I focused on the front of web development issues. Back in the late 1990’s and early 2000’s I tinkered with client-side web development a great deal. I was writing “Ajax” applications before they were known as that. Of course, they all ran on intranet sites for my clients because they would only work in IE. I learned something back then. It was all a matter of pixels. In many cases, you had to take a box model and calculate precisely where things were and how they should line up. Of course, back then I was still using tables for layouts and cutting up images into manageable slices to put in individual or spanned table cells. Making those images line up, then, was extremely important to work on all browsers.

Over the years, I drifted away from client-side development. I have been concentrating on the back end of the web development stack. IIS, Apache, SQL Server, MySQL, MSMQ, MQ Series, BizTalk, WF, Remoting=>WCF, and associated technologies have been where I spent my time. What happened with data once my server pieces were done was beyond me. As a 3-year veteran working with IIS at Microsoft, you can see why this is important to me. That said, to help make IIS a better web server, it is always useful to actually know what is being served by your webserver, and why it may be important to you. I started playing with ASP.NET MVC which of course means I had to look at the “View” side of things again. To get a better grip on ASP.NET MVC, I decided to implement my blog in Oxite. Oxite isn’t a product, its a technology sample that is being followed to its logical conclusion – full implementation. This project fills the void of most samples by truly evangelizing the technology in a real-world implementation that can (and should) be implemented by others. Many of the samples out there are great examples of how to start an app, but never demonstrate that you can fully implement your project in the technology.

So, as I decided to dive in again and start playing with client-side development, I realized quickly that I needed to relearn everything I once knew. Box models were still important, but so was understanding the nuances of where my pixels within the context of their containers. Unlike with tables, that are fairly predictable, I learned very quickly that CSS-based DIV layouts can break down quickly if you aren’t using the proper attributes in your styles. div wrapping, overflow, z-indexes, display styles all became important topics for me to learn. I was trying to learn All this while I was laying sick in my bed!

I must say that I’m hooked now. I love technologies like jQuery. I’ve written a few plug-ins already. Some of them you see on this site, others will be on my site soon. Some will be coming in next revisions and available for download from this site. You can get the twitter client plug-in that scrolls at the top of this site’s page by downloading the Oxite skin on this website. I love that the community has developed many resources such as Yahoo’s CSS reset and associated style sheets.

Don’t get me wrong, I’m not an expert in these technologies overnight. I’ve got a LOT to learn. But I just keep telling myself, its all a matter of pixels. Count them out and everything will turn out ok!

Some resources for your own journey in client-side design/development:

  • jQuery – jQuery is a technology rooted in Microsoft’s leading XmlHttpRequest object. jQuery native core allows you to assign behavior to elements of the document object, perform common tasks such as layout, animations, fades and much more. This site’s plug-in repository is worth checking out and scouring for examples.
  • jQueryUI – If you like jQuery, this framework of UI plug-ins will help you get a clean, professional look for any website. The site allows you to create a customized theme, download it, and apply it to your layout. Absolutely brilliant.
  • YUI – Yahoo User Interface Library provides many user interface modules. I highly recommend the reset CSS. It helps all browser get on the same footing as far as padding, margin, borders, and spacing go. Very useful tool to help you achieve your desired look/feel on all browsers.
  • The Ajaxian – Great blog with useful information about developing dynamic content on the client side.
  • Introducing JSON – A good starting spot to learn about JSON (JavaScript Object Notation) and associated extensions such as JSONP. JSON allows you to serialize objects across Ajax requests. jQuery provides support for JSON/JSONP.
  • Microsoft: Introduction to JSON in JavaScript and .NET – Useful information to further your understanding of JSON.
  • HTML 5 Draft Recommendation – It always helps to know where your rendering specification is heading. HTML 5 supports things such as canvases that can render objects of irregular shapes and even manipulate individual pixels.
  • Common layouts – This useful site provides the code needed to produce common layouts in fixed and fluid mode.
  • Firebug – This tool is useful if you need to inspect a website’s output and determine what isn’t working. Often times it is hard to tell what setting is making our layout go wildly wrong. Firebug allows you to view the aggregate of your CSS calls for a given element, and let you see where your settings are coming from. The tool is invaluable to any client-side developer.
  • FireUnit – Provides JavaScript debugging. This is a necessary tool for anyone developing modern, dynamic, and interactive web UI today.
  • Color Schemer – This site provides a great tool to create color pallets for your site.


There is so much more to look at that I’m leaving out here. Obviously I could make the list extremely long. However, emphasizing everything means I am emphasizing nothing. I suggest those sites above as a good starting point.

Happy Coding!

Accessing Custom IIS 7 Configuration at Runtime

I’ve been working on a series of posts and Webcasts in my “spare time” directed at some of the areas in which I am most frequently asked questions. I am currently working on developing topics dealing with IIS configuration. It seems logical that this would bring me a great deal of questions considering that IIS 7.0 is using a completely different configuration system than it did in previous versions. That said, I wanted to follow up to my Webcast (“Extending IIS Configuration“) with an article, and another webcast dealing with accessing custom configuration data at runtime.

In the webcast, I described how to extend an existing IIS configuration system object. I want to talk a little more about that. In this blog post I will take on four topics:

  1. Give you some warnings that were not provided in the Webcast regarding extending native IIS configuration
  2. Show you how to access your extended configuration data at runtime in a managed-code HTTP module
  3. Describe how to improve the example used in the Webcast in a custom configuration section.
  4. Show you how to access your custom configuration section at runtime in a managed-code HTTP module

Extending Native Configuration Elements


I talked with Carlos today to discuss the validity of extending native configuration elements for our own purposes. While there are certainly valid reasons to do this, it doesn’t come without a risk to your application. Any time that you modify a piece of data that was created by another party — Microsoft or otherwise — you run the risk of having your data overwritten or corrupting the data that the other party needs to use. That said, lets revisit the sample that is frequently given in many articles and was reused in my webcast.


In our Webcast, we discussed the idea that you could extend a native configuration element simply by creating a new configuration element schema and placing it in our %windir%sytem32inetsrvconfigschema directory. For our example, we created a file named SiteOwner_schema.xml and put the following code into it:

<sectionSchema name=”system.applicationHost/sites”>
<attribute name=”ownerName” type=”string”/>
attribute name=”ownerEmail” type=”string”/>
attribute name=”ownerPhone” type=”string”/>    

All we have done is matched the same section schema path as the existing “system.applicationHost/sites” sectionSchema element in our IIS_schema.xml file. We then added schema information for our three new attributes.

This simple step allows us to immediately start adding attributes to our site configuration, and to access that data programmatically, through PowerShell, and through the AppCmd utility. However, you should be aware of a few dangers before you do something of this nature.

The first problem is that many of our native configuration elements have associated “default” configuration elements. For instance, the <site/> element has an associated <siteDefaults/> element. When modifying the configuration schema for <site/> , you should also modify the <siteDefaults/> configuration schema to match. That said, you might consider changing the above sample configuration schema as follows:

<sectionSchema name=”system.applicationHost/sites”>
<attribute name=”ownerName” type=”string”/>
attribute name=”ownerEmail” type=”string”/>
attribute name=”ownerPhone” type=”string”/>
    <element name=”siteDefaults”>       
<attribute name=”ownerName” defaultValue=”undefined” type=”string”/>
attribute name=”ownerEmail” defaultValue=”undefined”  type
attribute name=”ownerPhone” defaultValue=”undefined” type=”string”/>    

As you can see, in the bolded section above we have now modified the <siteDefaults/> configuration element to match our changes to the <site/> element.  This isn’t the end of the story, however. While changing this might have seemed simple, modifying other elements become much more complex. Consider the fact that when you modify the schema for <application/> elements, there are several places where <applicationDefaults/> are kept. You will find <applicationDefaults/> under both the sites collection definition, as well as under the associated a site element definition. If you modify the application schema definition, you must be sure to edit the schema for both of the applicationDefaults definitions. This gets even more complex if you try to modify the <virtualDirectoryDefaults/> definition. You’ll find that defined three times in the native configuration: under the sites collection definition, under the application element definition, and under the site element definition itself.

You can see how you can quickly start adding complexity to your changes. Making sure that you make changes everywhere you need to becomes all the more risky.

The second problem you may have is that you may not be able to rely on your third-party to keep their schema definition in line with your own expectations. From one minor revision to the next, a configuration schema you may be depending on can change before your very eyes. This becomes a huge issue. Your future installation may need to make many dependency and version checks to decide what schema document to install, and your module may even need to make checks in case the user upgrades the third-party component without installing the upgraded schema. This can get very tricky, to say the least.

The third problem we can run into when we take a dependency on existing configuration is that external code may not behave the way we want it to. For instance, there is no guarantee that utilities and code written to handle those elements will know what to do if it encounters data that it doesn’t expect. Sure, we can cause IIS to validate our changes through schema, but there is no guarantee that the components which handle those elements can take on the challenge of handling the existing data. There is even a good chance that you could cause an Access Violation (read: crash) if the data is not handled properly. There is also a good chance that the components which normally handle those elements may overwrite your custom data.

So before we go on to show you how to access this extended configuration element data, please be warned that it may not be the best solution to your problem. Later in this article, I will describe how to modify our example to give us the same functionality without altering the schema definition of the existing elements.

Accessing Extended Native Configuration Elements at Runtime


With the warnings having been fairly posted, I’ll show you quickly how to access your custom configuration data at runtime from an HTTP module. Once you have saved your schema file to the appropriate directory, its time to write the HTTP module. That module is going to be very simple. We need to create a module that uses the PreSendRequestHeaders event. In this event we will get our “system.applicationHost/sites” configuration section, loop through the configured sites looking for the site on which the current HTTP request is executing, and then write HTTP headers out to the client. Just to make sure that our sample is working, we’ll wrap it up by adding JavaScript to an HTML page that will request the headers from the Web site and display them in a message box.

Getting Started

For this sample, I used Visual Studio 2008, but you can use plain old notepad and command-line compilation if your are feeling particularly froggy.

Visual Studio 2008 Walk-through

The following walk-through will create an HTTP module that can display the site owner details of the configuration system

  1. Click on the File | New | Project …  menu item.
  2. In the “Project types” tree on the left, drill down to the C# | Windows tree element
  3. In the “Templates” selector on the right, select the “Class Library” template
  4. Change the Name of the project to “SiteOwner
  5. Change the Location to “c:samples”
  6. Verify that the “Create directory for solution” checkbox is checked
  7. Click OK
  8. Click on the Project | Add Reference … menu item.
  9. Under the .NET tab, select the component with the Component Name of “System.Web
  10. Click OK
  11. Rename the “Class1.cs” file in the Solution Explorer to “SiteOwnerHeaderModule.cs
  12. Paste the following code in “SiteOwnerHeaderModule.cs” file:
    using System;
    using System.Web;
    using System.Web.Hosting;
    using Microsoft.Web.Administration;
    using System.Collections.Specialized;

    namespace SiteOwner
    public class SiteOwnerHeaderModule : IHttpModule {
    public void Dispose() {}
    public void Init(HttpApplication context) {
    context.PreSendRequestHeaders += new EventHandler(OnPreSendRequestHeaders);
    void OnPreSendRequestHeaders(object sender, EventArgs e){
                // Get the site collection

    ConfigurationSection section =
    ConfigurationElementCollection cfgSites = section.GetCollection();
                HttpApplication app = (HttpApplication)sender;
                HttpContext context = app.Context;
                // Loop through the sites to find the site of 
                // the currently executing request
    foreach (ConfigurationElement cfgSite in cfgSites) {
    if (HostingEnvironment.SiteName == (string)cfgSite.GetAttributeValue(“name”)) {
                        // This is the correct site, get the site owner attributes
    SiteOwner siteOwner = new SiteOwner(cfgSite);
    NameValueCollection headers = context.Response.Headers;
    headers.Add(“Site-Owner-Name”, siteOwner.Name);
    headers.Add(“Site-Owner-Email”, siteOwner.Email);
    headers.Add(“Site-Owner-Phone”, siteOwner.Phone);
    class SiteOwner {
    public string Name { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public SiteOwner(ConfigurationElement site) {
    this.Name = site.GetAttributeValue(“ownerName”) as string ;
    this.Email = site.GetAttributeValue(“ownerEmail”) as string ;
    this.Phone = site.GetAttributeValue(“ownerPhone”) as string;

  13. Click the File | Save menu item.
  14. Right-click the SiteOwner project in the Solution Explorer window and select Properties from the menu
  15. Click the Signing tab
  16. Check the Sign the assembly checkbox
  17. Select “<new>” from the Choose a strong name key file dropdown box
  18. Type “KeyFile” in the Key file name box
  19. Uncheck the checkbox labeled Protect my key file with a password
  20. Click OK
  21. Click the File | Save SiteOwner menu item
  22. Click the Build | Build SiteOwner menu item.

Notepad.exe and Command-line Walk-through

The following walk-through will create an HTTP module that can display the site owner details of the configuration system. This walk-through assumes that you have the Microosft .NET Framework SDK or Windows SDK installed. These include the C# compilers needed to build. For more help on building with csc.exe, see “Command-line building With csc.exe

  1. Paste the code from step 10 of the Visual Studio .NET 2008 walk-through into a new notepad instance
  2. Click File | Save As
  3. Browse to the “C:samples” folder if it exists; create the folder if it does not
  4. Type “SiteOwnerHeaderModule.cs” in the File name box
  5. Click the Save button
  6. Open a new SDK Command Prompt (Windows SDK) or Visual Studio Command Prompt (Visual Studio 2008).
  7. At the command prompt type:
    csc.exe /target:module /out:SiteOwner.netmodule /debug /r:System.Web.dll /r:%windir%system32inetsrvMicrosoft.Web.Administration.dll SiteOwnerHeaderModule.cs
  8. Press ENTER then type:
    sn.exe -k keyfile.snk
  9. Press ENTER then type:
    al.exe /out:SiteOwner.dll SiteOwner.netmodule /keyfile:keyfile.snk

Deploying Your HTTP Module

Once you have built your assembly using either Visual Studio 2008 or csc.exe, its time to deploy it to your system. This sample assumes that you don’t want all of your customers to have to install this same component to each Web site, so we’ll install it as a default module on the system.

Registering the Assembly in the GAC

To do this we first need to copy the assembly file(s) to the target system, and register them in the Global Assembly Cache. Using your preferred method to copy the files, copy the SiteOwner.dll (and SiteOwner.netmodule if you used command-line compilation) to the %windir%system32inetsrv directory on the target installation machine. Next open up a command prompt and type:

gacutil -i %windir%system32InetSrvSiteOwner.dll

Now you’ll need to get a copy of the “Public Key Token” for the assembly so that you can install this “strong-named assembly” module in IIS. To do this open up your %windir%assembly directory in Windows Explorer. Scroll down to the SiteOwner “file” in that window and copy the “Public Key Token”. You can do this easily by right-clicking the “file” and selecting Properties from the menu. Double click on the Public Key Token to select the entire contents, then right click the highlighted text and select Copy from the menu.


Installing the Module as a Default Module in IIS 7.0

Now that you have your assembly registered and your Public Key Token copied, its time to add this module to all the Web sites on your IIS 7.0 server. To accomplish this, open up your %windir%system32inetsrvconfigapplicationHost.config file in notepad. Scroll down near the bottom of the file to the default location path that looks something like this:

<location path=”” overrideMode=”Allow”>

Inside of that element scroll down to the <modules> element under the <system.webServer> section. You should find a number of modules already listed. To add yours, simply scroll to the bottom of the list and type the following:

<add name=”SiteOwner” type=”SiteOwner.SiteOwnerHeaderModule, SiteOwner, Version=, Culture=neutral, PublicKeyToken=” />

Once you have typed this line in, you can paste your Public Key Token in right after “PublicKeyToken=” in the line you just typed. Save the applicationHost.config file.

Testing the Module

Choose a Web site on your server to test your application. If you want to run this module for files other than ASP.NET files, you’ll need to choose a Web site running in Integrated Pipeline. For our sample, we are going to make an HTML file to test our code. Our HTML file will contain some JavaScript that will get the headers from the server and display them in a message box. We could use a number of diagnostic tools to do this same work, but this will serve our purposes.

Open up Notepad and paste the following markup into it:

<script language=”JavaScript” type=”text/javascript”>
var req = new ActiveXObject(‘Microsoft.XMLHTTP’);
req.open(‘HEAD’, location.href, false);

Save the file to the physical root of the Web site you wish to test. Type in the corresponding URL to your test file in your web browser. Your result should be a JavaScript alert that looks something like the following:


You’ll notice in my results, I have already set the Site’s ownerName attribute. (see the Webcast titled “Extending IIS Configuration” to see how).

Improving our Sample


As I stated earlier in this post, this demonstrates something that is definitely possible, but somewhat risky to do. We now want to improve our sample to limit our dependencies on native and/or third-party configuration schema definitions, and prevent us from encroaching on another module’s configuration territory. In concept, what we will do is move our configuration data to its own configuration section and use the site’s ID to allow us to map the data from the site collection to our configuration section.

Modifying the Schema

First, you’ll want to remove the custom site owner configuration data from the site nodes. Otherwise, once we modify the schema, the configuration will not validate. Once you’ve removed that data open the SiteOwner_schema.xml file in notepad and change it to the following:

<sectionSchema name=”system.applicationHost/siteOwner”> 
<collection addElement=”site”> 
<attribute name=”id” type=”uint” required=”true” isUniqueKey=”true” />
attribute name=”ownerName” type=”string” /> 
attribute name=”ownerEmail” type=”string” /> 
attribute name=”ownerPhone” type=”string” /> 

Save the file in the same location as you did previously. Now we need to tell the applicationHost.config file about our new section schema. To do this, we add a new section declaration underneath of the system.applicationHost sectionGroup in the applicationHost.config file.

<sectionGroup name=”system.applicationHost”>
    <section name=”siteOwner” allowDefinition=”AppHostOnly” overrideModeDefault=”Deny” />

Next we need to modify our HTTP module to read from the new configuration section:

using System;
using System.Web;
using System.Web.Hosting;
using Microsoft.Web.Administration;
using System.Collections.Specialized;

namespace SiteOwner{
public class SiteOwnerHeaderModule : IHttpModule{
public void Dispose() { }
public void Init(HttpApplication context){
+= new EventHandler(OnPreSendRequestHeaders);
void OnPreSendRequestHeaders(object sender, EventArgs e){
// Get the site collection
            ConfigurationSection section = 
ConfigurationElementCollection cfgSites = section.GetCollection(); 
            HttpApplication app = (HttpApplication)sender;
            HttpContext context = app.Context;

// Loop through the sites to find the site of 
            // the currently executing request
            foreach (ConfigurationElement cfgSite in cfgSites){
                if (HostingEnvironment.SiteName == (string)cfgSite.GetAttributeValue(“name”)){
// This is the correct site, find the associated
                    // Site Owner record in our custom config section
                    SiteOwner siteOwner = SiteOwner.Find((long)cfgSite.GetAttributeValue(“id”));
if (siteOwner != null) {
// Add the headers if we found a matching
                        // site owner record configured
                        NameValueCollection headers = context.Response.Headers;
headers.Add(“Site-Owner-Name”, siteOwner.Name);
headers.Add(“Site-Owner-Email”, siteOwner.Email);
headers.Add(“Site-Owner-Phone”, siteOwner.Phone);
class SiteOwner{
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public SiteOwner(ConfigurationElement owner){
this.Name = owner.GetAttributeValue(“ownerName”) as string;
this.Email = owner.GetAttributeValue(“ownerEmail”) as string;
this.Phone = owner.GetAttributeValue(“ownerPhone”) as string;
public static SiteOwner Find(long siteId){
             // Find the matching siteOwner record for this siteId         
ConfigurationSection section = 
ConfigurationElementCollection cfgSiteOwners = section.GetCollection();
foreach (ConfigurationElement cfgOwner in cfgSiteOwners) {
if (siteId == (long)cfgOwner.GetAttributeValue(“id”)){
return new SiteOwner(cfgOwner);
return null;


There isn’t much changed in this compared to the last. The difference, apart from a few code comments, is that I’ve modified the OnPreRequestHeaders function to get the current site ID, and pass that into the static SiteOwner.Find function. Then I modified the SiteOwner.Find function to read from our new configuration section. Please note that production code would likely set SiteOwner to extend from ConfigurationElement, and a special ConfigurationSection would be developed. Go ahead and compile and deploy this assembly the same way you did with the previous version. Make sure that you run gacutil on the new assembly once it is copied. Also, since we are running against a static HTML file, you might need to run iisreset.exe from a command-line in order to clear the cache from the server.

Once you have deployed your assembly and the schema file, its time to test the application. If we refresh our Web page, we will get a JavaScript alert without any site owner headers listed:


This is because we haven’t created any site owner configuration entries yet. So lets add a record directly to our config. I added the following configuration directly after the <sites> node in the applicationHost.config file:

<site id=”1″ ownerName=”Tobin Titus” ownerEmail=”tobint@microsoft.com” ownerPhone=”555-121-2121″ />

Save your file and refresh your Web browser. You should now see your site owner configuration data.



In this blog post, we’ve walked through extending existing IIS configuration objects, and accessing the custom data at runtime through an HTTP module. We’ve also talked about the risks of this approach and have demonstrated a better approach. This approach gives us the same ability to customize our IIS 7.0 configuration system, but gives us a much smaller dependency on the native configuration schema. We have little worry about schema changes, we don’t have to worry about other modules or utilities stomping on our custom data, and most importantly, we are far less likely to cause any Access Violations with the later approach. 

Many thanks go to Carlos once again for his help in putting this post together as well as for his CodeColorizer plug-in for Live Writer. High-fives and cookies in his office!

Reading IIS.NET Blogs (or any RSS) with Powershell

Being a member of the IIS team, I often find myself checking blog posts to see what the members of the product team are blogging about.  However, since Powershell came out, I find myself doing more and more work on my scripts. It’s a bit annoying to have to jump out of Powershell to go read blog posts.  As such, I’ve written a few quick scripts to help me read IIS.NET from my pretty blue shell. For those of you who are already familiar with powershell and don’t want to read the long blog post, you can download my blog script from the DownloadCENTER: http://www.iis.net/downloads/default.aspx?tabid=34&g=6&i=1387 

Setting up your Powershell environment

To start, I’ve written a few supporting functions in my profile.  These functions help me keep my scripts organized and, since I change my scripts quite often, it helps me to sign them as well. 
First off, if you haven’t created your own certificate for signing code, please go back and take a look at my first Powershell blog post that give you the details on how to do this.  
Next, we need to add a few things to your Powershell profile.  To open your Powershell profile from within Powershell, type: 

PS > notepad $profile 
First, I add a function to allow us to easily sign our scripts (assuming you have created a cert to sign them wth): 

## Sign a file
function global:Sign-Script ( [string] $file )
     $cert = @(Get-ChildItem cert:CurrentUserMy -codesigning)[0]
     Set-AuthenticodeSignature $file $cert
set-alias -name sign -value sign-script

The next function is used to help me organize things. I have several scripts for various work environments.  I like to organize them by function. So, I keep my IIS scripts in an “IIS” directory, my common scripts in a “common” directory and so on.  Inside each of my script directories, I keep a “load.ps1” script that I can  use to initialize any of my work environments.  Lastly, I create a Powershell drive that matches the work environment name so I can get to my scripts easily. The function below does all the work for me. 

## Create a Drive
function global:New-Drive([string]$alias)
     $path = (join-path -path $global:profhome -childpath $alias)
     if( !(Test-Path $path ) )
          ## Create the drive's directory if it doesn't exist
          new-item -path $global:profhome -name $alias -type directory
          ## Execute the load script for this drive if one exists
          $loadscript = (join-path -path $path -childpath "load.ps1")
          if( Test-Path $loadscript)
               $load = &$loadscript
     # Create the drive
     new-Psdrive -name $alias -scope global -Psprovider FileSystem -root $path

Within my profile, I simply call this function and pass in an alias. When the function executes it will create a directory with the alias name, if it doesn’t exist already. If the directory does exist, it will check for the load.ps1 file inside that path and execute it. Lastly, it will create powershell drive. I have the following calls added to my profile below: 

## Custom PS Drives
New-Drive -alias "common"
New-Drive -alias "iis"

Go ahead and save your profile now and type these commands: 

PS > Set-ExecutionPolicy Unrestricted
PS > &$profile
PS > Sign $profile
PS > Set-ExecutionPolicy AllSigned

The first command sets Powershell into unrestricted mode. This is because we need to execute the profile script and it hasn’t been signed yet.  The next command executes the profile. The third command uses the “sign” function that our profile script loaded. Since our profile is now signed, we can set our execution policy back to AllSigned. AllSigned means that Powershell will execute scripts as long as they are signed. 

From this point on, we can make changes to our profile and simply call our sign function again before we close our Powershell instance. The next instance of powershell that is opened will have our changes.  

Creating / Using Blog Functionality

Now that we have our environment set up, lets get to the blogging part.  If you’ve set up your environment right, you can execute the following command: 

PS > cd iis: 

This command will put you in the iis scripts directory.  Next, create a new blogs script by typing: 

PS > notepad blogs.ps1 

You’ll be prompted if you want to create the file. Go ahead and say yes.  Next, paste the following into the the notepad and save it: 

## Sets up all custom feeds from feeds.txt
function global:Import-Feed
     if( $global:RssFeeds -eq $null )
          $global:RssFeeds = @{};
     $RssFeeds.Add( "iisblogs", "http://blogs.iis.net/rawmainfeed.aspx" );
     $RssFeeds.Add( "iisdownloads", "http://www.iis.net/DownloadCENTER/all/rss.aspx" );
Import-Feed ## Call Import-Feed so we are ready to go
## Gets a feed or lists available feeds
function global:Get-Feed( [string] $name )
     if( $RssFeeds.ContainsKey( $name ) )
          return $RssFeeds[$name];
          Write-Host "The path requested does not exist";
          Write-Output $RssFeeds;
## Gets IIS Blogs
function global:Get-Blog([int]$index, [int]$last, [int]$first, [int]$open)
     $url = (Get-Feed iisblogs)
     return (Get-RSS $url $index $last $first $open)
## Gets a specific blog
function global:Get-AuthorBlog([string]$creator)
     Get-Blog | Where-Object {$_.creator -eq $creator}
## Gets Downloads from IIS
function global:Get-Download([int]$index, [int]$last, [int]$first, [int]$open)
     $url = (Get-Feed iisdownloads)
     return (Get-RSS $url $index $last $first $open)
## Gets a generic RSS Feed
function global:Get-RSS([string]$url, [int]$index, [int]$last, [int]$first, [int]$open)
     $feed = [/xml](new-object System.Net.WebClient).DownloadString($url)
          return $feed.rss.channel.item[$index]
          $ieaddr = $env:programfiles + "internet exploreriexplore.exe"
          return &(get-item $ieaddr) $feed.rss.channel.item[$open].link
          return ($feed.rss.channel.item | Select -last $last)
          return ($feed.rss.channel.item | Select -first $first)
     return $feed.rss.channel.item

Once you’ve saved this file, close it.  We need to sign this script and execute it by typing: 

PS IIS:> sign blogs.ps1
PS IIS:> ./blogs.ps1 

Now lets start reading.  

  • Read all Blogs
PS iis:> Get-Blog 
  • Read the last five blog posts
PS iis:> Get-Blog -last 5 
  • Read the first five blog posts
PS iis:> Get-Blog -first 5 
  • Read the 8th blog post
PS iis:> Get-Blog -index 8 
  • Open the 12th blog post and open in Internet Explorer
PS iis:> Get-Blog -open 12 
  • Read all blog posts by Bill Staples
PS iis:> Get-AuthorBlog bills 
  • Read all items in DownloadCENTER
PS iis:> Get-Download 
  • Get titles of all items in DownloadCENTER
PS iis:> Get-Download | Select Title 

Of course, all the laws of Powershell still apply, so I can still do fun stuff like like listing only the blog titles from my blog. 

PS iis:> Get-AuthorBlog TobinTitus | Select Title 

I can do the same witht he raw blog output: 

PS iis:> Get-Blog -last 5 | Select pubDate, Creator, Title 

Happy reading. 

IIS.NET Blogs in Powershell

Extending IIS 7 APIs through PowerShell (Part II)

In my previous post, I showed you how easy it was to leverage your knowledge of the IIS 7 managed SDK in Windows PowerShell.  We loaded the IIS 7 managed assemblies and then traversed the object model to display site information and stop application pools.  While this in itself was pretty cool, I don’t think I quite got my point across about how powerful IIS 7 and PowerShell are together. As such, I wanted to show you some more fun things to do with PowerShell in the name of easy IIS 7 administration.

First, our examples still required a great deal of typing and piping and filtering.  Let’s modify our profile script from my previous post by adding at least one new global variable that will give us access to the ServerManager without much typing.  Add the following line to your profile script from my previous post.

new-variable iismgr -value (New-Object Microsoft.Web.Administration.ServerManager) -scope "global"

(if you don’t have a profile script yet, go back to my previous post to learn how to create one).

Note: If you signed your script before, you’ll have to do it again after modifying the script

Open a new instance of PowerShell and now you can access the site collection just by typing:

PS C:> $iismgr.Sites

 That’s considerably smaller than our previous examples.  But let’s not stop there.  What happens if I want to search the site collection? PowerShell has some fun syntax for this as well. I simply pipe the output of my SiteCollection to a “Where-Object” cmdlet and then specify what site I’m looking for:

$iismgr.Sites | Where-Object {$_.Name -match "Default*"}

This is still quite a bit of typing when all I really want to do is find the default website. You may ask “Wouldn’t it be easier if we could just add a “Find” method to the SiteCollection object?” Well I’m glad you asked *cough*! Next, we are going to do just that! Open up another instance of notepad and add the following XML to it:

<?xml version="1.0" encoding="utf-8" ?>
<!-- *******************************************************************
Copyright (c) Microsoft Corporation.  All rights reserved.
******************************************************************** -->
          $rtr = "";
          if ( $args[0] ) 
          { $name = $args[0];
            $rtr = ((New-Object Microsoft.Web.Administration.ServerManager).Sites | 
                     Where-Object {$_.Name -match $name}) 
            $rtr = "No sites found." 

What we’ve done is identified that we want to add a scripted method to the Microsoft.Web.Administration.SiteCollection object. In our case, I’ve added a “Find” method by using the same cmdlet t at we typed before to search the site collection. The difference is, this type I use the $args array variable to check for a parameter and use it if one is available. Now, save this file into your %windir%system32WindowsPowerShellv1.0 directory as “iis.types.ps1xml”. Once you’ve saved the file, sign it the same way you signed your profile script. Keep in mind that these xml files contain code, so signing your xml is required to keep your PowerShell experience a secure one. Now, open your profile script (again) and add the following lines to the end:

new-variable iissites -value (New-Object Microsoft.Web.Administration.ServerManager).Sites -scope "global"
new-variable iisapppools -value (New-Object Microsoft.Web.Administration.ServerManager).ApplicationPools -scope "global"
update-typedata -append (join-path -path $PSHome -childPath "iis.types.ps1xml")

Note: Once again, you’ll have to re-sign this profile if your execution policy requires signed scripts.

Notice that I added two more variables: $iissites and $iisapppools. These variables allow me to access the site collection and application pool collection with a simple keyword. Lets try them out in PowerShell. Make sure you open a new instance of PowerShell so your profile script and xml type data are updated properly. Once your new instance of PowerShell is open, type the following:

PS C:> $iissites.Find("^Default*")

PowerShell will do all the work for you and you have MUCH less typing to do.

Another alternative to using xml files is to simply create a function and add it to your profile. For instance, we can create a function called “findsite” that provides the same functionality as our previous example. Either type the following command into PowerShell or add it to your profile script:

PS C:> function findsite { $name=$args[0]; ((New-Object Microsoft.Web.Administration.ServerManager).Sites | Where-Object {$_.Name -match $name}); } }

Now you can search for a site using the following syntax:

PS C:> findsite default*

Whatever way we choose to extend Microsoft.Web.Administration and/or PowerShell, we can use our output as we did before:

PS C:> (findsite default*).Id

The previous line should display the Id of the default web site. We can also stop the website:

PS C:> (findsite default*).Stop()

We can keep taking this to extremes and truncate every operation that we perform on a semi-regular basis. These scripts are not one-offs. Each script function we create or append to an existing object model can be reused and piped as input to another function. The possibilities are endless and completely customizable to your needs.

Adding performance

Some of you may have found the title to this blog post as amusing as I do. Throughout my career, I’ve been called into many a meeting asking that I “add” performance to a complete or nearly-complete product. No matter how many scowls I got, I could never resist joking about just adding the IPerformance interface. “And, while you are at it, just add the IScalable one too”, I would quip. (OK, I know some of you are doing searches for these interfaces — don’t bother). Laugh as hard as I may, I’m embarrassed to say that I am trying to do this very thing now.

A few weeks ago, I started playing around with a small sample that shows off some of the fun features of IIS 7. As I started coding, I added more features to the sample. Scope creep is a no-no, but this was something I was doing on my own time so I didn’t have a problem with it. However, the sample got so large that I had to actually stop and design a public API to support it. By the time I was done, my “sample” had a set of providers, a common API, localization support, utilities, and most notably, performance issues.

Last year on my personal blog, I talked about “engineering for usability“. In that post, I declared that the simplest design is sometimes (and probably most often) the best approach. That said, performance should have been considered very early on, and the sample should have been kept simple. Performance, as many of you know, is not something you add as an afterthought. Starting my sample the way I did, I never considered code performance to be an issue.

Now I’m forced to decide: do I scale back my sample knowing full well that it doesn’t have a security model or provide easy extensibility, or do I redesign the sample with the current feature set and design for performance up front? I’m leaning toward the latter despite reciting “keep it simple, stupid” in my head over and over again.

Where can I find in IIS 7.0 ?

Question: Where can I find Windows Authentication in IIS 7.0

I’ve seen this question or questions like this asked numerous times so I thought it would make a nice quick — and hopefully useful — blog post.

In previous versions of IIS, administrators were able to enable or disable features on their servers by simply checking or unchecking a box in the IIS management console.  However, when an administrator unchecked a feature in IIS, the feature still existed on the machine and was even loaded.  Unchecking a box allowed the administrator to disable a feature — but it didn’t physically remove anything from the machine.

This all changes with IIS 7.0. Currently, when you install IIS 7.0 on Windows Vista (or Longhorn server for that matter), you must select the features that you want installed. Each feature in IIS 7.0 is componentized into its own module library. The features you select at installation, and ONLY the features you select, will be copied to disk under the “%windir%system32inetsrv” directory. If you do not install the feature, it simply won’t exist on your machine. This obviously makes the server more robust and performant at the sime time — providing a high amount of customization as well as security.

Another thing to note is that once a feature module has been installed to the proper directory, it must also be added to the IIS configuration system. For more information on how to install and uninstall modules, see: Getting Started with Modules.

If you are having a hard time getting WindowsAuthentication, DynamicCompression, or some other feature of IIS to work. A good place to start looking is your installation. Make sure you’ve installed the features you need for your purposes.

Accessing IIS 7 APIs through PowerShell (Part I)

I’ve caught the PowerShell bug. In between stints with my ever-expanding code samples, I play with PowerShell a lot.  I thought I’d share a quick example of how to load Microsoft.Web.Administration.dll and use it to perform some basic tasks.

Note: I’m running these samples on Windows Vista RTM, but I have no reason to believe this will not work on the PowerShell release candidates for the Vista RC* builds that are available now

So let’s get started.

First, PowerShell has no idea where Microsoft.Web.Administration.DLL is so you have to tell it how to load it. Anyone who has written code to dynamically load an assembly should be familiar with this syntax.  Type the following command

PS C:> [System.Reflection.Assembly]::LoadFrom( “C:windowssystem32inetsrvMicrosoft.Web.Administration.dll” )

The path to your assembly may change depending on your install.  I’ll show you later how to use environment variables to calculate the correct path.  In the mean time the out put of the line above display something like the following:

GAC  Version    Location
---  -------    --------
True v2.0.50727 C:WindowsassemblyGAC_MSILMicrosoft.Web.Administration . . .

Once the assembly is loaded you can use PowerShell’s “New-Object” command to create a ServerManager object that is defined in Microsoft.Web.Administration.

PS C:> (New-Object Microsoft.Web.Administration.ServerManager)

This doesn’t give you much except the list of properties the ServerManager exposes:

ApplicationDefaults      : Microsoft.Web.Administration.ApplicationDefaults
ApplicationPoolDefaults  :
ApplicationPools         :
SiteDefaults             : Microsoft.Web.Administration.SiteDefaults
Sites                    : {Default Web Site}
VirtualDirectoryDefaults : Microsoft.Web.Administration.VirtualDirectoryDefaults
WorkerProcesses          : {}

To get more detail, you need to use the properties and methods of the ServerManager object to drill down and get the information we want. The ServerManager provides access to all of the sites on your machine through a SiteCollection object. This SiteCollection is made available through the “Sites” property of the ServerManager. 

PS C:> (New-Object Microsoft.Web.Administration.ServerManager).Sites

Which will produce a list view of all the sites and their associated property names/values.

ApplicationDefaults        : Microsoft.Web.Administration.ApplicationDefaults
Applications               : {DefaultAppPool, Classic .NET AppPool}
Bindings                   : {}
Id                         : 1
Limits                     : Microsoft.Web.Administration.SiteLimits
LogFile                    : Microsoft.Web.Administration.SiteLogFile
Name                       : Default Web Site
ServerAutoStart            : True
State                      : Started
TraceFailedRequestsLogging : Microsoft.Web.Administration.SiteTraceFailedRequestsLogging
VirtualDirectoryDefaults   : Microsoft.Web.Administration.VirtualDirectoryDefaults
ElementTagName             : site
IsLocallyStored            : True
RawAttributes              : {name, id, serverAutoStart}
ApplicationDefaults        : Microsoft.Web.Administration.ApplicationDefaults
Applications               : {DefaultAppPool}
Bindings                   : {}
Id                         : 2
Limits                     : Microsoft.Web.Administration.SiteLimits
LogFile                    : Microsoft.Web.Administration.SiteLogFile
Name                       : Test Web Site 1
ServerAutoStart            : False
State                      : Stopped
TraceFailedRequestsLogging : Microsoft.Web.Administration.SiteTraceFailedRequestsLogging
VirtualDirectoryDefaults   : Microsoft.Web.Administration.VirtualDirectoryDefaults
ElementTagName             : site
IsLocallyStored            : True
RawAttributes              : {name, id, serverAutoStart}

Of course, this isn’t the easiest view to read, so let’s say we just list the site names by piping our site list to the “ForEach-Object” command in PowerShell and display a list of site names only:

 PS C:> (New-Object Microsoft.Web.Administration.ServerManager).Sites | ForEach-Object {$_.Name}

This looks much more concise:

Default Web Site
Test Web Site 1

We could also use the Select-Object syntax to query the list into a table format:

 PS C:> (New-Object Microsoft.Web.Administration.ServerManager).Sites | Select Id, Name
        Id Name
        -- ----
         1 Default Web Site
         2 Test Web Site 1

Now lets use PowerShell to manage application pools. We can fit several commands on one line by using the semi-colon.  The following command-line is actually four different operations: Storing the application pool collection into a variable, displaying the name and runtime status of the first application pool, stopping the first application pool, then displaying the name and status again.

PS C:> $pools=(New-Object Microsoft.Web.Administration.ServerManager).ApplicationPools; $pools.Item(0) | Select Name, State;$pools.Item(0).Stop(); $pools.Item(0) | Select Name, State

Running this sample should display the following:

Name                                         State
----                                         -----
DefaultAppPool                               Started
DefaultAppPool                               Stopped

This is nice, but we can do this already with appcmd.exe right? Well, to some extent.  We don’t get the features of PowerShell that allow us to format our output the data to our liking. Also, as a developer, I find it much easier to use the API syntax I’m already familiar with than to remember appcmd.exe syntax.  Furthermore, PowerShell allows us to use WMI alongside our managed code calls, and unlike appcmd.exe, you can extend PowerShell and cmdlets. PowerShell gives you the ability to easily manage multiple servers from one command prompt on one machine.  Watch the PowerShell/IIS 7 interview on Channel9 if you want to see this remote administration in action.

One last thing that PowerShell brings to the table is the ability to “spot-weld” our object models (as Scott Hanselman quipped). You can create/modify/extend type data and formatting to your hearts desire.  For more information on this, check out the PowerShell documentation found in the PowerShell install, or in the PowerShell documentation set.

So, I would be remiss in this post if I didn’t try to make your PowerShell / IIS 7.0 life easier.  As such, I’ve created a profile script that loads all the IIS 7.0 managed assemblies for you.  The script is simple and contains more  echo commands than actual working script lines.

To install this script run the following command inside PowerShell:

PS C:> if ( test-path $profile ) { echo “Path exists.” } else { new-item -path $profile -itemtype file -force }; notepad $profile

This will create a profile path for you if you don’t already have one, then open up your profile in notepad.  If you haven’t added anything to the file, it will obviously display an empty file.  Paste the following in notepad when it opens:

echo “Microsoft IIS 7.0 Environment Loader”
echo “Copyright (C) 2006 Microsoft Corporation. All rights reserved.”
echo ”  Loading IIS 7.0 Managed Assemblies”

$inetsrvDir = (join-path -path $env:windir -childPath “system32inetsrv”)
Get-ChildItem -Path (join-path -path $inetsrvDir -childPath “Microsoft*.dll”) | ForEach-Object {[System.Reflection.Assembly]::LoadFrom( (join-path -path $inetsrvDir -childPath $_.Name)) }

echo ”  Assemblies loaded.”

Now, save the profile and close notepad.  You will likely have to sign this script or change your script execution policy to something very weak to make this script run properly (obviously I’m not recommending the latter). To find out more about signing scripts, type “get-help about_signing” in PowerShell. The instructions to create a self-signed certificate found in that help file are as follows:

In an SDK Command Prompt window, run the following commands.
The first command creates a local certificate authority for your computer.
The second command generates a personal certificate from the certificate authority:

makecert -n "CN=PowerShell Local Certificate Root" -a sha1 `
   -eku -r -sv root.pvk root.cer `
   -ss Root -sr localMachine
makecert -pe -n "CN=PowerShell User" -ss MY -a sha1 `
   -eku -iv root.pvk -ic root.cer
   MakeCert will prompt you for a private key password.

Go ahead and make a certificate for yourself following those instructions. To sign your profile, within PowerShell type the following:

PS C:>Set-AuthenticodeSignature $profile @(get-childitem cert:CurrentUserMy -codesigning)[0]

So far, you’ve created a certificate and signed your script. Now, you will have to change your script execution policy down at least one level from the default.  The default doesn’t allow scripts at all.  To get scripts to execute, at the minimum you’ll have to set it to “AllSigned” to allow only signed scripts to execute.  In this mode, each time you execute a script from a new publisher, you’ll be asked what level of trust to assign to the publisher (unless you respond to the prompt to “Always Run” or “Never Run” scripts from that publisher)

Do you want to run software from this untrusted publisher?
File C:UsersTobinTDocumentsWindowsPowerShellMicrosoft.PowerShell_profile.ps1 is published by CN=PowerShell User
and is not trusted on your system. Only run scripts from trusted publishers.
[V] Never run  [D] Do not run  [R] Run once  [A] Always run  [?] Help (default is "D"):

Now, each new instance of PowerShell that you run will automatically load the IIS 7.0 managed assemblies.  I know it seems like a great deal of work, but it really isn’t once you’ve made a few rounds around inside PowerShell. Consider that you only have to create the script once and then you have full the full range of the managed IIS 7.0 SDK at your fingertips inside PowerShell. 

If you have problems, feel free to leave comments and I’ll do my best to help you.

Change the runtime of an IIS 7 application pool

The following quick SDK sample demonstrates how to list and change the managed runtime version of application pools programatically in IIS 7.


Imports System
Imports Microsoft.Web.Administration
Public Class AppPoolSample
 Shared manager As ServerManager = New ServerManager()
  ' Main application processing
  Public Shared Sub Main(ByVal args As String())
      ' Get the apppool to change
      Dim iPool As Integer = GetAppPool()
      ' Get the framework version desired
      Dim rtVersion As String = GetVersion()
      ' Set the apppool runtime
      Dim poolToSet As ApplicationPool = manager.ApplicationPools(iPool)
            "Setting application pool '{0}' to runtime version: {1}...", _
            poolToSet.Name, rtVersion)
      poolToSet.ManagedRuntimeVersion = rtVersion
      ' Commit the changes and recycle the application pool
      Console.WriteLine("Your changes have been committed.")
  End Sub

  ' Prompts the user to select an application pool
  Public Shared Function GetAppPool() As Integer
    Dim pool As String = String.Empty
    Dim iPool As Integer = 0
    While (Not Integer.TryParse(pool, iPool))
      Console.WriteLine("Available ApplicationPools: Managed runtime version")
      Dim i As Integer
      For i = 0 To manager.ApplicationPools.Count - 1 Step i + 1
        Dim appPool As ApplicationPool = manager.ApplicationPools(i)
        Console.WriteLine("{3}{0,3}.{3}{1}: {2}", i + 1, _
            appPool.Name, appPool.ManagedRuntimeVersion, vbTab)
      Console.Write("{0}Choose an application pool to change: ", vbCrLf)
      pool = Console.ReadLine()
    End While
    Return iPool - 1
  End Function

    ' Prompts a user to select the version of runtime they would like
    ' the application pool to use
    Public Shared Function GetVersion() As String
        Dim rtVersion As String = String.Empty
        Dim iVersion As Integer = 0
        While (Not Integer.TryParse(rtVersion, iVersion))
            Console.WriteLine("{0}  1.{0}Framework version 1.0", vbTab)
            Console.WriteLine("{0}  2.{0}Framework version 1.1", vbTab)
            Console.WriteLine("{0}  3.{0}Framework version 2.0", vbTab)
            Console.Write("Choose the new managed runtime version: ")
            rtVersion = Console.ReadLine()
        End While
        Select Case iVersion
            Case 1
                rtVersion = "v1.0"
            Case 2
                rtVersion = "v1.1"
            Case 3
                rtVersion = "v2.0"
        End Select
        Return rtVersion
    End Function
End Class


using System;
using Microsoft.Web.Administration;

public class AppPoolSample 
  static ServerManager manager = new ServerManager();
  // Main application processing
  public static void Main(string[] args)  
    // Get the apppool to change
    int iPool = GetAppPool();
    // Get the framework version desired
    string rtVersion = GetVersion();
    // Set the apppool runtime
    ApplicationPool poolToSet = manager.ApplicationPools[iPool];
        "Setting application pool '{0}' to runtime version: {1}...",
        poolToSet.Name, rtVersion);
    poolToSet.ManagedRuntimeVersion = rtVersion;
    // Commit the changes and recycle the application pool
    Console.WriteLine("Your changes have been committed.");
  // Prompts the user to select an application pool
 public static int GetAppPool()
    string pool = String.Empty;
    int iPool = 0;
    while ((!int.TryParse(pool, out iPool)) ||
            (iPool > manager.ApplicationPools.Count || iPool <= 0))
                    "Available ApplicationPools: Managed runtime version");
      for (int i = 0; i <= manager.ApplicationPools.Count - 1; i++)
        ApplicationPool appPool = manager.ApplicationPools[i];
        Console.WriteLine("t{0,3}.t{1}: {2}", i + 1, 
            appPool.Name, appPool.ManagedRuntimeVersion);
      Console.Write("rnChoose an application pool to change: ");
      pool = Console.ReadLine();
  return iPool -1;
  // Prompts a user to select the version of runtime they would like
  // the application pool to use
  public static string GetVersion()
    string rtVersion = String.Empty;
    int iVersion = 0;
    while ((!int.TryParse(rtVersion, out iVersion)) ||
            (iVersion > 3 || iVersion < 1))
      Console.WriteLine("rnt   1.tFramework version 1.0");
      Console.WriteLine("t   2.tFramework version 1.1");
      Console.WriteLine("t   3.tFramework version 2.0");
      Console.Write("Choose the new managed runtime version: ");
      rtVersion = Console.ReadLine();
    switch (iVersion)
        case 1:
            rtVersion  = "v1.0";
        case 2:
            rtVersion = "v1.1";
        case 3:
            rtVersion = "v2.0";
    return rtVersion;

Post Navigation