Customize your Project Build Process

Source: Internet
Author: User

While the Visual Studio build process is familiar for all. NET developers, not everyone realizes the build mizmization capabilities that can be accomplished with just a little work. you can easily put together tasks that occur before, after, and even during a build.

Note:With the release of Visual Studio 2005, a new build tool-called msbuild-is used within the Visual Studio environment. this tool provides build process tasks and is similar to Nant in capability. for pre-and post build operations for automatic builds I wocould suggest looking at msbuild tasks rather than the project level pre-and post-build commands.

Pre-and post-build event commands

In nonweb projects, you can create pre-and post-build event commands. as their names suggest, these are commands that you can customize to run just prior to or after a build. you can even control whether the post-build event executes at all depending on the outcome of the build. in the previous version of Visual Studio these commands cocould only be found in C # projects, but Visual Studio 2005 now exposes them for VB. net as well. for C # projects you can find the settings on their own tab in the project properties pages, while for Visual Basic projects they are found via a Build Events button on the compile tab in the my project Properties window.

Project Build Events for C # Projects

Project Build Events for VB. Net projects note the Build Events button in the bottom right corner of the window.

Just type in the command you want to occur for each event type. you can click on an edit event button under each event type to help "build" Up your command using a set of tokens or "macros ". these variables help provide some shortcuts to including pathnames, project output locations, and other information into your event commands. note that the variables are sensitive to the type of build you are compiling, So if you switch to a release build, the variables referencing the output directory will be correctly pointed\ Bin \ releaseDirectory (or wherever you have set up the output directory to be ).

Macro examples

name description
$ (targetpath) the full directory path to the output directory, including the project output filename. example: C: \ csharpwinformapp \ bin \ debug \ csharpwinformapp.exe
$ (targetdir) the full directory path to the output directory. Example: C: \ csharpwinformapp \ bin \ debug \
$ (projectdir) the full directory path to where the project file exists. Example: C: \ csharpwinformapp \

The build event command lines are simply command-line operations that will be executed at the specified time. the commands are saved in the project file and are targets configured in msbuild to be used by the build process to execute the commands. note that Visual Studio 2005 does not copy these commands out into batch files during a build like its predecessor did.

Note that a failing build event will be shown in the build output and listed in the build error task list along with any other build errors. a failing pre-build event will cause the build to stop, while a failing post-build event will still mark the build as a failure even if the build of the Code succeeded without errors. you can choose to have the post-build event occur every build, only if the build succeeded, or when the project output (the resulting. DllOr. Exe) Actually changes.

A great example of using a custom post-build event is when you have multiple configuration files. whe n you add App. config File to your project, it will automatically be copied to the output directory of the project and renamed to match up with the project output file (e.g ., Csharpwinformapp.exe. config ), But the IDE will not do the same with other custom configuration files. What if your project had multiple . Config Files to break up the settings? For example, you have App. config To store application configuration but then you also have Enduser. config File to store user-specific settings that you didn't want to mix with the application settings. by default, this configuration file wocould not be copied to your output directory, and the application wocould receive an exception if it went looking for the file during execution. to get around this, a custom post-build event can copy Enduser. config File to the output directory every time a build succeeds.

In the build events, choose to run a post-build event when a successful build occurs and add a post-build event command line:

Copy "$ (projectdir) enduser. config" "$ (targetdir )"

Note the use of quotes around the variables and commands-the quotes are there because there may be spaces in the file and pathnames. also, the variables that generate pathnames will append an ending slash automatically. after a successful build of this project the current version ofEnduser. configFile in the project directory will be copied to the output directory.

Copying files after a build is just one example of how these build events can be useful. more complex operations can be saved med as well. for example, a Windows Script or executable cocould be run when a build completes to kick off a set of test scripts against the newly built output. for automated builds in Visual Studio 2005 these types of operations wocould be configured as msbuild tasks, but within the IDE the pre-and post-build commands can make a life a lot easier.

Handling Build Events

some of the limitations of the custom pre-and post-build command events are that they are available for only nonweb projects and are only project specific. they don't give you the flexibility to deal with building a multiproject solution or provide a way of handling more complex build Outcomes other than a successful build, a failed build, or a changed project output. for more advanced handling of build events, we can turn to the Visual Studio macro environment. by using the IDE build events we can configure some operations to occur before, during or after a build no matter what project we are building or what type of project it is.

To hook into the IDE build events, all we need to do is create some simple macros. Open up your macro IDE (from tools? Macros? Macro ide or Alt-F11 ). if you haven't used the macro ide before, the first thing you'll notice is that it resembles the regular. net IDE, could t the macro IDE is used solely for the creation, editing, and compiling of macros that can be used within your Visual Studio IDE.

Open up the mymacros project and see if it already contains an environmentevents module. if it doesn't, go ahead and copy the one from the samples directory into your mymacros project. the code looks like this:


