Author Topic: MSBuild: building of DefineConstants value  (Read 3078 times)

0 Members and 1 Guest are viewing this topic.

Andrey Bushman

  • Swamp Rat
  • Posts: 864
MSBuild: building of DefineConstants value
« on: March 10, 2015, 08:06:58 AM »
I heed to extend the current value of DefineConstants property of my csproj-file. The string, which I want to add as a suffix, can be evaluated on C# through the such way:
Code - C#: [Select]
  1. Int32 min_year = 2009;
  2. Int32 target_year = 2015;      
  3. String result = String.Join(";", Enumerable.Range(min_year, target_year -
  4.   min_year + 1).Select(n=>"NEWER_THAN_AUTOCAD_" + (n - 1)).ToArray());
  5. // result:
  6. // NEWER_THAN_AUTOCAD_2008;NEWER_THAN_AUTOCAD_2009;
  7. // NEWER_THAN_AUTOCAD_2010;NEWER_THAN_AUTOCAD_2011;
  8. // NEWER_THAN_AUTOCAD_2012;NEWER_THAN_AUTOCAD_2013;
  9. // NEWER_THAN_AUTOCAD_2014
I need to do the same logic in the MSBuild code... I try to do it through this way:
Code - C#: [Select]
  1. $([System.String]::Join(`;`,[System.Linq.Enumerable]::Range(2009,[MSBuild]::Add(
  2. [MSBuild]::Subtract($(CAD_Year),2009),1)).Select(n=>[System.String]::Concat(
  3. "NEWER_THAN_AUTOCAD_"),[MSBuild]::Subtract(n,1).ToArray()))
But I get this expression in the DefineConstants property instead of evaluated value. How can I do the same in the MSBuild?

CADbloke

  • Bull Frog
  • Posts: 342
  • Crash Test Dummy
Re: MSBuild: building of DefineConstants value
« Reply #1 on: March 10, 2015, 11:09:46 PM »
It looks like you can't use System.Linq in there, see  https://msdn.microsoft.com/en-us/library/dd633440.aspx for a list of static classes you may use.

How to do this? Do you really want to? You will need to edit the files anyway when the min_year or target_year changes and I feel that plain text will be easier for you or somebody else to understand in a few years time than the function to generate the text. Using predictable text patterns also makes it easier to Grep replacements if you wanted to do it in bulk. If you use functions you also run the risk of MSBuild changes - they may add or remove functionality in the future and break it.

There's always System.Text.RegularExpressions.Regex (it is on the allowed list of classes) but I thought I was the only one crazy enough to go there.

To add more Constants to the existing ones use
Code - XML: [Select]
  1. <DefineConstants>$(DefineConstants);ThisIsAnotherConstant</DefineConstants>

The other alternative is to write a Console app that modifies the Project file. This one in PowerShell is a good example: https://github.com/owen2/AutomaticPackageRestoreMigrationScript/blob/master/migrateToAutomaticPackageRestore.ps1

CADbloke

  • Bull Frog
  • Posts: 342
  • Crash Test Dummy
Re: MSBuild: building of DefineConstants value
« Reply #2 on: March 10, 2015, 11:13:28 PM »
oh, wait. I am unfamiliar with MSBuild inline tasks but ... https://msdn.microsoft.com/en-us/library/dd722601.aspx