Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save georgepaoli/f0290ad9f872c9926d74710af7d9aa24 to your computer and use it in GitHub Desktop.
Save georgepaoli/f0290ad9f872c9926d74710af7d9aa24 to your computer and use it in GitHub Desktop.
Microsoft.Web.Administration in IIS 7
From https://blogs.msdn.microsoft.com/carlosag/2006/04/17/microsoft-web-administration-in-iis-7/
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment