Build with msbuild and dynamically set project references

I have a couple of projects which reference SQL Server assemblies. With SQL Server 2005 and SQL Server 2008 I am currently maintaining 2 project files which point to the same source files and the only difference is the references to the SQL Server assemblies.

Is there some way that I can only maintain one project and dynamically specify the references in my build script?


Solution 1:

Searching for a solution to the same problem you had I came to the proposed solution of having a Condition on the ItemGroup. But this had a side effect because in Visual Studio references I could see both references, which also impacted ReSharper.

I finally use a Choose When Otherwise and I don't have any issue anymore with ReSharper and Visual Studio showing two References.

<Choose>
  <When Condition=" '$(Configuration)' == 'client1DeployClickOnce' ">
    <ItemGroup>
        <ProjectReferenceInclude="..\client1\app.Controls\app.Controls.csproj">
        <Project>{A7714633-66D7-4099-A255-5A911DB7BED8}</Project>
        <Name>app.Controls %28Sources\client1\app.Controls%29</Name>
      </ProjectReference>
    </ItemGroup>
  </When>
  <Otherwise>
    <ItemGroup>
      <ProjectReference Include="..\app.Controls\app.Controls.csproj">
        <Project>{2E6D4065-E042-44B9-A569-FA1C36F1BDCE}</Project>
        <Name>app.Controls %28Sources\app.Controls%29</Name>
      </ProjectReference>
    </ItemGroup>
  </Otherwise>
</Choose>

You might read more about it on my blog post: [ProjectReference with Condition in your MSBuild project file][https://laurentkempe.com/2009/12/03/ProjectReference-with-Condition-in-your-MSBuild-project-files/]

Solution 2:

Every MSBuild element (ok almost every) can have a Condition associated with it. What I would suggest is that you edit the project file (which is an MSBuild file itself) and place all the SQL server references in an ItemGroup which has a condition on it for instance:

  <ItemGroup Condition="'$(SqlServerTargetEdition)'=='2005'">
    <!-- SQL Server 2005 References here -->
    <Reference Include="..."/>
  </ItemGroup>

And another ItemGroup for Sql server 2008:

  <ItemGroup Condition="'$(SqlServerTargetEdition)'=='2008'">
    <!-- SQL Server 2008 References here -->
    <Reference Include="..."/>
  </ItemGroup>

You should provide a default value for the property SqlServerTargetEdition before those items are declared. Then at the command line you can override that value using the /p switch when invoking msbuild.exe.

Sayed Ibrahim Hashimi

My Book: Inside the Microsoft Build Engine : Using MSBuild and Team Foundation Build