Click here to Skip to main content
15,894,896 members
Articles / Web Development / IIS

Programmatically Manage IIS

Rate me:
Please Sign up or sign in to vote.
4.48/5 (12 votes)
27 Nov 2008CPOL5 min read 74.2K   1.8K   55  
Base library for programmatically managing IIS through C# and Directory Services.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
using System.IO;

namespace Sarafian.Framework.General.DirectoryManager.IIS
{
    public class WebSite : Base.BaseEntry
    {
        public const string SCHEMA_CLASS_NAME = "IIsWebServer";
        public WebSite(DirectoryEntry entry, Service service)
            : base(entry)
        {
            Service = service;
        }

        protected override void GuardValidEntry()
        {
            if (!IsWebSite(base.SourceEntry))
            {
                throw new Exception("WebSite not found Exception");
            }
        }
        protected override void HandleChild(DirectoryEntry child)
        {
            if (WebVirtualDir.IsWebVirtualDir(child))
            {
                WebVirtualDir = new WebVirtualDir(child, this);
                return;
            }
        }
        protected override void BeforeRefresh()
        {
            WebVirtualDir = null;
        }
        protected override string SchemaClassName
        {
            get { return SCHEMA_CLASS_NAME; }
        }


        public DirectoryEntry WebSiteEntry { get { return base.SourceEntry; } }
        public Service Service { get; private set; }

        public static bool IsWebSite(DirectoryEntry entry)
        {
            return entry.SchemaClassName == SCHEMA_CLASS_NAME;
        }

        public string ServerBindings
        {
            get {
                if (base.Properties["ServerBindings"].IsString)
                {
                    return base.Properties["ServerBindings"].StringValue;
                }
                object[] values = (object[])base.Properties["ServerBindings"].Value;
                return values[0].ToString();
            }
            set { base.Properties.SetPropertyValue("ServerBindings", value); }
        }
        public string ServerComment
        {
            get { return base.Properties["ServerComment"].StringValue; }
            set { base.Properties["ServerComment"].Value = value; }
        }
        public int SiteID
        {
            get { return Convert.ToInt32(WebSiteEntry.Path.Substring(WebSiteEntry.Path.LastIndexOf(@"/") + 1)); }
        }
        public int Port
        {
            get 
            {
                try
                {
                    return Convert.ToInt32(ServerBindings.Replace(":", "")); 
                }
                catch (Exception)
                {
                }
                return -1;
            }
            set { ServerBindings = String.Concat(":", value.ToString(), ":"); }
        }

        public string DisplayName
        {
            get { return String.Format("{0}:{1}", ServerComment, Port.ToString()); }
        }

        public WebSiteStates State
        {
            get
            {
                DirectoryEntry site = new DirectoryEntry(base.SourceEntry.Path);
                return (WebSiteStates)Convert.ToInt32(site.Properties["ServerState"].Value);
                //PropertyValueCollection pvc;
                //pvc = root.Properties["ServerState"];
                //if (pvc.Value != null)
                //    result = (pvc.Value.Equals((int)eStates.Start) ? "Running" :
                //              pvc.Value.Equals((int)eStates.Stop) ? "Stopped" :
                //              pvc.Value.Equals((int)eStates.Pause) ? "Paused" :
                //              pvc.Value.ToString());

                //return (WebSiteStates)this.Properties["ServerState"].IntValue; ;
            }
        }

        public string PhysicalPath
        {
            get { return WebVirtualDir.PhysicalPath; }
        }


        public WebVirtualDir WebVirtualDir { get; private set; }
        public List<VirtualDirectory> VirtualDirectories { get { return WebVirtualDir.VirtualDirectories; } }
        public VirtualDirectory FindVirtualDirectory(string virtualDirectoryName)
        {
            return WebVirtualDir.FindVirtualDirectory(virtualDirectoryName);
        }
        //public override string Name
        //{
        //    get
        //    {
        //        return base.Name + "_" + ServerComment;// +"(" + ServerBindings + ")";
        //    }
        //}

        public static WebSite Create(Service service, string siteName, int port, string physicalPath)
        {
            string newSiteID = service.GetNextAvailableSiteID().ToString();
            DirectoryEntry newSite = service.Children.Add(newSiteID, SCHEMA_CLASS_NAME);
            newSite.Properties["ServerComment"][0] = siteName;
            newSite.CommitChanges();

            //if (!Directory.Exists(physicalPath))
            //{
            //    Directory.CreateDirectory(physicalPath);
            //}
            WebSite webSite = new WebSite(newSite, service);

            if (service.MajorVersionNumber == 6)
            {
                webSite.ApplyASPNETV2();
            }

            WebVirtualDir root = WebVirtualDir.Create(webSite, physicalPath);
            webSite.Port = port;
            webSite.CommitChanges();
            return webSite;
        }

        #region Methods
        public void Start()
        {
            WebSiteEntry.Invoke("Start");
        }

        public void Stop()
        {
            WebSiteEntry.Invoke("Stop");
        }

        public void Restart()
        {
            Stop();
            Start();
        }
        public VirtualDirectory AddVirtualDirectory(string virtualDirectoryName, string physicalPath)
        {
            VirtualDirectory existing = WebVirtualDir.FindVirtualDirectory(virtualDirectoryName);
            if (existing != null)
            {
                existing.Delete();
            }
            VirtualDirectory vd = VirtualDirectory.Create(this, virtualDirectoryName, physicalPath);
            base.Refresh();
            return vd;
        }

        public VirtualDirectory ConvertToApplication(string subFolder)
        {
            VirtualDirectory vd = AddVirtualDirectory(subFolder, Path.Combine(WebVirtualDir.PhysicalPath, subFolder));
            vd.CreateApp();
            base.Refresh();
            return vd;
        }

        public void ApplyASPNETV2()
        {
            string dotNetFxDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
            string regiis = Path.Combine(dotNetFxDir, "Aspnet_regiis.exe");
            string args = "-s W3SVC/" + SiteID.ToString();
            System.Diagnostics.Process.Start(regiis, args);
        }
        #endregion

    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Team Leader ALGOSYSTEMS
Greece Greece
I live in Athens Greece and currently I am working with Business scale application with .NET latest technologies

I've been developing applications for personal and friends usage with C++ using majorly Borland's various IDEs since 1994.
In 2002 I began working for an R&D institute where I was introduced to C# which I worships ever since.

I love core application development and I would like to publish more articles here and on my blog, but there is not enough time to do so.

I usualy "waste" my spare time watching sitcoms, preferable SCI-FI.
I would like to play chess but I can't find any real world players to hang out with.

Comments and Discussions