using System;
using System.DirectoryServices;
using System.Globalization;
using Ada.Configurator.Common;
using NAnt.Core.Attributes;
using NAnt.Core;

namespace AdaNantTasks
{
    /// <summary>
    /// Delete an IIS virtual directory on a website with a hostheader.
    /// </summary>
    [TaskName("deleteVirtualDirectoryTask")]
    public class DeleteVirtualDirectoryTask : Task
    {
        public NantLogger logger = new NantLogger();
        public string VirDirSchemaName = "IIsWebVirtualDir";

        private string m_server;
        [TaskAttribute("server", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string Server
        {
            get { return m_server; }
            set { m_server = value; }
        }

        private string m_virtualDirectoryName;
        [TaskAttribute("virtualDirectoryName", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string VirtualDirectoryName
        {
            get { return m_virtualDirectoryName; }
            set { m_virtualDirectoryName = value; }
        }

        private string m_websiteName;
        [TaskAttribute("websiteName", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public string WebsiteName
        {
            get { return m_websiteName; }
            set { m_websiteName = value; }
        }

        /// <summary>
        /// Creates website
        /// </summary>
        protected override void ExecuteTask()
        {
            try
            {
                this.DeleteVirtualDirectory();
                Project.Log(Level.Info, string.Format("Virtualdirectory [{0}] created", m_virtualDirectoryName));
            }
            catch (Exception ex)
            {
                logger.Log(this.Project, Level.Error, string.Format("VirtualDirectory [{0}] not created, because an exception occurred [{1}]", m_virtualDirectoryName, ex.ToString()));
                throw new BuildException("Unable to create website", ex);
            }
        }

        /// <summary>
        /// Delete an IIS virtualdirectory
        /// </summary>
        public void DeleteVirtualDirectory()
        {
            if (string.IsNullOrEmpty(m_server)) { throw new Exception("Property [Server] can't be null or empty"); } else { Console.WriteLine(string.Format("DeleteVirtualDirectory: [{0}]", m_server)); }
            if (string.IsNullOrEmpty(m_virtualDirectoryName)) { throw new Exception("Property [VirtualDirectoryName] can't be null or empty"); } else { Console.WriteLine(string.Format("DeleteVirtualDirectory: [{0}]", m_virtualDirectoryName)); }
            if (string.IsNullOrEmpty(m_websiteName)) { throw new Exception("Property [WebsiteName] can't be null or empty"); } else { Console.WriteLine(string.Format("DeleteVirtualDirectory: [{0}]", m_websiteName)); }

            int websiteId = this.GetWebSiteId(m_server, m_websiteName);

            string iisPath = string.Format("IIS://{0}/w3svc/{1}", m_server, websiteId);

            using (DirectoryEntry w3svc = new DirectoryEntry(iisPath))
            {
                w3svc.RefreshCache();

                using (DirectoryEntry folderRoot = w3svc.Children.Find("Root", VirDirSchemaName))
                {
                    folderRoot.RefreshCache();
                    DirectoryEntry virtualDirectory = null;

                    try
                    {
                        folderRoot.Children.Find(m_virtualDirectoryName, VirDirSchemaName);
                        folderRoot.Invoke("AppDelete");
                        folderRoot.Children.Remove(virtualDirectory);
                    }
                    catch
                    {
                        Console.WriteLine("Virtual directory [{0}] already exists or error during delete", m_virtualDirectoryName);
                    }
                }
            }
        }

        /// <summary>
        /// Get website id on websitename
        /// </summary>
        /// <param name="serverName">Name of the IIS server e.g. localhost</param>
        /// <param name="websiteName">Name of the website e.g. test</param>
        /// <returns>
        /// Less the 0, site does not exist
        /// Id of the existing site
        /// </returns>
        public int GetWebSiteId(string serverName, string websiteName)
        {
            if (string.IsNullOrEmpty(serverName)) { throw new Exception("Parameter [serverName] can't be null or empty"); } else { Console.WriteLine(string.Format("GetWebSiteId: [{0}]", serverName)); }
            if (string.IsNullOrEmpty(websiteName)) { throw new Exception("Parameter [websiteName] can't be null or empty"); } else { Console.WriteLine(string.Format("GetWebSiteId: [{0}]", websiteName)); }
            int result = -1;

            using (DirectoryEntry w3svc = new DirectoryEntry(string.Format("IIS://{0}/w3svc", serverName)))
            {
                w3svc.RefreshCache();

                foreach (DirectoryEntry site in w3svc.Children)
                {
                    using (site)
                    {
                        site.RefreshCache();

                        if (site.Properties["ServerComment"] != null)
                        {
                            if (site.Properties["ServerComment"].Value != null)
                            {
                                if (site.Properties["ServerComment"].Value.ToString().Equals(websiteName, StringComparison.OrdinalIgnoreCase))
                                {
                                    result = int.Parse(site.Name);
                                }
                            }
                        }
                    }
                }
            }

            Console.WriteLine(string.Format("GetWebSiteId: [{0}]", result));
            return result;
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.