tags:

views:

1541

answers:

4

I'm trying to make a reusable target in my MSBuild file so I can call it multiple times with different parameters.

I've got a skeleton like this:

<Target Name="Deploy">
  <!-- Deploy to a different location depending on parameters -->
</Target>

<Target Name="DoDeployments">
  <CallTarget Targets="Deploy">
    <!-- Somehow indicate I want to deploy to dev -->
  </CallTarget>

  <CallTarget Targets="Deploy">
    <!-- Somehow indicate I want to deploy to testing -->
  </CallTarget>
</Target>

But I can't work out how to allow parameters to be passed into the CallTarget, and then in turn the Target itself.

A: 

There might be a better way to do this in MSBuild, but in Ant, I would use global properties to carry information from one task to the next. It was a lousy solution, but I didn't see a better way at the time. You should be able to do this in MSBuild, but bear in mind that you will need to use the CreateProperty task to dynamically assign a property.

On the other hand, it's pretty easy to implement tasks in C# (or VB or whatever). Maybe that's a better solution for you.

Daniel Yankowsky
+5  A: 

Hi, MSBuild targets aren't designed to receive parameters. Instead, they use the properties you define for them.

<PropertyGroup>
  <Environment>myValue</Environment>
</PropertyGroup>
<Target Name="Deploy">
  <!-- Use the Environment property -->
 </Target>

However, a common scenario is to invoke a Target several times with different parameters (i.e. Deploy several websites). In that case, I use the MSBuild "MSBuild" task and send the "parameters" as Properties:

<Target Name="DoDeployments">
     <MSBuild Projects ="$(MSBuildProjectFullPath)"
        Properties ="VDir=MyWebsite;Path=C:\MyWebsite;Environment=$(Environment)"
        Targets="Deploy" />

     <MSBuild Projects ="$(MSBuildProjectFullPath)"
        Properties ="VDir=MyWebsite2;Path=C:\MyWebsite2;Environment=$(Environment)"
        Targets="Deploy" />
</Target>

$(MSBuildProjectFullPath) is the fullpath of the current MSBuild script in case you don't want to send "Deploy" to another file.

Hope this helps!

ocenteno
+2  A: 

I would be very careful thinking of MSBuild in terms similar to a procedural progamming language. It's designed to behave differently.

Sayed Ibrahim Hashimi
A: 
    <CreateProperty
        Value="file1">
        <Output
            TaskParameter="Value"
            PropertyName="filename" />
    </CreateProperty>
    <CallTarget Targets="Deploy"/>
    <Message Text="$(filename)"/>
    <CreateProperty
        Value="file2">
        <Output
            TaskParameter="Value"
            PropertyName="filename" />
    </CreateProperty>
    <Message Text="$(filename)"/> 
    <CallTarget Targets="Deploy"/>
Ming Jia
CreateProperty has been depricated in V4. Use PropertyGroup within a Target instead. Ref: http://msdn.microsoft.com/en-us/library/ms171458.aspx
WooWaaBob