Wednesday, August 31, 2011

VS : Changing .config file using conditional post-build event

Sometimes .config file - either app config file or web.config file - needs to be changed based on some condition during the build time. For example, one might want to use local SQL connection string in one case and use remote SQL connection string for another case. Due to pre-build / post-build event feature of Visual Studio, these cases can be solved without big effort.

Let's say one wants to use remote SQL connection by default and use local SQL connection only when special parameter (called UseLocalSQL) is defined. To implement this sceanrio, first one needs to add the condition to Post build event in VS Project Properties dialog.


if '$(UseLocalSQL)'=='True' Copy "$(ProjectDir)LocalApp.config" "$(TargetPath).config" /y

This means if UseLocalSQL parameter is defined and it's true, the copy .config command will be executed. If local SQL is not needed, default app.config will have remote SQL connection string.
(NOTE: one can also use pre-build event instead of post-build event. It's matter of implementation choice)

If one needs to use MSBUILD tool, the following can be used.

C>msbuild test.sln /t:Rebuild /p:Configuration=Release /p:UseLocalSQL=True

And if one uses TFS build system, the msbuild paramaeter can be specified as follows:


No comments:

Post a Comment