Microsoft.Web.Administration in IIS 7


While creating the new administration stack in IIS 7, we were looking into the different ways users could manipulate the server configuration as well as the new runtime information available in IIS 7 (Internally we call this RSCA-Runtime State and Control API) from managed code, and we realized we needed to provide a simpler and more straight forward API that developers could consume from managed code. Microsoft.Web.Administration is the answer to this problem. This API is designed to be simple to code against in an “intellisense-driven” sort of way. At the root level a class called ServerManager exposes all the functionality you will need.

To show the power and simplicity of this API, let’s look at some samples below. To try this samples just create a new Console Application in Visual Studio and add a reference to Microsoft.Web.Administration.dll that can be found at IIS directory (%WinDir%\System32\InetSrv).
Please note that the following code is based on Windows Vista Beta 2 code and will likely change for the release candidate versions of Windows Vista since we have planned several enhancements to simplify the API and expose more features into it.
The following picture shows the main objects (excluding Configuration related classes).
 
Microsoft.Web.Administration
Creating a Site
 

ServerManager iisManager = new ServerManager();
iisManager.Sites.Add(“NewSite”“http”“*:8080:”“d:\\MySite”);
iisManager.Update();

This basically creates an instance of the ServerManager class and uses the Add method in the Sites collection to create a new site named “NewSite” listening at port 8080 using http protocol and content files are at d:\MySite.
One thing to note is that calling Update is a requirement since that is the moment when we persist the changes to the configuration store.
After running this code you have now a site that you can browse using http://localhost:8080

Adding an Application to a site

ServerManager iisManager = new ServerManager();
iisManager.Sites[“NewSite”].Applications.Add(“/Sales”“d:\\MyApp”);
iisManager.Update();


This sample uses the Sites collection Indexer to get NewSite site and uses the Applications collection to add a new http://localhost:8080/Sales application.


Creating a Virtual Directory

ServerManager iisManager = new ServerManager();
Application app iisManager.Sites[“NewSite”].Applications[“/Sales”];
app.VirtualDirectories.Add(“/VDir”“d:\\MyVDir”);
iisManager.Update();



Runtime State and Control

Now, moving on to the new Runtime state and control information we also expose in this objects information about their current state as well as the ability to modify them. For example, we expose the list of W3WP processes running (Worker processes) and what I think is really cool, we even expose the list of requests currently running. Stopping a Web Site

ServerManager iisManager = new ServerManager();
iisManager.Sites[“NewSite”].Stop();


Recyciling an Application Pool

ServerManager iisManager = new ServerManager();
iisManager.ApplicationPools[“DefaultAppPool”].Recycle();


Getting the list of executing requests

ServerManager iisManager = new ServerManager();
foreach
(WorkerProcess w3wp in iisManager.WorkerProcesses) {
    Console.WriteLine(
“W3WP ({0})”, w3wp.ProcessId);
            
    foreach 
(Request request in w3wp.GetRequests(0)) {
        Console.WriteLine(
“{0} – {1},{2},{3}”,
                    request.Url,
                    request.ClientIPAddr,
                    request.TimeElapsed,
                    request.TimeInState)
;
    
}
}

Another big thing on this API is the ability to edit the “.config” files using a simple API, this includes the ability of modifying the main applicationHost.config file from IIS, web.config files from asp.net as well as machine.config and other config files (such as administration.config). However I will talk about them in a future post.

