Customize web.config Sections and Compile from Command LineIt is always important to being able to customize a software project build steps. Always there is the need to support at least two configurations: Debug and Release, but for some other projects you might need more configuration types. For instance you might need to support more than one database username depending on the data schema forcing you to come up with a different connectionStrings section in the web.config file depending on the username being used, you could also need to compile the XML documentation using a tool like SandCastle and come up with an automated MSDN-like help site or any other documentation style, but you might not want to do that always since the those documentation tools’ build process takes a bit of extra time to execute.
The project file (.csproj) is compiled by default using msbuild which is shipped by default with .NET 2.0 and higher and with the latest version of Visual Studio. This project file is nothing more than an XML file that defines the steps and properties msbuild needs to follow in order to come up with the correct build, something like an Ant or NAnt file. One very sensitive part of a build is the ability to replace web.config sections, such as the connectionStrings section. The guys at Microsoft provide the Web Project Deployment tool that implements a task called webConfigReplace, all this task does is pretty simple: it takes a file containing the XML that will replace the existing section in web.config. This works great for ASP .NET projects with the added dependency of an extra project file in the solution, but what if you want to get rid of the extra project in the solution and implement the replacement task in the actual project file (.csproj) containing your project? It’s actually not that complicated, all is needed is to download the Web Project Deployment tool and include the library in the project file as seen here:
Then it is just a matter of setting the properties for this tool and that’s about it now you can come up with a new web.config file every time you hit compile:
Another cool thing is that you can compile your project from a command line which will get rid of the Visual Studio dependency to build, also you can change the value of properties inside the project file with the /p command line argument to msbuild. This method also allows organizations that are working on a mixed environment (unix/Windows, java/.net) to understand each other since msbuild looks a lot more like a tool that can be controlled from command line and XML project files which the java guys are used to, this integration of the teams gives more power and value to the organization since it helps break those mental barriers that java and .net developers often have.