Hi!

I have managed to write those two tasks we've been talking about today
in the morning and create some accompanying unit test.

I attach four files:
+ WriteRegistryTask.cs (I have put it in NAntContrib\src\Tasks\Win32 folder),
+ WriteRegistryTaskTest.cs (I have put it in
NAntContrib\tests\Tasks\Win32 folder),
+ DeleteRegistryTask.cs (I have put it in NAntContrib\src\Tasks\Win32 folder),
+ DeleteRegistryTaskTest.cs (I have put it in
NAntContrib\tests\Tasks\Win32 folder).

I hope you'll find it useful :).

Best regards!
Marcin
// NAnt - A .NET build tool
// Copyright (C) 2002 Scott Hernandez
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// Marcin Hoppe ([EMAIL PROTECTED])

using System;
using System.Globalization;
using System.Security.Permissions;

using Microsoft.Win32;

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

[assembly: RegistryPermissionAttribute(SecurityAction.RequestMinimum , 
Unrestricted=true)]

namespace NAnt.Contrib.Tasks.Win32 {
        /// <summary>
        /// Deletes a specified key or value from the Windows Registry.
        /// </summary>
        /// <example>
        /// <para>Delete a single value from the Registry.</para>
        ///   <code>
        ///     <![CDATA[
        /// <deleteregistry key="SOFTWARE\NAnt-Test\SampleValue" 
hive="LocalMachine" />
        ///     ]]>
        ///   </code>
        /// <para>Delete a single key (and all its subkeys) from the 
Registry.</para>
        ///   <code>
        ///     <![CDATA[
        /// <deleteregistry key="SOFTWARE\NAnt-Test\*" hive="LocalMachine" />
        ///     ]]>
        ///   </code>
        /// </example>
        [TaskName("deleteregistry")]
        public class DeleteRegistryTask : Task {
                #region Private Instance Fields

                private string          _regKey = null;
                private string          _regKeyValueName = null;
                private RegistryHive[]  _regHive = new RegistryHive[] { 
RegistryHive.LocalMachine };
                private string          _regHiveString = 
RegistryHive.LocalMachine.ToString();

                #endregion Private Instance Fields

                #region Public Instance Properties

                /// <summary>
                /// The registry key to delete, including the path.
                /// </summary>
                /// <remarks>
                /// If the last component of the path is *, the whole subkey is 
removed.
                /// </remarks>
                /// <example>
                /// SOFTWARE\NAnt-Test
                /// </example>
                [TaskAttribute("key", Required = true)]
                [StringValidator(AllowEmpty = false)]
                public virtual string RegistryKey 
                {
                        get { return _regKey; }
                        set 
                        {
                                string key = value;
                                if (value.StartsWith("\\")) 
                                {
                                        key = value.Substring(1);
                                }
                                string[] pathParts = 
key.Split("\\".ToCharArray(0, 1)[0]);
                                //split the key/path apart.
                                _regKeyValueName = pathParts[pathParts.Length - 
1];
                                _regKey = key.Substring(0, (value.Length - 
_regKeyValueName.Length));
                        }
                }