Option strict off
Option explicit off
Imports envdte
Imports envdte80
Imports system. Diagnostics
Public module environmentevents
# Region "automatically generated code, do not modify"
'Automatically generated code, do not modify
'Event sources begin
<System. contextstaticattribute ()> Public withevents
Dteevents as envdte. dteevents
<System. contextstaticattribute ()> Public withevents
Incluentevents as envdte. incluentevents
<System. contextstaticattribute ()> Public withevents
Using wevents as envdte. Using wevents
<System. contextstaticattribute ()> Public withevents
Tasklisteven TS as envdte. tasklisteven TS
<System. contextstaticattribute ()> Public withevents
Findevents as envdte. findevents
<System. contextstaticattribute ()> Public withevents
Outputdomainwevents as envdte. outputdomainwevents
<System. contextstaticattribute ()> Public withevents
Selectionevents as envdte. selectionevents
<System. contextstaticattribute ()> Public withevents
Buildevents as envdte. buildevents
<System. contextstaticattribute ()> Public withevents
Solutionevents as envdte. solutionevents
<System. contextstaticattribute ()> Public withevents
Solutionitemsevents as envdte. projectitemsevents
<System. contextstaticattribute ()> Public withevents
Miscfilesevents as envdte. projectitemsevents
<System. contextstaticattribute ()> Public withevents
Debuggerevents as envdte. debuggerevents
<System. contextstaticattribute ()> Public withevents
Projectsevents as envdte. projectsevents
<System. contextstaticattribute ()> Public withevents
Textdocumentkeypressevents as envdte80.textdocumentkeypressevents
<System. contextstaticattribute ()> Public withevents
Codemodelevents as envdte80.codemodelevents
<System. contextstaticattribute ()> Public withevents
Debuggerprocessevents as envdte80.debuggerprocessevents
<System. contextstaticattribute ()> Public withevents
Debuggerexpressionevaluationevents
As envdte80.debuggerexpressionevaluationevents
'Event sources end
'End of automatically generated code
# End Region
End Module

This sets up the types of IDE events you can hook into. Now if you openEnvironmenteventsModule in yourMymacros folder, You can selectBuildeventsFrom the Class Name drop-down (the left drop-down box above the Code ). then from the right method name drop-down, you can select one of four build events to hook:

onbuildbegin will fire when any build operation is fired from the IDE. It fires only once for a full solution or multiproject build operation.
onbuilddone will fire when a build operation completes. This event fires only once for a full solution or multiproject build operation.
onbuildprojconfigbegin will fire when a project build begins. This event is used to catch each project build event within a solution or multiproject build operation.
onbuildprojconfigdone will fire when a project build completes. This event is used to catch the completion of each project build within a solution or multiproject build operation.

Note:These events fire even if build errors or warnings occur, and the default behavior of Visual Studio is to build all projects in a solution even if projects earlier in the build have failed.

For an example, you can add the capability to stop the build process when a project fails and display a message box in the IDE to note when the build process is complete (in case someone isn' t paying attention the build output ).

Canceling a failed build

The normal behavior of Visual Studio is to build every project in a solution, even if one or more of those projects fails. if you have a half-dozen projects in your solution, then this can sometimes take a little while. it is much faster if the build quits when any of the projects fails. by handling a build event, you can ensure that.

Start by selectingOnbuildprojconfigdoneEvent from the method name drop-down abve the code. The macro ide will automatically generate the method signature to hook the event:

Private sub partition (_ byval project as string, _ byval projectconfig as string, _ byval platform as string, byval solutionconfig as string, _ byval success as Boolean) _ handles buildevents. onbuildprojconfigdoneend sub

since this event will fire whenev er a project completes a build, you can easily stop the rest of the build from occurring by using the executecommand method of the DTE object to send a build. cancel command to the IDE. the DTE object is a reference to the Visual Studio IDE, and using DTE. executecommand method to cancel the build is the same as hitting Ctrl-break during a build or typing build. cancel into the IDE command window. using the success parameter of the event signature, you can determine whether you want to stop the build. the code looks like this:

Private sub buildevents_onbuildprojconfigdone (_ byval project as string, byval projectconfig as string, _ byval platform as string, byval solutionconfig as string, _ byval success as Boolean) _ handles buildevents. onbuildprojconfigdoneif success = false then 'the build failed... cancel any further builds. DTE. executecommand ("build. cancel ") end ifend sub
Alert the user on a successful build

Now, the idea was to capture the end Of the build process to alert the user that the build was complete. for that you hook into the onbuilddone event the same way you did for the Project Build complete. this time, you'll use a standard Windows message box to display an informative alert:

Private sub buildevents_onbuilddone (_ byval scope as envdte. vsbuildsdetail, _ byval action as envdte. vsbuildaction) _ handles buildevents. onbuilddone 'alert that we finished building! System. Windows. Forms. MessageBox. Show ("build is complete! ") End sub

These are some pretty simple examples, but you have the power of. net Framework in your hands for any of these events so you are limited only by what you can come up with to handle. you can share these with other developers by just sending them the code to include in their own macro project or take it a step further and create a visual Studio add-in that hooks these events and distrients it That Way. if you take a look at the other ide events you can tap into, you will understand why the Visual Studio IDE is so extensible.

something to consider when you are implementing custom build events is that they are handled within the IDE only. build Events implemented using the extensibility of the IDE (macros or add-ins) will not fire if the build is run from the command line and they are executed for all project built with the IDE. however, pre-and post-build event commands will execute only for the project they are added to and even if the build is being run via the command line with devenv.exe/build or with msbuild. this cocould be important if you want to automate your build process on a build machine.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.