Search

Friday, January 04, 2008

NAnt, What Operating System is This?

I needed a quick way to tell what operating system the NAnt build file was running under. Why, one might wonder? Let's say you are installing a web application under IIS and you need the ASP.NET extension to be enabled. If you are wondering what that means, it's simple, with the introduction of IIS 6 (under Windows 2003), individual extensions (such as ASP or ASP.NET) can be enabled or disabled by the system administrator. So back to the why, you need to install a ASP.NET web application under IIS but to make things more complicated (as I often like to do), the ASP.NET extension might be disabled. So, you create a NAnt build file to do all the copy/setup steps for your web application installation (if you don't know what NAnt is, check out my other post titled Getting Started with NAnt - .NET Build Tool) but now you need to check if the ASP.NET extension is enabled. Before you can do that, you have to remember that only IIS 6 under Windows 2003 supports enabling/disabling extensions. If you try that under Windows XP (IIS 5) or Windows 2000 (IIS 5), your build file with barf. So to make a long story short, I need a test that will tell me if the NAnt build file is running under Windows 2003 or another operating system. So let's start with the NAnt build file that will output the current operating system:
<project name="testOS" default="runTest">
  <property name="operatingSystem" value="${operating-system::to-string(environment::get-operating-system())}" />

  <target name="runTest">
    <echo message="${operatingSystem}" />
  </target>
</project>

On Windows 2000 with Service Pack 4, that will output "Microsoft Windows NT 5.0.2195 Service Pack 4"
On Windows XP with Service Pack 2, that will output "Microsoft Windows NT 5.1.2600 Service Pack 2"
On Windows 2003 with Service Pack 2, that will output "Microsoft Windows NT 5.2.3790 Service Pack 2"
So now, to test if the NAnt build file is running under Windows 2003, we simply use "string::contains":
<if test="${string::contains(operatingSystem, 'Microsoft Windows NT 5.2')}">
  <echo message="This is Windows 2003" />
</if>

The complet NAnt build file to test the operating system should look like:
<project name="testOS" default="runTest" basedir=".">
  <property name="operatingSystem" value="${operating-system::to-string(environment::get-operating-system())}" />

  <target name="runTest">
    <if test="${string::contains(operatingSystem, 'Microsoft Windows NT 5.0')}">
      <echo message="This is Windows 2000" />
    </if>

    <if test="${string::contains(operatingSystem, 'Microsoft Windows NT 5.1')}">
      <echo message="This is Windows XP" />
    </if>

    <if test="${string::contains(operatingSystem, 'Microsoft Windows NT 5.2')}">
      <echo message="This is Windows 2003" />
    </if>
  </target>
</project>
// //]]>