                /// <summary>
                /// Space separated list of registry hives to search for <see 
cref="RegistryKey" />.
                /// For a list of possible values, see <see cref="RegistryHive" 
/>. The 
                /// default is <see cref="RegistryHive.LocalMachine" />.
                /// </summary>
                /// <remarks>
                /// <seealso cref="RegistryHive" />
                /// </remarks>
                [TaskAttribute("hive")]
                public virtual string RegistryHiveName 
                {
                        get { return _regHiveString; }
                        set 
                        {
                                _regHiveString = value;
                                string[] tempRegHive = _regHiveString.Split(" 
".ToCharArray()[0]);
                                _regHive = 
(RegistryHive[])Array.CreateInstance(typeof(RegistryHive), tempRegHive.Length);
                                for (int x = 0; x < tempRegHive.Length; x++) 
                                {
                                        _regHive[x] = 
(RegistryHive)Enum.Parse(typeof(RegistryHive), tempRegHive[x], true);
                                }
                        }
                }

                #endregion Public Instance Properties

                #region Override implementation of Task

                /// <summary>
                /// Delete the specified value or key from the Registry.
                /// </summary>
                protected override void ExecuteTask() {
                        if (_regKey == null) {
                                throw new BuildException("Registry key 
missing!");
                        }

                        try {
                                foreach (RegistryHive hive in _regHive) {
                                        RegistryKey regKey = GetHiveKey(hive);

                                        if(regKey != null) {
                                                if(_regKeyValueName == "*") {
                                                        // Delete the whole 
subtree.
                                                        
regKey.DeleteSubKeyTree(_regKey);

                                                        string infoMessage = 
string.Format(     CultureInfo.InvariantCulture,
                                                                                
                                                "{0} deleted.",
                                                                                
                                                _regKey);
                                                        Log(Level.Info, 
infoMessage);
                                                } else  {
                                                        // Delete only the 
specified value.
                                                        RegistryKey subKey = 
regKey.CreateSubKey(_regKey);

                                                        if(subKey != null) {
                                                                
subKey.DeleteValue(_regKeyValueName, true);

                                                                string 
infoMessage = string.Format(     CultureInfo.InvariantCulture,
                                                                                
                                                        "{0}\\{1} deleted.",
                                                                                
                                                        _regKey,
                                                                                
                                                        _regKeyValueName);
                                                                Log(Level.Info, 
infoMessage);
                                                        }
                                                }
                                        }       
                                }
                        } 
                        catch (Exception e) {
                                throw new BuildException("Deleting registry key 
or value failed!", e);
                        }
                }

                #endregion Override implementation of Task

                #region Protected Instance Methods

                /// <summary>
                /// Returns the key for a given registry hive.
                /// </summary>
                /// <param name="hive">The registry hive to return the key 
for.</param>
                /// <returns>
                /// The key for a given registry hive.
                /// </returns>
                protected RegistryKey GetHiveKey(RegistryHive hive) 
                {
                        switch (hive) 
                        {
                                case RegistryHive.LocalMachine:
                                        return Registry.LocalMachine;
                                case RegistryHive.Users:
                                        return Registry.Users;
                                case RegistryHive.CurrentUser:
                                        return Registry.CurrentUser;
                                case RegistryHive.ClassesRoot:
                                        return Registry.ClassesRoot;
                                default:
                                        Log(Level.Verbose, "Registry not found 
for {0}.", hive.ToString());
                                        return null;
                        }
                }

                #endregion Protected Instance Methods
        }
}
// NAnt - A .NET build tool
// Copyright (C) 2002 Scott Hernandez
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// Marcin Hoppe ([EMAIL PROTECTED])

using System;
using System.Globalization;
using System.Security.Permissions;

using Microsoft.Win32;

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

[assembly: RegistryPermissionAttribute(SecurityAction.RequestMinimum , 
Unrestricted=true)]

namespace NAnt.Contrib.Tasks.Win32 {
    /// <summary>
    /// Writes a specified value to the Windows Registry.
    /// </summary>
    /// <example>
    /// <para>Write a single value to the Registry.</para>
    ///   <code>
    ///     <![CDATA[
    /// <writeregistry value="A test value" 
key="SOFTWARE\NAnt-Test\SampleValue" hive="LocalMachine" />
    ///     ]]>
    ///   </code>
    /// </example>
    [TaskName("writeregistry")]
    public class WriteRegistryTask : Task {
        #region Private Instance Fields

        private string          _regKeyValue = null;
        private string          _regKey = null;
        private string          _regKeyValueName = null;
        private RegistryHive[]  _regHive = new RegistryHive[] { 
RegistryHive.LocalMachine };
        private string          _regHiveString = 
RegistryHive.LocalMachine.ToString();

        #endregion

        #region Public Instance Properties

        /// <summary>
        /// Value to be stored in the Registry.
        /// </summary>
        [TaskAttribute("value", Required=true)]
        public virtual string RegistryKeyValue {
            get { return _regKeyValue; }
            set { _regKeyValue = value; }
        }

        /// <summary>
        /// The registry key to write to, including the path.
        /// </summary>
        /// <example>
        /// SOFTWARE\NAnt-Test
        /// </example>
        [TaskAttribute("key", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public virtual string RegistryKey {
            get { return _regKey; }
            set {
                string key = value;
                if (value.StartsWith("\\")) {
                    key = value.Substring(1);
                }
                string[] pathParts = key.Split("\\".ToCharArray(0, 1)[0]);
                //split the key/path apart.
                _regKeyValueName = pathParts[pathParts.Length - 1];
                _regKey = key.Substring(0, (value.Length - 
_regKeyValueName.Length));
            }
        }

        /// <summary>
        /// Space separated list of registry hives to search for <see 
cref="RegistryKey" />.
        /// For a list of possible values, see <see cref="RegistryHive" />. The 
        /// default is <see cref="RegistryHive.LocalMachine" />.
        /// </summary>
        /// <remarks>
        /// <seealso cref="RegistryHive" />
        /// </remarks>
        [TaskAttribute("hive")]
        public virtual string RegistryHiveName {
            get { return _regHiveString; }
            set {
                _regHiveString = value;
                string[] tempRegHive = _regHiveString.Split(" 
".ToCharArray()[0]);
                _regHive = 
(RegistryHive[])Array.CreateInstance(typeof(RegistryHive), tempRegHive.Length);
                for (int x = 0; x < tempRegHive.Length; x++) {
                    _regHive[x] = 
(RegistryHive)Enum.Parse(typeof(RegistryHive), tempRegHive[x], true);
                }
            }
        }

        #endregion Public Instance Properties

        #region Override implementation of Task

        /// <summary>
        /// Write the specified value to the Registry.
        /// </summary>
        protected override void ExecuteTask() {
            if (_regKey == null) {
                throw new BuildException("Missing registry key!");
            }

            if (_regKeyValue == null) {
                throw new BuildException("Missing value!");
            }

            try {
                foreach (RegistryHive hive in _regHive) {
                    RegistryKey regKey = GetHiveKey(hive);

                    if (regKey != null) {
                        RegistryKey newKey = regKey.CreateSubKey(_regKey);

                        if (newKey != null) {
                            newKey.SetValue(_regKeyValueName, _regKeyValue);

                                                        string infoMessage = 
string.Format(     CultureInfo.InvariantCulture,
                                                                                
                                                "{0}{1} set to {2}.",
                                                                                
                                                _regKey,
                                                                                
                                                _regKeyValueName,
                                                                                
                                                _regKeyValue);
                                                        Log(Level.Info, 
infoMessage);
                        }
                    }
                }
            } catch (Exception e) {
                throw new BuildException("Writing to registry failed!", e);
            }
        }

        #endregion

        #region Protected Instance Methods

        /// <summary>
        /// Returns the key for a given registry hive.
        /// </summary>
        /// <param name="hive">The registry hive to return the key for.</param>
        /// <returns>
        /// The key for a given registry hive.
        /// </returns>
        protected RegistryKey GetHiveKey(RegistryHive hive) {
            switch (hive) {
                case RegistryHive.LocalMachine:
                    return Registry.LocalMachine;
                case RegistryHive.Users:
                    return Registry.Users;
                case RegistryHive.CurrentUser:
                    return Registry.CurrentUser;
                case RegistryHive.ClassesRoot:
                    return Registry.ClassesRoot;
                default:
                    Log(Level.Verbose, "Registry not found for {0}.", 
hive.ToString());
                    return null;
            }
        }

        #endregion Protected Instance Methods
    }
}
// NAnt - A .NET build tool
// Copyright (C) 2001-2005 Gert Driesen
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// Marcin Hoppe ([EMAIL PROTECTED])

using System;

using Microsoft.Win32;

using NUnit.Framework;

using Tests.NAnt.Contrib;

namespace Tests.NAnt.Contrib.Win32.Tasks {
        /// <summary>
        /// Tests the DeleteRegistry task.
        /// </summary>
        [TestFixture]
        public class DeleteRegistryTaskTest : BuildTestBase {

                private string _regKey = "Software\\NAnt-Test";
                private string _regValueName = "SampleValue";

                [SetUp]
                protected override void SetUp() {
                        base.SetUp ();

                        // Create a registry key for testing.
                        RegistryKey r = 
Registry.LocalMachine.CreateSubKey(_regKey);
                        r.SetValue(_regValueName, _regValueName);
                }

                [TearDown]
                protected override void TearDown() {
                        base.TearDown ();

                        // Delete created subkey (a fallback).
                        Registry.LocalMachine.DeleteSubKey(_regKey, false);
                }

                [Test]
                public void Test_DeleteRegistryKey() {
                        Assert.IsTrue(Registry.LocalMachine.OpenSubKey(_regKey) 
!= null);

                        string _xml = @"
                                        <project>
                                                <deleteregistry 
key='Software\NAnt-Test\*' hive='LocalMachine' />
                                        </project>";

                        RunBuild(_xml);

                        Assert.IsTrue(Registry.LocalMachine.OpenSubKey(_regKey) 
== null);
                }

                [Test]
                public void Test_DeleteRegistryKeyValue() {
                        
Assert.IsTrue(Registry.LocalMachine.OpenSubKey(_regKey).GetValue(_regValueName) 
!= null);

                        string _xml = @"
                                        <project>
                                                <deleteregistry 
key='Software\NAnt-Test\SampleValue' hive='LocalMachine' />
                                        </project>";

                        RunBuild(_xml);

                        
Assert.IsTrue(Registry.LocalMachine.OpenSubKey(_regKey).GetValue(_regValueName) 
== null);
                }
        }
}
// NAnt - A .NET build tool
// Copyright (C) 2001-2005 Gert Driesen
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// Marcin Hoppe ([EMAIL PROTECTED])

using System;

using Microsoft.Win32;

using NUnit.Framework;

using Tests.NAnt.Contrib;

namespace Tests.NAnt.Contrib.Win32.Tasks {
        /// <summary>
        /// Tests the WriteRegistry task.
        /// </summary>
        [TestFixture]
        public class WriteRegistryTaskTest : BuildTestBase {
                [SetUp]
                protected override void SetUp() {
                        base.SetUp ();
                }

                [TearDown]
                protected override void TearDown() {
                        base.TearDown();
                }

                [Test]
                public void Test_WriteRegistry() {
                        string _xml = @"
                                        <project>
                                                <property name='sample.value' 
value='sample value' />
                                                <writeregistry 
value='${sample.value}' key='Software\NAnt-Test\Sample' hive='LocalMachine' />
                                                <readregistry 
property='read.value' key='Software\NAnt-Test\Sample' hive='LocalMachine' />
                                                <deleteregistry 
key='Software\NAnt-Test\*' hive='LocalMachine' />
                                                <fail 
unless='${sample.value==read.value}' />
                                        </project>";

                        RunBuild(_xml);
                }
        }
}

Reply via email to