ok. i've added appcreate to my fix; for downward compatibility,
i've made 'pooled' the default [though i hate the lack of
logic in that]. the result is attached

rutger

> -----Original Message-----
> From: kevin baribeau [mailto:[EMAIL PROTECTED]
> Sent: Thursday, November 25, 2004 15:17
> To: Rutger Dijkstra
> Cc: [EMAIL PROTECTED]
> Subject: Re: [NAntC-Dev] IIS Application roots
> 
> 
> Sounds like your fix is more well-thought out and useful than mine. 
> It should be used instead.  The major issue I have with what is in the
> code right now is assigning values to the AppRoot attribute, the
> behaviour of iis when this is done is not documented afaik, so using
> it in this way should be avoided.
> 
> Kevin
> 
> On Thu, 25 Nov 2004 11:44:15 +0100, Rutger Dijkstra
> <[EMAIL PROTECTED]> wrote:
> > Two remarks about this fix:
> > 1.) 'AppCreate(true)' will create an in-process application.
> >    Not recommend as a default. (potentially hazardous)
> > 2.) The default value for the appcreate attribute is 'false',
> >    meaning that no application is created. A logical choice,
> >    but it will probably break most existing uses of the task.
> >   (deploy a web-app and run some tests against it)
> > 
> > I have submitted a version of the iis-tasks that take care
> > of some other bugs. I could add the 'appcreate' attribute
> > with possible values of 'none', 'inproc', 'pooled', and
> > 'outofproc' (where 'pooled' = 'outofproc' on iis4 since it
> > does not support 'pooled').
> > The most logical default would be 'none' but if we want to
> > avoid breaking existing scripts the most responsible default
> > would be 'pooled' (which i use in my fix).
> > 
> > cheers, rutger
> > 
> > > From: "Gert Driesen" <[EMAIL PROTECTED]>
> > > To: "'kevin baribeau'" <[EMAIL PROTECTED]>,
> > >       <[EMAIL PROTECTED]>
> > > Subject: RE: [NAntC-Dev] IIS Application roots
> > > Date: Wed, 24 Nov 2004 12:12:50 +0100
> > 
> > 
> > >
> > > > -----Original Message-----
> > > > From: [EMAIL PROTECTED]
> > > > [mailto:[EMAIL PROTECTED] On
> > > > Behalf Of kevin baribeau
> > > > Sent: dinsdag 23 november 2004 20:26
> > > > To: [EMAIL PROTECTED]
> > > > Subject: [NAntC-Dev] IIS Application roots
> > > >
> > > > Hi all.
> > > >
> > > > I've made a small change to the mkiisdir task to support creating
> > > > application roots on virtual directories.  Here is a patch (created
> > > > with cvs diff -c) and a summary of the changes.
> > > >
> > > >
> > > > 1. Add a boolean attribute appcreate.  If true, create an 
> application
> > > > root on this directory, otherwise do nothing special.
> > > >
> > > > 2. Remove line setting "AppRoot" property.  This is wrong 
> according to
> > > > the documentation here (it was causing weird behaviour on iis 5):
> > > >
> > > >
> > > > http://msdn.microsoft.com/library/default.asp?url=/library/en-
> > > > us/iissdk/iis/ref_mb_approot.asp
> > > >
> > > > The appropriate quote is: "Important Because this property is
> > > > internally configured by IIS, you should consider it to be 
> read-only.
> > > > Do not configure this property."
> > > >
> > > > 3. Add an if statement creating application root if the "AppCreate"
> > > > attribute is set to True.
> > > >
> > > >
> > > > I would appreciate it greatly if this change would be accepted into
> > > > the main development branch (nightly builds, cvs etc.).  Also any
> > > > feedback and suggested changes / improvements are welcome.
> > >
> > > Kevin, can you add docs for the new "appcreate" ?
> > >
> > > Can someone else review this patch ?
> > >
> > > Gert
> > >

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.733 / Virus Database: 487 - Release Date: 2004-08-02
// NAntContrib
// Copyright (C) 2002 Brian Nantz [EMAIL PROTECTED]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
//
// Brian Nantz ([EMAIL PROTECTED])
// Gert Driesen ([EMAIL PROTECTED])

using System;
using System.Collections;
using System.DirectoryServices;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Xml;

using NAnt.Core;
using NAnt.Core.Attributes;

namespace NAnt.Contrib.Tasks {
    /// <summary>
    /// Base class for all IIS-related task.
    /// </summary>
    /// <remarks>
    /// Basically this class hold the logic to determine the IIS version as well
    /// as the IIS server/port determination/checking logic.
    /// </remarks>
    public abstract class IISTaskBase : Task {
        /// <summary>
        /// Defines the IIS versions supported by the IIS tasks.
        /// </summary>
        protected enum IISVersion {
            None,
            Four,
            Five,
            Six
        }

        #region Private Instance Fields

        private string _virtualDirectory;
        private int _serverPort = 80;
        private string _serverName = "localhost";
        private string _serverInstance = "1";
        private IISVersion _iisVersion = IISVersion.None;

        #endregion Private Instance Fields

        #region Protected Instance Constructors

        protected IISTaskBase() : base() {
        }

        #endregion Protected Instance Constructors

        #region Public Instance Properties

        /// <summary>
        /// Name of the IIS virtual directory.
        /// </summary>
        [TaskAttribute("vdirname", Required=true)]
        public string VirtualDirectory {
            get { return _virtualDirectory; }
            set { _virtualDirectory = value.Trim('/'); }
        }

        /// <summary>
        /// The IIS server, which can be specified using the format 
<c>[host]:[port]</c>. 
        /// The default is <c>localhost:80</c>.
        /// </summary>
        /// <remarks>
        /// <para>
        /// This allows for targeting a specific virtual site on a physical box.
        /// </para>
        /// </remarks>
        [TaskAttribute("iisserver")]
        public string Server {
            get {
                return StringFormat("{0}:{1}", _serverName, _serverPort);
            }
            set {
                if (value.IndexOf(":") < 0) {
                    _serverName = value;
                } else {
                    string[] parts = value.Split(':');
                    _serverName = parts[0];
                    _serverPort = Convert.ToInt32(parts[1], 
CultureInfo.InvariantCulture);
                }
            }
        }

        #endregion Public Instance Properties

        #region Protected Instance Properties

        /// <summary>
        /// Gets the version of IIS corresponding with the current OS.
        /// </summary>
        /// <value>
        /// The version of IIS corresponding with the current OS.
        /// </value>
        protected IISVersion Version {
            get {
                if (_iisVersion == IISVersion.None) {
                    Version osVersion = Environment.OSVersion.Version;

                    if (osVersion.Major < 5) {
                        // Win NT 4 kernel -> IIS4
                        _iisVersion = IISVersion.Four;
                    } else {
                        switch (osVersion.Minor) {
                            case 0:
                                // Win 2000 kernel -> IIS5
                                _iisVersion = IISVersion.Five;
                                break;
                            case 1:
                                // Win XP kernel -> IIS5
                                _iisVersion = IISVersion.Five;
                                break;
                            case 2:
                                // Win 2003 kernel -> IIS6
                                _iisVersion = IISVersion.Six;
                                break;
                        }
                    }
                }
                return _iisVersion;
            }
        }

        protected string ServerPath {
            get { 
                return StringFormat("IIS://{0}/W3SVC/{1}/Root", _serverName, 
_serverInstance); 
            }
        }

        protected string ApplicationPath {
            get { 
                return StringFormat("/LM/W3SVC/{0}/Root", _serverInstance); 
            }
        }

        protected string VdirPath {
            get {
                if(this.VirtualDirectory.Length == 0) {
                    return string.Empty;
                } else {
                    return "/"+VirtualDirectory;
                }
            }
        }

        #endregion Protected Instance Properties

        #region Protected Instance Methods

        //bug-fix for DirectoryEntry.Exists which checks for the wrong 
COMException
        protected bool DirectoryEntryExists(string path) {
            DirectoryEntry entry = new DirectoryEntry(path);
            try {
                //trigger the *private* entry.Bind() method
                object adsobject = entry.NativeObject;
                return true;
            } catch {
                return false;
            }
            finally {
                entry.Dispose();
            }
        }
        protected string StringFormat(string format, params object[] args) {
            return string.Format(CultureInfo.InvariantCulture,format,args);
        }
        protected void CheckIISSettings() {
            if(!DirectoryEntryExists(StringFormat("IIS://{0}/W3SVC", 
_serverName))) {
                throw new BuildException(StringFormat(
                    "The webservice at '{0}' does not exist or is not 
reachable.", _serverName));
            }
            _serverInstance = FindServerInstance();
 
            if (_serverInstance == null) {
                throw new BuildException(StringFormat("No website is bound to 
'{0}'.", Server));
            }
        }

        #endregion Protected Instance Methods

        #region Private Instance Methods
        private int BindingPriority(string binding) {
            string[] bindingParts = binding.Split(':');
            int port = Convert.ToInt32(bindingParts[1], 
CultureInfo.InvariantCulture);
            string host = bindingParts[2];
            if(port != _serverPort) { return 0; }
            if(host.Length == 0) { return 1; }
            if(host == _serverName) { return 2; }
            return 0;
        }
        private int BindingPriority(string binding, bool siteRunning) {
            int basePriority = BindingPriority(binding);
            return siteRunning? basePriority << 4: basePriority; 
        }
        private bool IsRunning(DirectoryEntry website) {
            return 2 == (int)website.Properties["ServerState"].Value;
        }
        private string FindServerInstance() {
            int maxBindingPriority = 0;
            string instance = null;
            DirectoryEntry webServer = 
                new DirectoryEntry(StringFormat("IIS://{0}/W3SVC", 
_serverName));
            webServer.RefreshCache();
 
            foreach( DirectoryEntry website in webServer.Children ) {
                if(website.SchemaClassName != "IIsWebServer") { 
                    website.Close();
                    continue; 
                }
                foreach( string binding in website.Properties["ServerBindings"] 
) {
                    int bindingPriority = BindingPriority(binding, 
IsRunning(website));
                    if(bindingPriority <= maxBindingPriority) { continue; }
                    instance = website.Name;
                    maxBindingPriority = bindingPriority;
                }
                website.Close();
            }
            webServer.Close();
            return instance;
        }

        #endregion Private Instance Methods
    }

    /// <summary>
    /// Creates or modifies a virtual directory of a web site hosted on Internet
    /// Information Server.
    /// </summary>
    /// <remarks>
    /// <para>
    /// If the virtual directory does not exist it is created, and if it already
    /// exists it is modified. Only the IIS-properties specified will be set. 
If set
    /// by other means (e.g. the Management Console), the unspecified 
properties retain their current value, 
    /// otherwise they are inherited from the parent. 
    /// </para>
    /// <para>
    /// For a list of optional parameters see <see 
href="ms-help://MS.VSCC/MS.MSDNVS/iisref/html/psdk/asp/aore8v5e.htm">IIsWebVirtualDir</see>.
    /// </para>
    /// </remarks>
    /// <example>
    ///   <para>
    ///   Create a virtual directory named <c>Temp</c> pointing to 
<c>c:\temp</c> 
    ///   on the local machine.
    ///   </para>
    ///   <code>
    ///     <![CDATA[
    /// <mkiisdir dirpath="c:\temp" vdirname="Temp" />
    ///     ]]>
    ///   </code>
    /// </example>
    /// <example>
    ///   <para>
    ///   Create a virtual directory named <c>Temp</c> pointing to 
<c>c:\temp</c> 
    ///   on machine <c>Staging</c>.
    ///   </para>
    ///   <code>
    ///     <![CDATA[
    /// <mkiisdir iisserver="Staging" dirpath="c:\temp" vdirname="Temp" />
    ///     ]]>
    ///   </code>
    /// </example>
    /// <example>
    ///   <para>
    ///   Configure the home directory of for http://svc.here.dev/ to point to
    ///   D:\Develop\Here and require authentication
    ///   </para>
    ///   <code>
    ///     <![CDATA[
    /// <mkiisdir iisserver="svc.here.dev" dirpath="D:\Develop\Here" 
vdirname="/" authanonymous="false"/>
    ///     ]]>
    ///   </code>
    /// </example>
    /// <example>
    ///   <para>
    ///   Create a virtual directory named <c>WebServices/Dev</c> pointing to 
    ///   <c>c:\MyProject\dev</c> on the web site running on port <c>81</c> of
    ///   machine <c>MyHost</c>.
    ///   </para>
    ///   <code>
    ///     <![CDATA[
    /// <mkiisdir iisserver="MyHost:81" dirpath="c:\MyProject\dev" 
vdirname="WebServices/Dev" />
    ///     ]]>
    ///   </code>
    ///   Note that if <c>WebServices</c> is neither an existing virtual 
directory nor an
    ///   existing physical subdirectory of the web root, your IIS Management 
Console
    ///   will get confused. Even though 
<c>http://MyHost:81/WebServices/Dev/theService.asmx</c>
    ///   may be a perfectly working webservice, the Management Console will 
not show it.
    /// </example>
    [TaskName("mkiisdir")]
    public class MakeIISDirTask : IISTaskBase {
        public enum AppType {
            none = -1,
            inprocess = 0,
            pooled = 2,
            outofprocess = 1
        }
        private class IisPropertyAttribute: Attribute {
        }
        #region Private Instance Fields

        private DirectoryInfo _dirPath;
        private bool _accessExecute = false;
        private bool _accessNoRemoteExecute = false;
        private bool _accessNoRemoteRead = false;
        private bool _accessNoRemoteScript = false;
        private bool _accessNoRemoteWrite = false;
        private bool _accessRead = true;
        private bool _accessSource = false;
        private bool _accessScript = true;
        private bool _accessSsl = false;
        private bool _accessSsl128 = false;
        private bool _accessSslMapCert = false;
        private bool _accessSslNegotiateCert = false;
        private bool _accessSslRequireCert = false;
        private bool _accessWrite = false;
        private bool _anonymousPasswordSync = true;
        private bool _appAllowClientDebug = false;
        private bool _appAllowDebugging = false;
        private AppType _apptype = AppType.pooled;
        private bool _aspAllowSessionState = true;
        private bool _aspBufferingOn = true;
        private bool _aspEnableApplicationRestart = true;
        private bool _aspEnableAspHtmlFallback = false;
        private bool _aspEnableChunkedEncoding = true;
        private bool _aspErrorsToNTLog = false;
        private bool _aspEnableParentPaths = true;
        private bool _aspEnableTypelibCache = true;
        private bool _aspExceptionCatchEnable = true;
        private bool _aspLogErrorRequests = true;
        private bool _aspScriptErrorSentToBrowser = true;
        private bool _aspThreadGateEnabled = false;
        private bool _aspTrackThreadingModel = false;
        private bool _authAnonymous = true;
        private bool _authBasic = false;
        private bool _authNtlm = false;
        private bool _authPersistSingleRequest = false;
        private bool _authPersistSingleRequestIfProxy = true;
        private bool _authPersistSingleRequestAlwaysIfProxy = false;
        private bool _cacheControlNoCache = false;
        private bool _cacheIsapi = true;
        private bool _contentIndexed = true;
        private bool _cpuAppEnabled = true;
        private bool _cpuCgiEnabled = true;
        private bool _createCgiWithNewConsole = false;
        private bool _createProcessAsUser = true;
        private bool _dirBrowseShowDate = true;
        private bool _dirBrowseShowExtension = true;
        private bool _dirBrowseShowLongDate = true;
        private bool _dirBrowseShowSize = true;
        private bool _dirBrowseShowTime = true;
        private bool _dontLog = false;
        private bool _enableDefaultDoc = true;
        private bool _enableDirBrowsing = false;
        private bool _enableDocFooter = false;
        private bool _enableReverseDns = false;
        private bool _ssiExecDisable = false;
        private bool _uncAuthenticationPassthrough = false;
        private string _aspScriptErrorMessage = "An error occurred on the 
server when processing the URL.  Please contact the system administrator.";
        private string _defaultDoc = 
"Default.htm,Default.asp,index.htm,iisstart.asp,Default.aspx";

        #endregion Private Instance Fields

        #region Public Instance Properties

        /// <summary>
        /// The file system path.
        /// </summary>
        [TaskAttribute("dirpath", Required=true)]
        public DirectoryInfo DirPath {
            get { return _dirPath; }
            set { _dirPath = value; }
        }

        [TaskAttribute("accessexecute"),IisProperty]
        public bool AccessExecute {
            get { return _accessExecute; }
            set { _accessExecute = value; }
        }

        [TaskAttribute("accessnoremoteexecute"),IisProperty]
        public bool AccessNoRemoteExecute {
            get { return _accessNoRemoteExecute; }
            set { _accessNoRemoteExecute = value; }
        }

        [TaskAttribute("accessnoremoteread"),IisProperty]
        public bool AccessNoRemoteRead {
            get { return _accessNoRemoteRead; }
            set { _accessNoRemoteRead = value; }
        }

        [TaskAttribute("accessnoremotescript"),IisProperty]
        public bool AccessNoRemoteScript {
            get { return _accessNoRemoteScript; }
            set { _accessNoRemoteScript = value; }
        }

        [TaskAttribute("accessnoremotewrite"),IisProperty]
        public bool AccessNoRemoteWrite {
            get { return _accessNoRemoteWrite; }
            set { _accessNoRemoteWrite = value; }
        }

        [TaskAttribute("accessread"),IisProperty]
        public bool AccessRead {
            get { return _accessRead; }
            set { _accessRead = value; }
        }

        [TaskAttribute("accesssource"),IisProperty]
        public bool AccessSource {
            get { return _accessSource; }
            set { _accessSource = value; }
        }

        [TaskAttribute("accessscript"),IisProperty]
        public bool AccessScript {
            get { return _accessScript; }
            set { _accessScript = value; }
        }

        [TaskAttribute("accessssl"),IisProperty]
        public bool AccessSsl {
            get { return _accessSsl; }
            set { _accessSsl = value; }
        }

        [TaskAttribute("accessssl128"),IisProperty]
        public bool AccesssSl128 {
            get { return _accessSsl128; }
            set { _accessSsl128 = value; }
        }

        [TaskAttribute("accesssslmapcert"),IisProperty]
        public bool AccessSslMapCert {
            get { return _accessSslMapCert; }
            set { _accessSslMapCert = value; }
        }

        [TaskAttribute("accesssslnegotiatecert"),IisProperty]
        public bool AccessSslNegotiateCert {
            get { return _accessSslNegotiateCert; }
            set { _accessSslNegotiateCert = value; }
        }

        [TaskAttribute("accesssslrequirecert"),IisProperty]
        public bool AccessSslRequireCert {
            get { return _accessSslRequireCert; }
            set { _accessSslRequireCert = value; }
        }

        [TaskAttribute("accesswrite"),IisProperty]
        public bool AccessWrite {
            get { return _accessWrite; }
            set { _accessWrite = value; }
        }

        [TaskAttribute("anonymouspasswordsync"),IisProperty]
        public bool AnonymousPasswordSync {
            get { return _anonymousPasswordSync; }
            set { _anonymousPasswordSync = value; }
        }
        /// <summary>Specify what type of application to create for this
        /// virtual directory. Possible values are <c>none</c>, 
<c>inprocess</c>,
        /// <c>pooled</c>, and <c>outofprocess</c>. The default is 
<c>pooled</c>.
        /// </summary>
        [TaskAttribute("appcreate")]
        public AppType AppCreate {
            get { return _apptype; }
            set { _apptype = value; }
        }

        [TaskAttribute("appallowclientdebug"),IisProperty]
        public bool AppAllowClientDebug {
            get { return _appAllowClientDebug; }
            set { _appAllowClientDebug = value; }
        }

        [TaskAttribute("appallowdebugging"),IisProperty]
        public bool AppAllowDebugging {
            get { return _appAllowDebugging; }
            set { _appAllowDebugging = value; }
        }

        [TaskAttribute("aspallowsessionstate"),IisProperty]
        public bool AspAllowSessionState {
            get { return _aspAllowSessionState; }
            set { _aspAllowSessionState = value; }
        }

        [TaskAttribute("aspbufferingon"),IisProperty]
        public bool AspBufferingOn {
            get { return _aspBufferingOn; }
            set { _aspBufferingOn = value; }
        }

        [TaskAttribute("aspenableapplicationrestart"),IisProperty]
        public bool AspEnableApplicationRestart {
            get { return _aspEnableApplicationRestart; }
            set { _aspEnableApplicationRestart = value; }
        }

        [TaskAttribute("aspenableasphtmlfallback"),IisProperty]
        public bool AspEnableAspHtmlFallback {
            get { return _aspEnableAspHtmlFallback; }
            set { _aspEnableAspHtmlFallback = value; }
        }

        [TaskAttribute("aspenablechunkedencoding"),IisProperty]
        public bool AspEnableChunkedEncoding {
            get { return _aspEnableChunkedEncoding; }
            set { _aspEnableChunkedEncoding = value; }
        }

        [TaskAttribute("asperrorstontlog"),IisProperty]
        public bool AspErrorsToNTLog {
            get { return _aspErrorsToNTLog; }
            set { _aspErrorsToNTLog = value; }
        }

        [TaskAttribute("aspenableparentpaths"),IisProperty]
        public bool AspEnableParentPaths {
            get { return _aspEnableParentPaths; }
            set { _aspEnableParentPaths = value; }
        }

        [TaskAttribute("aspenabletypelibcache"),IisProperty]
        public bool AspEnableTypelibCache {
            get { return _aspEnableTypelibCache; }
            set { _aspEnableTypelibCache = value; }
        }

        [TaskAttribute("aspexceptioncatchenable"),IisProperty]
        public bool AspExceptionCatchEnable {
            get { return _aspExceptionCatchEnable; }
            set { _aspExceptionCatchEnable = value; }
        }

        [TaskAttribute("asplogerrorrequests"),IisProperty]
        public bool AspLogErrorRequests {
            get { return _aspLogErrorRequests; }
            set { _aspLogErrorRequests = value; }
        }

        [TaskAttribute("aspscripterrorsenttobrowser"),IisProperty]
        public bool AspScriptErrorSentToBrowser {
            get { return _aspScriptErrorSentToBrowser; }
            set { _aspScriptErrorSentToBrowser = value; }
        }

        [TaskAttribute("aspthreadgateenabled"),IisProperty]
        public bool AspThreadGateEnabled {
            get { 
                if (this.Version != IISVersion.Five) {
                    throw new BuildException("Option only applies to IIS 5.x", 
Location);
                }
                return _aspThreadGateEnabled;
            }
            set { 
                if (this.Version != IISVersion.Five) {
                    throw new BuildException("Option only applies to IIS 5.x", 
Location);
                }
                _aspThreadGateEnabled = value; 
            }
        }

        [TaskAttribute("asptrackthreadingmodel"),IisProperty]
        public bool AspTrackThreadingModel {
            get { 
                if (this.Version != IISVersion.Five) {
                    throw new BuildException("Option only applies to IIS 5.x", 
Location);
                }
                return _aspTrackThreadingModel; 
            }
            set { 
                if (this.Version != IISVersion.Five) {
                    throw new BuildException("Option only applies to IIS 5.x", 
Location); 
                }
                _aspTrackThreadingModel = value; 
            }
        }

        [TaskAttribute("authanonymous"),IisProperty]
        public bool AuthAnonymous {
            get { return _authAnonymous; }
            set { _authAnonymous = value; }
        }

        [TaskAttribute("authbasic"),IisProperty]
        public bool AuthBasic {
            get { return _authBasic; }
            set { _authBasic = value; }
        }

        [TaskAttribute("authntlm"),IisProperty]
        public bool AuthNtlm {
            get { return _authNtlm; }
            set { _authNtlm = value; }
        }

        [TaskAttribute("authpersistsinglerequest"),IisProperty]
        public bool AuthPersistSingleRequest{
            get { return _authPersistSingleRequest; }
            set { _authPersistSingleRequest = value; }
        }

        [TaskAttribute("authpersistsinglerequestifproxy"),IisProperty]
        public bool AuthPersistSingleRequestIfProxy{
            get { 
                if (this.Version != IISVersion.Five) {
                    throw new BuildException("Option only applies to IIS 5.x", 
Location); 
                }
                return _authPersistSingleRequestIfProxy; }
            set { 
                if (this.Version != IISVersion.Five) {
                    throw new BuildException("Option only applies to IIS 5.x", 
Location);
                }
                _authPersistSingleRequestIfProxy = value; 
            }
        }

        [TaskAttribute("authpersistsinglerequestalwaysifproxy"),IisProperty]
        public bool AuthPersistSingleRequestAlwaysIfProxy{
            get { 
                if (this.Version != IISVersion.Five) {
                    throw new BuildException("Option only applies to IIS 5.x", 
Location); 
                }
                return _authPersistSingleRequestAlwaysIfProxy; 
            }
            set { 
                if (this.Version != IISVersion.Five) {
                    throw new BuildException("Option only applies to IIS 5.x", 
Location); 
                }
                _authPersistSingleRequestAlwaysIfProxy = value; 
            }
        }

        [TaskAttribute("cachecontrolnocache"),IisProperty]
        public bool CacheControlNoCache {
            get { return _cacheControlNoCache; }
            set { _cacheControlNoCache = value; }
        }

        [TaskAttribute("cacheisapi"),IisProperty]
        public bool CacheIsapi {
            get { return _cacheIsapi; }
            set { _cacheIsapi = value; }
        }

        [TaskAttribute("contentindexed"),IisProperty]
        public bool ContentIndexed {
            get { return _contentIndexed; }
            set { _contentIndexed = value; }
        }

        [TaskAttribute("cpuappenabled"),IisProperty]
        public bool CpuAppEnabled {
            get { 
                if (this.Version != IISVersion.Five) {
                    throw new BuildException("Option only applies to IIS 5.x", 
Location); 
                }
                return _cpuAppEnabled; 
            }
            set { 
                if (this.Version != IISVersion.Five) {
                    throw new BuildException("Option only applies to IIS 5.x", 
Location);
                }
                _cpuAppEnabled = value;
            }
        }

        [TaskAttribute("cpucgienabled"),IisProperty]
        public bool CpuCgiEnabled{
            get { 
                if (this.Version != IISVersion.Five) {
                    throw new BuildException("Option only applies to IIS 5.x", 
Location);
                }
                return _cpuCgiEnabled;
            }
            set {
                if (this.Version != IISVersion.Five) {
                    throw new BuildException("Option only applies to IIS 5.x", 
Location);
                }
                _cpuCgiEnabled = value;
            }
        }

        [TaskAttribute("createcgiwithnewconsole"),IisProperty]
        public bool CreateCgiWithNewConsole {
            get { return _createCgiWithNewConsole; }
            set { _createCgiWithNewConsole = value; }
        }

        [TaskAttribute("createprocessasuser"),IisProperty]
        public bool CreateProcessAsUser {
            get { return _createProcessAsUser; }
            set { _createProcessAsUser = value; }
        }

        [TaskAttribute("dirbrowseshowdate"),IisProperty]
        public bool DirBrowseShowDate {
            get { return _dirBrowseShowDate; }
            set { _dirBrowseShowDate = value; }
        }

        [TaskAttribute("dirbrowseshowextension"),IisProperty]
        public bool DirBrowseShowExtension {
            get { return _dirBrowseShowExtension; }
            set { _dirBrowseShowExtension = value; }
        }

        [TaskAttribute("dirbrowseshowlongdate"),IisProperty]
        public bool DirBrowseShowLongDate {
            get { return _dirBrowseShowLongDate; }
            set { _dirBrowseShowLongDate = value; }
        }

        [TaskAttribute("dirbrowseshowsize"),IisProperty]
        public bool DirBrowseShowSize {
            get { return _dirBrowseShowSize; }
            set { _dirBrowseShowSize = value; }
        }

        [TaskAttribute("dirbrowseshowtime"),IisProperty]
        public bool DirBrowseShowTime {
            get { return _dirBrowseShowTime; }
            set { _dirBrowseShowTime = value; }
        }

        [TaskAttribute("dontlog"),IisProperty]
        public bool DontLog {
            get { return _dontLog; }
            set { _dontLog = value; }
        }

        [TaskAttribute("enabledefaultdoc"),IisProperty]
        public bool EnableDefaultDoc {
            get { return _enableDefaultDoc; }
            set { _enableDefaultDoc = value; }
        }

        [TaskAttribute("enabledirbrowsing"),IisProperty]
        public bool EnableDirBrowsing {
            get { return _enableDirBrowsing; }
            set { _enableDirBrowsing = value; }
        }

        [TaskAttribute("enabledocfooter"),IisProperty]
        public bool EnableDocFooter {
            get { return _enableDocFooter; }
            set { _enableDocFooter = value; }
        }

        [TaskAttribute("enablereversedns"),IisProperty]
        public bool EnableReverseDns {
            get { return _enableReverseDns; }
            set { _enableReverseDns = value; }
        }

        [TaskAttribute("ssiexecdisable"),IisProperty]
        public bool SsiExecDisable {
            get { return _ssiExecDisable; }
            set { _ssiExecDisable = value; }
        }

        [TaskAttribute("uncauthenticationpassthrough"),IisProperty]
        public bool UncAuthenticationPassthrough {
            get { return _uncAuthenticationPassthrough; }
            set { _uncAuthenticationPassthrough = value; }
        }

        [TaskAttribute("aspscripterrormessage"),IisProperty]
        public string AspScriptErrorMessage {
            get { return _aspScriptErrorMessage; }
            set { _aspScriptErrorMessage = value; }
        }

        [TaskAttribute("defaultdoc"),IisProperty]
        public string DefaultDoc {
            get { return _defaultDoc; }
            set { _defaultDoc = value; }
        }

        #endregion Public Instance Properties

        private DirectoryEntry GetOrMakeNode(string basePath, string relPath, 
string schemaClassName) {
            if(DirectoryEntryExists(basePath+relPath)) {
                return new DirectoryEntry(basePath+relPath);
            }
            DirectoryEntry parent = new DirectoryEntry(basePath);
            parent.RefreshCache();
            DirectoryEntry child = parent.Children.Add(relPath.Trim('/'), 
schemaClassName);
            child.CommitChanges();
            parent.CommitChanges();
            parent.Close();
            return child;
        }

        private bool IsIisProperty(PropertyInfo prop) {
            return 
prop.GetCustomAttributes(typeof(IisPropertyAttribute),true).Length > 0;
        }
        private string AttributeName(PropertyInfo prop) {
            return 
((TaskAttributeAttribute)prop.GetCustomAttributes(typeof(TaskAttributeAttribute),true)[0]).Name;
        }
        // Set the IIS properties that have been specified
        private void SetIisProperties(DirectoryEntry vdir) {
            XmlElement taskElement = (XmlElement)this.XmlNode;
            foreach(PropertyInfo prop in this.GetType().GetProperties()) {
                if(!IsIisProperty(prop)) continue;
                string propertyName = AttributeName(prop);
                if( taskElement.HasAttribute(propertyName)) {
                    Log(Level.Debug,"setting {0} = 
{1}",propertyName,prop.GetValue(this,null));
                    vdir.Properties[propertyName][0] = prop.GetValue(this,null);
                } 
            }
        }

        private void CreateApplication(DirectoryEntry vdir) {
            Log(Level.Debug,"setting application type {0}",AppCreate);
            if(AppCreate == AppType.none) {
                vdir.Invoke("AppDelete");
            } else if(this.Version == IISVersion.Four) {
                vdir.Invoke("AppCreate",AppCreate == AppType.inprocess);
            } else {
                vdir.Invoke("AppCreate2",(int)AppCreate);
            }

        }
        #region Override implementation of Task

        protected override void ExecuteTask() {
            Log(Level.Info, "Creating/modifying virtual directory '{0}' on"
                + " '{1}'.", this.VirtualDirectory, this.Server);

            // ensure IIS is available on specified host and port
            this.CheckIISSettings();

            try {
                DirectoryEntry vdir = 
                    
GetOrMakeNode(this.ServerPath,this.VdirPath,"IIsWebVirtualDir");
                vdir.RefreshCache();

                vdir.Properties["Path"].Value = DirPath.FullName;
                this.CreateApplication(vdir);
                this.SetIisProperties(vdir);
  
                vdir.CommitChanges();
                vdir.Close();
            } catch (Exception ex) {
                throw new BuildException(StringFormat( 
                    "Error creating virtual directory '{0}' on '{1}'.", 
                    this.VirtualDirectory, this.Server), Location, ex);
            }
        }

        #endregion Override implementation of Task
    }

    /// <summary>
    /// Deletes a virtual directory from a given web site hosted on Internet 
    /// Information Server.
    /// </summary>
    /// <example>
    ///   <para>
    ///   Delete a virtual directory named <c>Temp</c> from the web site running
    ///   on port <c>80</c> of the local machine. If more than one web site is
    ///   running on port <c>80</c>, take the web site bound to the hostname 
    ///   <c>localhost</c> if existent or bound to no hostname otherwise.
    ///   </para>
    ///   <code>
    ///     <![CDATA[
    /// <deliisdir vdirname="Temp" />
    ///     ]]>
    ///   </code>
    /// </example>
    /// <example>
    ///   <para>
    ///   Delete a virtual directory named <c>Temp</c> from the website running 
    ///   on port <c>81</c> of machine <c>MyHost</c>.
    ///   </para>
    ///   <code>
    ///     <![CDATA[
    /// <deliisdir iisserver="MyHost:81" vdirname="Temp" />
    ///     ]]>
    ///   </code>
    /// </example>
    [TaskName("deliisdir")]
    public class DeleteIISDirTask : IISTaskBase {
        protected override void ExecuteTask() {
            Log(Level.Info, "Deleting virtual directory '{0}' on '{1}'.", 
                this.VirtualDirectory, this.Server);

            // ensure IIS is available on specified host and port
            this.CheckIISSettings();

            //make sure we dont delete the serverinstance ROOT
            if(this.VirtualDirectory.Length == 0) {
                throw new BuildException("The root of a web site can not be 
deleted",Location);
            }
            try {
                DirectoryEntry vdir = new 
DirectoryEntry(this.ServerPath+this.VdirPath);
                vdir.Parent.Children.Remove(vdir);
 
            } catch (Exception ex) {
                throw new BuildException(StringFormat(
                    "Error deleting virtual directory '{0}' on '{1}'.", 
                    this.VirtualDirectory, this.Server), Location, ex);
            }
        }
    }

    /// <summary>
    /// Lists the configuration settings of a specified virtual directory in a
    /// web site hosted on Internet Information Server.
    /// </summary>
    /// <example>
    ///   <para>
    ///   List the settings of a virtual directory named <c>Temp</c>.
    ///   </para>
    ///   <code>
    ///     <![CDATA[
    /// <iisdirinfo vdirname="Temp" />
    ///     ]]>
    ///   </code>
    /// </example>
    [TaskName("iisdirinfo")]
    public class IISDirInfoTask : IISTaskBase {
        protected override void ExecuteTask() {
            Log(Level.Info, "Retrieving settings of virtual directory '{0}'"
                + " on '{1}'.", this.VirtualDirectory, this.Server);

            // ensure IIS is available on specified host and port
            this.CheckIISSettings();

            try {
                // retrieve DirectoryEntry representing root of web site
                DirectoryEntry folderRoot = new DirectoryEntry(this.ServerPath);
                folderRoot.RefreshCache();

                // locate DirectoryEntry representing virtual directory
                DirectoryEntry newVirDir = 
folderRoot.Children.Find(this.VirtualDirectory, folderRoot.SchemaClassName);

                // output all properties of virtual directory
                foreach (string propertyName in 
newVirDir.Properties.PropertyNames) {
                    object propertyValue = 
newVirDir.Properties[propertyName].Value;

                    if (propertyValue.GetType().IsArray) {
                        Log(Level.Info, '\t' + propertyName + ":");
                        Array propertyValues = (Array) propertyValue;
                        foreach (object value in propertyValues) {
                            Log(Level.Info, "\t\t" + value.ToString());
                        }
                    } else {
                        Log(Level.Info, '\t' + propertyName + ": " 
                            + 
newVirDir.Properties[propertyName].Value.ToString());
                    }
                }

                newVirDir.Close();
                folderRoot.Close();
            } catch (BuildException) {
                // re-throw exception
                throw;
            } catch (Exception ex) {
                throw new BuildException(StringFormat(
                    "Error retrieving info for virtual directory '{0}' on 
'{1}'.", 
                    this.VirtualDirectory, this.Server), Location, ex);
            }
        }
    }
}

Reply via email to