Eric Kulcyk
Eric Kulcyk

Reputation: 279

How do I specify common source files and properties and have them appear in Visual Studio

I have a solution with many projects that would like to share source files and properties. If I put the sources files in, for instance, a common .props file, the source files affect the build but don't show up in Visual Studio. A short example is:

Scratch.csproj:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <ItemGroup>
    <Compile Include="Program.cs"/>
  </ItemGroup>

  <Import Project="a.props" />
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

A.props:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
    <Compile Include="a.cs"/>
  </ItemGroup>
</Project>

a.cs, Program.cs:

namespace Scratch
{
  public class A {}
}

This code will not compile because class A has been declared twice. However, the file a.cs appears nowhere in the visual studio solution. Is there a good fix for this so that we can have shared properties and source files that also appear in the solution? I saw one possibility being instead of a.props, using a.csproj and adding it as well to the solution. However, that too has problems. If you only instead on using some of the properties from that project (depending on conditions set), it won't be clear which source file or property goes to which project.

Upvotes: 3

Views: 2192

Answers (1)

Tom Blodget
Tom Blodget

Reputation: 20812

Visual Studio doesn't deal with the full flexibility of MSBuild files. Builds work because Visual Studio invokes MSBuild libraries but the project designers, Solution Explorer, etc can't represent things they haven't been designed for.

The common way to include shared source (that is, if you don't make a separate project of it), is to add files to the project as links: Add Exiting Item..., select the files, and instead of clicking the button, click the arrow on the right side of the button and adds links. Solution Explorer is designed to recognize linked files.

Properties should be fine in a shared Import file but note that Visual Studio doesn't recognize changes to Imports; you have to reload the project manually.

Upvotes: 3

Related Questions