Introduction
This is my first tip, so please bear with me . I'm a programmer since the ages of Timex
ZX Spectrum, now I'm developing websites and robust
translation engines. I faced the need to set restrictions on
websites' inbound connections. So I developed this little widget to
help me out. Of course, you can manually search in IIS
for this particular element and settings, but you can also consider this as
a light approach to programmatically command IIS. This was tested under IIS 6.1
running on Windows 7, adaptations may be required for other environments. You may use the tool freely, just please leave the propaganda on! :) Have fun!
The Need to Develop this Widget
This is a simple example to demonstrate
that we can manage IIS programmatically.
- Give wings to imagination and develop a load balancer to distribute your resources wisely upon request made to your websites!
- To be able to automatically allocate resources
to the websites that are more requested and free from those that
are less!
Using the Code
Simply extract the source and compile it under Visual Studio 2010; you may need to set reference to Microsoft.Web.Administration.dll.
You may need to run Visual Studio or the Widget as Administrator!
Here's the full code, it should be self explanatory.
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 EnforceIISwebsiteLimit
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void ListSites(TreeView tv, params string[] keyValues)
{
using (ServerManager serverManager = new ServerManager())
{
Configuration config = serverManager.GetApplicationHostConfiguration();
ConfigurationSection sitesSection = config.GetSection("system.applicationHost/sites");
ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();
tv.Nodes.Clear();
int nodecount = 0;
foreach (ConfigurationElement element in sitesCollection)
{
tv.Nodes.Add(element.ElementTagName);
for (int i = 0; i < keyValues.Length; i += 2)
{
object o = element.GetAttributeValue(keyValues[i]);
string value = null;
if (o != null)
{
value = o.ToString();
tv.Nodes[nodecount].Nodes.Add(o.ToString());
tv.Nodes[nodecount].Nodes[i].ForeColor = System.Drawing.Color.Green;
}
if (!String.Equals(value, keyValues[i + 1], StringComparison.OrdinalIgnoreCase))
{
break;
}
}
nodecount++;
}
}
}
public ConfigurationElement FindElement(ConfigurationElementCollection collection,
string elementTagName, params string[] keyValues)
{
foreach (ConfigurationElement element in collection)
{
if (String.Equals(element.ElementTagName, elementTagName, StringComparison.OrdinalIgnoreCase))
{
bool matches = true;
for (int i = 0; i < keyValues.Length; i += 2)
{
object o = element.GetAttributeValue(keyValues[i]);
string value = null;
if (o != null)
{
value = o.ToString();
}
if (!String.Equals(value, keyValues[i + 1], StringComparison.OrdinalIgnoreCase))
{
matches = false;
break;
}
}
if (matches)
{
return element;
}
}
}
return null;
}
public void Enforcesitelimits(string sitename)
{
using (ServerManager serverManager = new ServerManager())
{
Configuration config = serverManager.GetApplicationHostConfiguration();
ConfigurationSection sitesSection =
config.GetSection("system.applicationHost/sites");
ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();
ConfigurationElement siteElement =
FindElement(sitesCollection, "site", "name", sitename);
if (siteElement == null)
throw new InvalidOperationException("Element not found!");
ConfigurationElement limitsElement =
siteElement.GetChildElement("limits");
try
{
limitsElement["maxBandwidth"] =
(long)Convert.ToDouble(textBox1.Text);
limitsElement["maxConnections"] =
(long)Convert.ToDouble(textBox2.Text);
limitsElement["connectionTimeout"] =
TimeSpan.Parse(textBox3.Text);
}
catch
{
MessageBox.Show("Ivalid set of Parameters");
}
serverManager.CommitChanges();
}
}
public void GetsiteAtributes(string sitename)
{
using (ServerManager serverManager = new ServerManager())
{
Configuration config = serverManager.GetApplicationHostConfiguration();
ConfigurationSection sitesSection =
config.GetSection("system.applicationHost/sites");
ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();
ConfigurationElement siteElement =
FindElement(sitesCollection, "site", "name", sitename);
if (siteElement == null) throw new InvalidOperationException("Element not found!");
ConfigurationElement limitsElement = siteElement.GetChildElement("limits");
textBox1.Text = limitsElement["maxBandwidth"].ToString();
textBox2.Text = limitsElement["maxConnections"].ToString();
textBox3.Text = limitsElement["connectionTimeout"].ToString();
}
}
public void Start_website(string sitename)
{
using (ServerManager serverManager = new ServerManager())
{
var site = serverManager.Sites.FirstOrDefault(s => s.Name == sitename);
if (site != null)
{
try
{
site.Start();
while ( site.State == ObjectState.Starting )
{
}
if (site.State == ObjectState.Started) MessageBox.Show (" Site started! ");
}
catch
{
MessageBox.Show ( " Site couldent be started " );
}
}
else throw new InvalidOperationException("Could not find website!");
}
}
public void Stop_website(string sitename)
{
using (ServerManager serverManager = new ServerManager())
{
var site = serverManager.Sites.FirstOrDefault(s => s.Name == sitename);
if (site != null)
{
try
{
site.Stop();
while ( site.State == ObjectState.Stopping )
{
}
if (site.State == ObjectState.Stopped) MessageBox.Show (" Site stopped! ");
}
catch
{
MessageBox.Show ( " Site couldn't be stopped " );
}
}
else throw new InvalidOperationException("Could not find website!");
}
}
public void Restart_website(string sitename)
{
using (ServerManager serverManager = new ServerManager())
{
var site = serverManager.Sites.FirstOrDefault(s => s.Name == sitename);
if (site != null)
{
try
{
site.Stop();
while (site.State == ObjectState.Stopping)
{
}
site.Start();
while (site.State == ObjectState.Starting)
{
}
if (site.State == ObjectState.Started) MessageBox.Show(" Site Restarted! ");
}
catch
{
MessageBox.Show("Site couldn't be Restarted");
}
}
else throw new InvalidOperationException("Could not find website!");
}
}
public void button1_Click(object sender, EventArgs e)
{
if (treeView1.Nodes.Count == 0 || treeView1.SelectedNode == null) return;
if (treeView1.SelectedNode.ForeColor == System.Drawing.Color.Green)
{
Enforcesitelimits(treeView1.SelectedNode.Text);
}
}
public void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (treeView1.Nodes.Count == 0 || treeView1.SelectedNode == null) return;
if (e.Node.ForeColor == System.Drawing.Color.Green)
{
GetsiteAtributes(e.Node.Text);
}
}
public void Form1_Load(object sender, EventArgs e)
{
ListSites(treeView1, "name", @"Default Web Site");
}
public void button2_Click(object sender, EventArgs e)
{
if (treeView1.Nodes.Count == 0 || treeView1.SelectedNode == null) return;
if (treeView1.SelectedNode.ForeColor == System.Drawing.Color.Green)
{
Start_website(treeView1.SelectedNode.Text);
}
}
public void button3_Click(object sender, EventArgs e)
{
if (treeView1.Nodes.Count == 0 || treeView1.SelectedNode == null) return;
if (treeView1.SelectedNode.ForeColor == System.Drawing.Color.Green)
{
Stop_website(treeView1.SelectedNode.Text);
}
}
public void button4_Click(object sender, EventArgs e)
{
if (treeView1.Nodes.Count == 0 || treeView1.SelectedNode == null) return;
if (treeView1.SelectedNode.ForeColor == System.Drawing.Color.Green)
{
Restart_website(treeView1.SelectedNode.Text);
}
}
}
}
Points of Interest
While setting up the app, I played a bit with the treeview
component... interesting!