Search code examples
c#.netvisual-studio.net-coremsbuild

Detecting if build is launched from Visual Studio or CI (or better: when it uses normal dotnet or .NET framework)


I have a monorepo with multiple projects. I am building either from Visual Studio, or from the CI. From the CI, I just use "dotnet build". From Visual Studio I don't know how it works.

Some of my projects have COM References. It builds with Visual Studio. But it refuses to build with "dotnet build". I have code to adapt to either case, so I wanted to use preprocessor directives to make selection in code depending on how the projects are built...

It turns out it is really complicated.

In .csproj files I tried to do:

<!-- Check if we are in Visual Studio -->
<PropertyGroup Condition="'$(VisualStudioVersion)' != ''">
    <IsFullMsBuild>true</IsFullMsBuild>
    <DefineConstants>FULL_MSBUILD</DefineConstants>
</PropertyGroup>

<!-- Explicitly disable IsFullMsBuild when using dotnet build -->
<PropertyGroup Condition="'$(UsingMicrosoftNETSdk)' == 'true'">
    <IsFullMsBuild>false</IsFullMsBuild>
</PropertyGroup>

<!-- COMReference only included for full MSBuild -->
<ItemGroup Condition="'$(IsFullMsBuild)' == 'true'">
    <COMReference Include="SpatialAnalyzerSDK">
        ...
    </COMReference>
</ItemGroup>

But, FULL_MSBUILD directive is wrong.

Is there a way to achieve what I want ?

The goal of this, is to be able to build projects as always from Visual Studio, and in addition to have a stripped down version for CI with "dotnet build" so I can run tests on parts which do not need rely on COM...


Solution

  • If you want to run a build from Visual Studio or CI based on specific condition to make a stripped down version for CI with "dotnet build", you can use the property $(BuildingInsideVisualStudio)

    This document says,

    When building inside Visual Studio, the property $(BuildingInsideVisualStudio) is set to true. This can be used in your project or .targets files to cause the build to behave differently.

        <PropertyGroup>
            <MyProperty Condition="'$(BuildingInsideVisualStudio)' == 'true'">This build is done by VS</MyProperty>
            <MyProperty Condition="'$(BuildingInsideVisualStudio)' != 'true'">This build is done from command line of by CI</MyProperty>
        </PropertyGroup>
    
    
        <!-- COMReference only included for build in Visual Studio -->
        <ItemGroup Condition="'$(BuildingInsideVisualStudio)' == 'true'">
            <COMReference Include="SpatialAnalyzerSDK">
                ...
            </COMReference>
        </ItemGroup>