Click here to Skip to main content
13,404,627 members (35,859 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

15K views
50 downloads
6 bookmarked
Posted 8 Aug 2013

Connection Limit Enforcer for IIS Websites

, 11 Aug 2013
Rate this:
Please Sign up or sign in to vote.
Enforce limits to IIS Websites inbound connections

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.

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)

Share

About the Author

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

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

You may also be interested in...

Comments and Discussions

 
AnswerRe: the way! Pin
bgsjust8-Aug-13 23:48
professionalbgsjust8-Aug-13 23:48 
GeneralRe: the way! Pin
bgsjust9-Aug-13 2:59
professionalbgsjust9-Aug-13 2:59 
AnswerRe: the way! Pin
bgsjust9-Aug-13 12:06
professionalbgsjust9-Aug-13 12:06 
QuestionNot an Article Pin
Simon_Whale8-Aug-13 14:11
professionalSimon_Whale8-Aug-13 14:11 
AnswerRe: Not an Article Pin
bgsjust8-Aug-13 23:43
professionalbgsjust8-Aug-13 23:43 
GeneralRe: Not an Article Pin
Simon_Whale8-Aug-13 23:52
professionalSimon_Whale8-Aug-13 23:52 
GeneralRe: Not an Article Pin
bgsjust9-Aug-13 0:24
professionalbgsjust9-Aug-13 0:24 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.1802120.2 | Last Updated 11 Aug 2013
Article Copyright 2013 by bgsjust
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid