Monday, July 24, 2006

Beginning Open-Source Programming

Having spent the last few years making good use of some of the many excellent open-source tools for .NET, I thought that it was long past time that I contributed a little something back. I don't claim to be a guru programmer, but the situation arose at work where I needed a bit of functionality that present in NAnt or NAntContrib. I've been playing around with Microsoft's WiX Toolset for creating MSI deployment packages, and as part of the process, a GUID is required to identify the particular product. You can do this easily enough in NAnt with a bit of script, thusly:

<script language="C#">

<code><![CDATA[

public static void ScriptMain(Project project)

{

project.Properties["mynew.guid"] =

Guid.NewGuid().ToString().ToUpper();

}

]]>

<code>

<script>

but when, as in my case, you are building four separate MSI packages and therefore need four GUIDs, it becomes a bit of a chore. So, I downloaded the source for NAntContrib, and knocked together the tiniest of tasks to do the same.

[TaskName("guid")]

public class GuidTask : Task {

private string _prefix = "new";

/// <summary>

/// The generated GUID will be stored in a property prefix.guid.

/// The default is new.

/// </summary>

[TaskAttribute("prefix", Required=false)]

[StringValidator(AllowEmpty=true)]

public string Prefix {

get { return _prefix; }

set { _prefix = StringUtils.ConvertEmptyToNull(value); }

}

/// <summary>

/// Executes the task.

/// </summary>

protected override void ExecuteTask() {

string guid = Guid.NewGuid().ToString().ToUpper();

Project.Properties[Prefix + ".guid"] = guid;

Log(Level.Info, "Generated new GUID {0} for property '{1}.guid'.", guid, Prefix);

}

I did say that it was tiny! Actually, that's about half of the code; the rest is pretty much all XML code comments for the API documentation. The result of this all is that the NAnt script to do what my first sample does is now:

<guid prefix="mynew" />

Personally, I'm rather pleased with it the whole process. It's quite enlightening being able to trawl through the various codebases for some high-profile open-source .NET applications; and definitely rather pleasing to be able to contribute to the community which provides such great tools. I'm hoping that I'll see the code included in 0.85-rc5.