Comments (61)

  1. That might possibly be the coolest thing I’ve ever seen IIS do.

  2. Its Wonderful and very cool.

    special thanks to Mr. carlos, Microsoft and Microsoft communities.

  3. Klok says:

    Waauuu, we will be saving so many lines of code and using this extensive.

  4. Does this modify the (what used to be) metabase? When dealing with several web servers in a cluster, will I still need to sync the metabases (or .config files) across nodes, or can I finally centralize all this on a NAS via UNC?

  5. David.Wang says:

    Mark – IIS7 does not use the metabase to store configuration. It is totally within .config files.

    There is a Legacy ABO Compatibility component (completely optional, but installed by default) which you can install to capture all legacy API calls to configure the metabase and transparently translate it into .config settings.

    You will still need to synchronize config settings across servers in a cluster, though if you run the same command remotely it’d do the same.

    I have yet to understand the need to have IIS read configuration from a UNC share vs ability to copy the same IIS configuration to multiple machines. They accomplish the same objective; you can view one as a local-cached version of the other. Central UNC share sounds cooler but is more fragile, so why???

    In other words, suppose you get what you want — the "centralized" config file on NAS via UNC. All that means is that after IIS calls CreateFile to get a handle to the file, read/write to the file can now RANDOMLY fail as IIS works with various sections of the file (and underneath the scenes, network traffic is getting used to fulfill the read/write).

    What should IIS do? Bail on first error? Bail after retrying 5 times in 5 seconds (but suppose you are modifying config — where do they go)? Cache the change locally and periodically propagate back to the UNC (but explain how this is any better than IIS reading local .config file and a separate "syncing" service periodically syncing changes between multiple locations?

    In other words — please explain your real scenario and requirements, not how you think we should implement things.

    //David

  6. David,

    Say, for example, you have several IIS nodes behind a load balancer. Then, you expose a user-facing control panel application that modifies the metabase for a feature like Application Roots, for example. This requires the replication of the "master" metabase (the one where the control panel made the change) to all the "slave" IIS nodes. This can’t occur realtime because of the sheer volume of updates occurring to the metabase. So, you have to replicate on a schedule – say, every 5 minutes. David,

    Say, for example, you have several IIS nodes behind a load balancer. Then, you expose a user-facing control panel application that modifies the metabase for a feature like Application Roots, for example. This requires the replication of the "master" metabase (the one where the control panel made the change) to all the "slave" IIS nodes. This can’t occur realtime because of the sheer volume of updates occurring to the metabase. So, you have to replicate on a schedule – say, every 5 minutes.

    What a NAS/UNC based configuration store (metabase) buys you is a way out of the replication scenario. However, there still exists the random fail issue as you described. Ideally, I’d like to see a realtime replication method similar to Active Directory. Here, there are multiple peer nodes, where any change is replicated to the other nodes. Maybe this can be accomplished via a pure in-memory database with replication via two-phase commit across IIS nodes. Maybe a heartbeat service between IIS nodes? Just brainstorming here.

    – Mark

  7. Oneda says:

    O Scott Guthrie, do time de produtos Web da Microsoft, escreveu um post bem interessante sobre as novidades…

  8. Though IIS 7 still support WMI, ABO, etc administrative interface, but you will love this new managed…

  9. Can you create AppPools with the new interface?

    I’ve been beating myselft up for a couple of months trying to figure out how to create an app pool via the WMI interface.  I’ve resorted to using ADSI, but I hear that’s going away…

    Chris

  10. Jim B says:

    How about adding a "re-read config files" function to allow central config storage and after editing the config, telling each machine to re-read the file to flush the servers internal cache?

  11. Not a bad idea, considering change notification doesnt work on metabase.xml.

  12. Прошли старые добрые деньки. Реестр закапывают в землю, бинарные форматы закапыв

  13. CarlosAg says:

    Yes you can create application pools as well as enumerate, remove them and even recycle them.

  14. ryfm says:

    ну и слава богу, тока блин, когда еще смогу перетащить клиентов на 7ку…

  15. Carlos Aguilar, del equipo de IIS 7 y desarrollador de la nueva consola y el nuevo API de administración…

  16. Before the boom of web and internet, HTTP was not so common is everyday life. When internet became more…

  17. Gopinath says:

    Is there a way to Push data to client (Push Server ) using IIS 7? (ex live stock update !)

  18. IIS7 is a major upgrade of IIS, and will ship in both Windows Vista as well as Windows Longhorn Server. …

  19. Ali AYEN says:

    ServerManager iisManager = new ServerManager();

    iisManager.Sites.Add("NewSite", "http", "*:8080:", "d:\MySite");

    >–>> iisManager.Update();

    I think .Update() method is replaces with .CommitChanges()

  20. More than a year ago I wrote about Microsoft.Web.Administration.dll and how it was a new API we were

  21. Mick says:

    Can this be used to manage remote IIS servers within the same AD group?

    mick dot walker at gmail dot com

  22. CarlosAg says:

    Yes, you can use it to manage IIS 7 running in Windows Vista SP1 or Windows Server 2008 but only from a client running Windows Vista SP1 or Windows Server 2008. The way to do it is creating a ServerManager like this:

    ServerManager remoteManager = ServerManager.OpenRemote("yourServer");

  23. More than a year ago I wrote about Microsoft.Web.Administration.dll and how it was a new API we were

  24. Mick Walker says:

    Thanks for your reply Carlos.

    Do you know where I can find some ‘good’ documentation on this?

  25. Mick Walker says:

    Also is there anyway to control FTP settings for a Site?

  26. Mick Walker says:

    When using FTP 7.0 with IIS 7.0 and using Microsoft.Web.Administration how do add ftp settings to a web site? Or do I have to manually edit the .config files xml to add it?

    If not supported, would this feature be supported in future?

  27. CarlosAg says:

    You can absolutely use Microsoft.Web.Administration for that, however you will either need to use the loosely typed model (ConfigurationSection, ConfigurationElement, etc) or you will need to create your own strongly typed classes for it.

    For example if you want to set something in the site, you can use:

    ConfigurationElement ftpServer =ServerManager.Sites["Default Web Site"].GetChildElement("ftpServer");

    And then use that for anything you need, also FTP defines several sections as well that you can use GetSection() over a Configuration object.

  28. PrideRock says:

    IIS7伴随着Vista已经悄悄来临,学习的时候我也摘录了一些有关于此的文章。 不敢独享,还是贴出来大家共享吧!

  29. MarkDubya says:

    Will this all be exposed to the (VB) scripting engine?

  30. Marcel Meyer says:

    Hi Carlos,

    How do I query the current memory usage of a Site?

    Regards,

    Marcel

  31. Матвей says:

    Интересную тему для вордпресса поставили. Сами делали или стандартную какую брали? 🙂

  32. Tazeem Ansari says:

    Hi Carlos ,

    I am facing that create a virtual director from C# code without having admin previliages the code is

               System.DirectoryServices.DirectoryEntry oDE;

               System.DirectoryServices.DirectoryEntries oDC;

               System.DirectoryServices.DirectoryEntry oVirDir;

               oVirDir = null;

               try

               {

                   // check whether to create FTP or IIS virtual directory

                   if (IsFTP)

                   {

                       oDE = new DirectoryEntry("IIS://" + deploymentServerName + "/MSFTPSVC/1/Root");

                   }

                   else

                   {

                       oDE = new DirectoryEntry("IIS://" + deploymentServerName + "/W3SVC/1/Root");

                   }

                   try

                   {

                       string directoryEntryNameStr = oDE.Name;

                   }

    now tell me a solution when I can create a virtual directory without being admin to windows Vista.

    I clicked IIS6.0 metadata and configuration compatibilty and manament from window feature on/off/

  33. CarlosAg says:

    For security reasons you cannot add a virtual directory unless you are an administrator.

    You can imagine that if a non-administrator was able to expose a random directory over the URL namespace of the site would be a bad idea.

  34. Safe3 says:

    本文翻译整理自CarlosAguilarMares的blog文章:Microsoft.Web.AdministrationinIIS7。

    请注意本文的内容均基于WindowsVista…

  35. ddnguyen73 says:

    Can we use the Microsoft.Web.Administration from a Windows Server 2008 to remotely manage IIS 6 running on Windows Server 2003?  Where is the Microsoft.Web.Administration located?  Is it part of .Net or Windows?

  36. CarlosAg says:

    Unfortunately you can only use it to manage a Windows Vista, Windows Server 2008, Windows 7, and Windows Server 2008 R2 server.

    It is not distributed with .net but instead is part of IIS.

  37. ddnguyen73 says:

    Are they any major changes to the Microsoft.Web.Administration API’s in IIS 7.5?

  38. Kev says:

    I am using VS2008 on an XP machine and cannot see the Microsoft.Web.Administration namespace. I guess this is because it is part of IIS7, which is not on the development machine. The finished code is to run on an IIS 7 server. I’d like to create a reference but don’t know where to find one. Can anyone help please?

    Thanks!

  39. Kev says:

    Update: I installed the IIS Remote Manager on the XP dev machine thinking I might get the dll with it, but it appears not…

  40. 童貞卒業 says:

    童貞卒業を考えているなら、迷わずココ!今まで童貞とヤッた事がない女性というのは意外と多いものです。そんな彼女たちは一度童貞とやってみたいと考えるのは自然な事と言えるでしょう。当サイトにはそんな好奇心旺盛な女性たちが登録されています

  41. 素人 says:

    素人ホストでは日頃のストレスを発散したい、もう一度恋がしたい、そういた女性が癒しを求めて登録されています。当サイトは癒やされたい女性・寂しい女性を癒やす男性が集うカップリングサイトです

  42. 熟女 says:

    熟女だって性欲がある、貴方がもし人妻とSEXしてお金を稼ぎたいのなら、一度人妻ワイフをご利用ください。当サイトには全国各地からお金持ちのセレブたちが集まっています。女性から男性への報酬は、 最低15万円からと決めております。興味のある方は一度当サイト案内をご覧ください

  43. Philip says:

    Just wondering, How would one go about using this API to both View and Modify the contents of the IPGrant and/or Deny Table?

    Could you be so kind as to give an explanation or hint?

  44. CarlosAg says:

    @Philip, here is an example:

           using(ServerManager serverManager = new ServerManager()) {

               Configuration config = serverManager.GetApplicationHostConfiguration();

               ConfigurationSection ipSecuritySection = config.GetSection("system.webServer/security/ipSecurity");

               ConfigurationElementCollection ipSecurityCollection = ipSecuritySection.GetCollection();

               ConfigurationElement addElement = ipSecurityCollection.CreateElement("add");

               addElement["ipAddress"] = @"169.132.124.234";

               ipSecurityCollection.Add(addElement);

               serverManager.CommitChanges();

           }

       }

    You can also learn more at the configReference where we have samples for all sections: http://www.iis.net/…/ipSecurity

  45. sridevi says:

    using (ServerManager mgr = new ServerManager())

                       {

                           Site site = mgr.Sites[siteName];

                           if (site != null)

                           {

                               Microsoft.Web.Administration.Application app = site.Applications[appName];

                               if (app == null)

                               {

                                   Microsoft.Web.Administration.Application iisApplication =

                                   site.Applications.Add(appName, ApplicationPath);

                                   //sets the application to Classic .Net AppPool

                                   iisApplication.ApplicationPoolName = "ASP.NET v4.0 wcf";

                                   //mgr.ApplicationPools["DefaultAppPool"].Recycle();

                               }

  46. markus says:

    anyone got a clue how to delete a virtual directory? with VirtualDirectories.Remove…. i cant get it to work

  47. 闫大卫 says:

    非常不错,但是最近我在开发一个使用IIS Express运行的控制本地系统自带的IIS的系统,问题出现了。

    可以获取到站点信息,但是不能获取到Site.State、Stop、Start都不能使用,保异常为:未实现的方法。

    但是该用VS开发服务器就没有这样的问题,难道是配置问题?不知道是什么原因,请求协助Email:yandavid@163.com.谢谢。

  48. Raj says:

    How do I get TARGETSITE (id for the website ) programmetically? Thx For example, get ID for MyWebSite?

  49. Superfreak3 says:

    Would love to be able to get code to delete 2 virtual directories/applications then check to see if application pool has any other apps assigned to it.  If not, delete the app Pool.

  50. Geethanga says:

    I'm trying to create a virtual directory using C#. When try to add a reference to Microsoft.Web.Administration Namespace I can't find it in the list. Any clue?

    And thanks for the great article.

  51. Warren Yu says:

    How can  I using Microsoft.Web.Administration in my asp.net web site.

    I want create a web page to manager the iis.

  52. jhon says:

    How to assign a specific user credentials for a site in IIS 6.0 using Visual Studio help please

  53. hellomo says:

    关于ASP.NET操作IIS7的范例,可以查阅

    http://www.china-java.net/frmDOCView.aspx

  54. Ananth says:

    its not working for remote administration, any code is really appritiated

  55. Kambiz says:

    Error On remote machine?

    Unauthorized Access Exception

  56. Tasin says:

    i want a vb code that can query the iis metadata to give the list of site that has browsing directory enabled status .can anyone provide it???

  57. Adrian says:

    Hi this is great, however I am sitting with a major headache and cannot for the love of me add the node

    “”

    to the file … do you perhaps have a solution? I had tried the below to no avail.

    Configuration config = serverManager.GetWebConfiguration(“Default Web Site”);
    ConfigurationSection applicationPoolsSection = config.GetSection(“system.web”);
    ConfigurationElementCollection applicationPoolsCollection = applicationPoolsSection.GetCollection();

    ConfigurationElement addElement = applicationPoolsCollection.CreateElement(“identity”);
    addElement[“key”] = “impersonate”;
    addElement[“value”] = “true”;
    applicationPoolsCollection.Add(addElement);

    serverManager.CommitChanges();

    1. CarlosAg says:

      You need to make sure request the right section, in this case it is system.web/identity (the whole thing), you can figure that out looking into %windir%\system32\inetsrv\config\schema

      So do:
      using(ServerManager serverManager = new ServerManager()) {
      Configuration config = serverManager.GetWebConfiguration(“Your Site”);

      ConfigurationSection identitySection = config.GetSection(“system.web/identity”);
      identitySection[“impersonate”] = true;

      serverManager.CommitChanges();
      }

Skip to main content