Saturday, March 12, 2011

IIS administration using C# - multiple websites text search and replace in physicalpath

I recently found myself in a situation where I had several different web applications that where branches/tagged/deployed as a unit. When working with several different feature branches this leads to either having quite a few individual sites in IIS or updating the configurations of the existing IIS sites when switching to another branch. Since the setup and configuration of these sites was non-trivial, I ended up wondering if I could have one setup in IIS and then just bulk update the web applications physical path using a search and replace functionality.


Initially I tried vbs, but then I found this nice dll Microsoft.Web.Administration, which allows you to perform IIS administration from C#/.NET.


We have the following file system layout



Looking at the IIS administration tool we are currently pointing to branch1.





Running the program and bulk updating one or more site's physical paths.



Looking in the IIS administration again we see that the physical path of the site has been updated.



The source code below is pretty self explanatory. (Please note that I have kept the sources to the bare minimum to illustrate working with the Web.Administration API, rather than doing null checks, array length checks, try catches ...)


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Web.Administration;

namespace UpdateIisApplicationPaths
{
 public partial class Form1 : Form
 {
  private readonly ServerManager serverManager = new ServerManager();
  public Form1()
  {
   InitializeComponent();
  }

  private void Form1_Load(object sender, EventArgs e)
  {
   foreach (var site in serverManager.Sites)
   {
    websitesListBox.Items.Add(site.Name);
   }  
  }

  private void commitChangesButton_Click(object sender, EventArgs e)
  {
   Cursor.Current = Cursors.WaitCursor;
   foreach (var sitename in websitesListBox.SelectedItems)
   {
    var physicalPath = serverManager.Sites[(string) sitename].Applications[0].VirtualDirectories[0].PhysicalPath;
    physicalPath = physicalPath.Replace(oldPhysicalSitePathTextBox.Text, newPhysicalSitePathTextBox.Text);
    serverManager.Sites[(string) sitename].Applications[0].VirtualDirectories[0].PhysicalPath = physicalPath;
   }
   serverManager.CommitChanges();
   Cursor.Current = Cursors.Default;
  }

  private void websitesListBox_SelectedIndexChanged(object sender, EventArgs e)
  {
   if (websitesListBox.SelectedItems.Count > 0)
   {
    oldPhysicalSitePathTextBox.Text =
     serverManager.Sites[(string) websitesListBox.SelectedItems[0]].Applications[0].VirtualDirectories[0].PhysicalPath;
   }
  }
 }
}
Post a Comment