J-P
J-P

Reputation: 403

How to get property value of a project file using msbuild

Using MSBuild I include a solution>

<ItemGroup>
    <ProjectToBuild Include="$(SVNLocalPath)\$(SolutionName)"> </ProjectToBuild>
</ItemGroup>

I need to include all the *.csproj file from the solution with the condition of the proj file contain or define a property; for example if x.csproj contain a defined property "TestProjectType" would like to include the project into my itemGroup

something like this

<Target Name = "TestProperties">
    <Message Text="TestProperties"/>
    <ItemGroup>
        <AllProj Include="$(SVNLocalPath)\*.csproj"/>
        <AllTestProj Include="%(AllProj.Identity)" Condition="%(AllProj.ProjectTypeGuids)=={3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"/>
    </ItemGroup>
    <Message Text="@(AllTestProj )"/>
</Target>

Thanks

Upvotes: 3

Views: 3454

Answers (1)

starian chen-MSFT
starian chen-MSFT

Reputation: 33698

You can achieve that through custom task.

A simple sample to check a property (test) in all projects exclude current project of current solution:

<UsingTask TaskName="GetPropertyTask" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v12.0.dll">
    <ParameterGroup>
      <ProjectFile ParameterType="System.String" Required="true" />  
      <BuildOutput ParameterType="System.String[]" Output="true" />
    </ParameterGroup>
    <Task>
      <Reference Include="System.Xml"/>
      <Reference Include="Microsoft.Build"/>
      <Using Namespace="Microsoft.Build" />
      <Using Namespace="Microsoft.Build.Evaluation" />
      <Using Namespace="Microsoft.Build.Utilities" />
      <Code Type="Fragment" Language="cs">
          <![CDATA[

        var properties = new Dictionary<string, string>
        {
          { "Configuration", "$(Configuration)" },
          { "Platform", "$(Platform)" }
        };
        //Log.LogMessage(MessageImportance.High, "customLog");
        // Log.LogMessage(MessageImportance.High, ProjectFile);

        var collection = new ProjectCollection(properties);
        var project = collection.LoadProject(ProjectFile);
       ProjectProperty pp = project.Properties.Where(p => p.Name == "MyCustomProperty").FirstOrDefault();
            string customValue = pp==null?"empty":pp.EvaluatedValue;
       BuildOutput = new String[] { customValue };
      ]]></Code>
    </Task>
  </UsingTask>
  <Target Name="AfterBuild">
    <GetPropertyTask ProjectFile="%(ProjectToScan.FullPath)">
      <Output ItemName="ProjectToScanOutput" TaskParameter="BuildOutput"/>
    </GetPropertyTask>
    <Message Text="ClassLibrary1" Importance="high"  Condition="'%(ProjectToScanOutput.Identity)' == 'test'" />
  </Target>

More information, please refer to this article.

Upvotes: 3

Related Questions