File String Replacements using MSBuild in Visual Studio

In this article I am going to talk through three scenarios where string replacement is necessary within website files (MVC) or assets (SharePoint Solution). This should give a good base line to work from and allow you to see a good business case for carry out this task in this way.

The Scenarios

All of the scenarios revolve around the need to have a specific base URL for global CSS and JS links in our sites and projects, whilst keeping in mind CI. Let’s take a look:

  • SharePoint Sandboxed Solution – Master Pages and Page Layouts
  • MVC Website (hosted on Azure) – Linked deployment file
  • MVC Website (hosted on Azure) – Views

The Business Case

When you deploy SharePoint projects or publish an MVC website from Visual Studio, you will more than likely need to do so to different environments (ALM) and when you want to hook things up to a global repository for the given environment, this is where things can get tricky. The business case here, is to be able to point at the correct global repository for the given environment dynamically, as part of the publishing process and what’s even better is, we will make it so that it works with CI as well.

Getting things Ready

The first thing you need to do is get the community MS Build Tasks from GitHub ( You can do this by downloading them directly or via the NuGet console on the relevant project in Visual Studio:

If you are working in a SharePoint project you will need to read through the following guide created by Chris O’Brien. This will allow you to setup the basic build configuration(s), we follow a similar route that Chris has taken with both of our approaches:

SharePoint Sandboxed Solution

Now it’s time to amend the project file with the specific lines of XML which will tell MSBuild to replace our special string token with the correct base URL for how you are publishing the project. I have written up how you can do this and you can get this on GitHub now:

MVC Website Hosted on Azure

The process for websites is slightly different. We need to use the publishing profile as our guide so we will stick with the Debug and Release build configs. The important differences with this target are that we are hooking into a Web Publish target event and not a SharePoint Tools one. Again, this has all been detailed out over on GitHub:

File String Replacements using MSBuild in Visual Studio
Tagged on:                 

Leave a Reply

%d bloggers like this: