Conditional Includes with Visual Studio Project Files

Often during development your application may be set to connect to a dev or test set of services. When you go to release your application you’ll then switch to point to the production or live set of services. A common way to do this is to define a constant which is the base url for the services and then use the DEBUG conditional compilation constant to control what the value of the constant is. For example

public static class Contants
{
#if DEBUG
    public const string BaseUrl = "
http://test.apiservice.com";
#else
    public const string BaseUrl = "
http://production.apiservice.com";
#endif
}

This is a simple but effective strategy to control which services are used based on build configuration. If you select a Debug build, you’ll connect to the test services; the Release build will connect to the production services. This strategy also keeps the differences between a debug and release build to a minimum, since all that is changing is the base url for the service. However, this simplicity can lead to some confusion as it can be hard to tell whether you’re using a debug or release build of an application.

One work around for this is to surface up the base url in the UI, for example in the About page, so that you can tell which version of the app is running. Another alternative is to customise the default tile for the application so that it is clear which build is installed. This can be done by dynamically switching between multiple image files during the build process.

Let’s start by creating our two live tiles (one for debug, one for release):

FlipCycleTileMedium FlipCycleTileMedium

Create the following folder structure in the solution folder:

DefaultTiles
         Debug
               FlipCycleTileMedium.png
         Release
               FlipCycleTileMedium.png

Place the created images into the appropriate folder – note that they should have the same file name.

In Visual Studio, right-click on the project node and select “Unload Project”. Then right-click the project node again and select Edit. Locate where the live tile image is included eg:

<Content Include="AssetsTilesFlipCycleTileMedium.png">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>

And replace it with the following xml

<Content Include="..DefaultTiles$(Configuration)FlipCycleTileMedium.png">
  <Link>AssetsTilesFlipCycleTileMedium.png</Link>
  <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>

This xml links in the appropriate file based on the $(Configuration) parameter. Save and reload the project. Now as you switch build configurations you’ll see that the appropriate live tile image is included. You can check this by either deploying the application to a device/emulator, or by checking the output folder where you’ll see the appropriate file appear after the build has completed.

Leave a comment