Brothers In Code

...a serious misallocation of .net resources

Synchronizing Config Files with Post-Build Events

If you have a test project, you'll get tired of keeping your configs in sync.  Depending how you're project is setup, sometimes you can refer some sections to a centralized config.  However most of the time I prefer to just use a post build event to copy the file from one project to another.

copy $(SolutionDir)MyWebProject\Web-ConnectionStrings.config $(ProjectDir)MyProject.Tests.ConnectionStrings.config
echo ^<!--copied via post-build event in $(ProjectName)--^> >>$(ProjectDir)MyProject.Tests.ConnectionStrings.config


The first line copies the file.  But I wanted myself or other developers to know that the file is being overwritten, so I added the second line which appends a message to the end of the file.

I Love Visual Studio's Build Events!

I've been using Visual Studio for more than 10 years, yet I've only discovered build events in the last year.  I really don't know how I survived with out them.

The big push for me was SharePoint.  There's a lot of things to do after you build a project: register a dll, run some stsadm.exe commands, copy some files to the 12 hive, etc.  Doing all this manually started to drive me nuts. 

But build events saved me.  Basically if you can execute your task from the command line, then it can be a build event.

A simpler example involves config files.  In a multi-project solution, I often need to keep multiple copies of a config file - say a dll is used by both a web app and a unit test project.  Keeping these in sync can be frustrating - all of a sudden your unit tests start blowing up because you only changed an expired connection string in the web app and not in the unit test.  I wrote a simple build event to copy the config files from the main project.  I even appended a little note that it was copied by the build event so I remember to edit the main file and not the copy.

There's pre and post-build events and there's lots of "macro" variables that'll keep your build events friendly over multiple developers or PCs.  You'll find the build events tab by right clicking a project file and selecting properties.

B