Quick Tip: Aborting builds in Visual Studio based on file contents

Quick TipRemember a little while back when I had that problem with Entity Framework and SQL Server 2005/2008 databases? Well, it raised it’s ugly head again, and I was looking for a way to detect our error. Fortunately, we can setup a pre-build event to detect the bug and stop the process from going further.

Visual Studio has a wonderful little feature in the project settings for pre-build and post-build events. Mainly they are for running batch scripts to copy/move files or other small things. However, since we have the full featured batch command script at our disposal, we can do a quick file content check and abort if we don’t find what we’re expecting.

Open your solution in Visual Studio, right click on the project and select “Properties”. From there, click the tab that says “Build Events.” You’ll see something like this:

Build Events Screen

From here, either click the “Edit Pre-build” button or you can type directly into the window. Here’s the basic format of what you need your script to say

findstr /c:"[STRING TO FIND]" "$(SolutionDir)[FILE NAME]" >nul 2>&1
if errorlevel 1 echo [YOUR ERROR MESSAGE HERE].
view raw gistfile1.bat hosted with ❤ by GitHub

In my case, I’m checking my cptt.edmx file in my DAL folder to make sure that the ProviderManifestToken value is set to 2005. My particular pre-build command looks like this:

findstr /c:"ProviderManifestToken=\"2005\"" "$(SolutionDir)DAL\cptt.edmx" >nul 2>&1
if errorlevel 1 echo Invalid Manifest token for DAL. Modify cptt.edmx file in a text editor and set the ProviderManifestToken property to 2005.
view raw gistfile1.bat hosted with ❤ by GitHub

That’s all there is to it! If I modify my cptt.edmx file in Notepad and change the value to 2008 (what we don’t want), the next time I do a build I see the following:

Build Events Error
Click for larger view.

My build won’t continue after that, and I know that I need to fix things before I can continue.

There you have it! Simple pre-build error checking based on file contents. Enjoy!

2 thoughts on “Quick Tip: Aborting builds in Visual Studio based on file contents

What are your 10 bits on the matter? I want to know!

This site uses Akismet to reduce spam. Learn how your comment data is processed.