Click here to Skip to main content
15,886,597 members
Articles / Programming Languages / C#
Tip/Trick

Connection Limit Enforcer for IIS Websites

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
11 Aug 2013CPOL1 min read 21K   53   6   9
Enforce limits to IIS Websites inbound connections

Image 1

Introduction

This is my first tip, so please bear with me Smile | :). 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.

C#
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); // exp.  65536
                        limitsElement["maxConnections"] = 
                        (long)Convert.ToDouble(textBox2.Text); //exp. 1024
                        limitsElement["connectionTimeout"] = 
                        TimeSpan.Parse(textBox3.Text); //exp.  TimeSpan.Parse("00:01:00");
                        }
                        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)
                    {
                        //start the site...
                        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)
                    {
                        //stop the site...
                        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)
                {
                    //Restart the site...
                    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! Smile | :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO BGSSOFTLINE
Portugal Portugal
http://www.linkedin.com/profile/view?id=255306870&trk=tab_pro

Http://bgssoftline.dynip.sapo.pt/store

Comments and Discussions

 
QuestionMessage Closed Pin
8-Aug-13 21:11
user55832088-Aug-13 21:11 
AnswerRe: the way! Pin
bgsjust8-Aug-13 22:48
professionalbgsjust8-Aug-13 22:48 
GeneralMessage Closed Pin
9-Aug-13 0:23
user55832089-Aug-13 0:23 
GeneralRe: the way! Pin
bgsjust9-Aug-13 1:59
professionalbgsjust9-Aug-13 1:59 
AnswerRe: the way! Pin
bgsjust9-Aug-13 11:06
professionalbgsjust9-Aug-13 11:06 
QuestionNot an Article Pin
Simon_Whale8-Aug-13 13:11
Simon_Whale8-Aug-13 13:11 
AnswerRe: Not an Article Pin
bgsjust8-Aug-13 22:43
professionalbgsjust8-Aug-13 22:43 
GeneralRe: Not an Article Pin
Simon_Whale8-Aug-13 22:52
Simon_Whale8-Aug-13 22:52 
GeneralRe: Not an Article Pin
bgsjust8-Aug-13 23:24
professionalbgsjust8-Aug-13 23:24 
I don't see what's so difficult to understand!

If you your site is being bombed by requests and all your bandwidth is being consumed what will you do ? Turn off the router ? Smile | :)

Restrain the access to your webpages, or all system will collapse! Smile | :)

Ok I will revise it and expand the article.

Regards!

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.