blogs.conchango.com

welcome to the conchango blogging site
Welcome to blogs.conchango.com Sign in | Join | Help
in Search

Stuart Preston's Blog

Mostly about Visual Studio Team System, Team Foundation Server, Engineering Practices and Application Lifecycle Management.

Dynamic C# code execution inside an MSBuild script.

One thing Powershell has that MSBuild hasn't is a scripting engine that can access the .NET core libraries directly.  For example, in Powershell you could use the following function to get the current day of the week and assign it to a variable:

$a = (get-date).dayofweek

In the MSBuild world we are restricted to writing a custom task to access the .NET core libraries, but I thought I'd have a go at writing a stepping stone when you just want to access .NET from within MSBuild without having to compile anything.  The result is essentially a fusion of a basic MSBuild custom task and CodeDom technology and the source code is attached. 

Here is a simple example of its usage:

This script simply returns the Day of the Week and assigns it to the $(DynamicCodeResult) property so it could be later used in the script.

I realised I needed to add a way of injecting references into the code so it would compile (for example if I wanted to use the System.Xml namespace).  So I added this support, resulting in the following slightly more sophisticated example:

Simply, this piece of code loops through an RSS feed and pulls out the title of each post.  Note the additional "Using" and "ReferencedAssemblies" attributes on the DynamicCode task.  I'm sure you get the idea. 

I've only supported C# and a return type of string for now from the dynamically executed code but the source is attached so feel free to make some customisations and leave a comment on how you are using it.

Published 24 June 2007 20:56 by Stuart.Preston
Attachment(s): Conchango.MSBuild.Tasks.DynamicCode.zip

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

 

Francis Norton said:

Since you mention Powershell, did you consider writing a Powershell MsBuild task that would accept and execute a scriptblock? If so, any special reason for deciding against, or was it basically the lower learning curve and installation requirements of sticking with C#?
July 26, 2007 10:51
 

Stuart.Preston said:

I thought about it but despite the easy access to .NET objects, I wanted something that was portable and didn't rely on any other dependencies being installed besides the .NET Framework.

July 26, 2007 19:24

Leave a Comment

(required) 
(optional)
(required) 
Submit
Powered by Community Server (Personal Edition), by Telligent Systems