Welcome!

Microsoft Cloud Authors: Janakiram MSV, Yeshim Deniz, David H Deans, Andreas Grabner, Stackify Blog

Related Topics: Microsoft Cloud

Microsoft Cloud: Article

MSBuild - What It Does and What You Can Expect in the Future

The standard customizable build platform for the .NET Framework

IMPORT
The final XML element we'll cover on this tour is Import, and it's the key to making your build process reuseable. It pulls in another MSBuild file. Right at the bottom of your Visual Basic and C# files, you'll see an Import tag that pulls in the "Microsoft. CSharp.targets" or "Microsoft.VisualBasic.targets" file, which is the root of the build process for these projects. Both targets files again import the "Microsoft.Common.targets" file. There's more to MSBuild syntax, which is covered in the online documentation, but this overview should give you an idea.

LOGGERS
Traditionally build processes log to the console and to log files. The information logged is fairly hard-coded: the folder that's currently building, the command lines executing, and their output, including any warnings and errors. MSBuild was designed to log in a much richer fashion. Strongly typed .NET events are fired at each step, and any number of "loggers" can subscribe to the events they want and do whatever they like with the information. Events include "ProjectStarted" and "Message", which can be emitted by a <Message> task in the build. Output from tools the build launches is logged as Message, Error or Warning events as appropriate.

The build process is abstracted from the loggers, which are chosen when the build starts. For example, a builder might simultaneously attach a console logger, several file loggers with different verbosity settings, and a logger that inserts event details in a database. MSBuild ships with a built-in console logger, which is attached by default, and a file logger, both of which have adjustable verbosity settings. Like tasks, loggers are just .NET classes and you can write your own - start by deriving from the Logger class.

How MSBuild Builds a Project
MSBuild can be invoked directly on the command line (msbuild.exe) or inside Visual Studio. Either way the build is handled by the same MSBuild engine. Here's what MSBuild does:

1.  First, any global properties are applied to the project. Global properties are special: they can't be modified except within a Target. If MSBuild is invoked from the command line, the set of global properties will be the ones passed in via the /property: command line switch. If MSBuild is invoked as part of Visual Studio, the active configuration and platform are the global properties.
2.  Starting from the beginning of the project file, MSBuild engine evaluates the properties that are defined in the project. Imported targets files are loaded and evaluated as the MSBuild engine progresses: think of them as inserted directly into the project file. If a property is defined in two or more places, the last one wins.
3.  After the properties are evaluated, MSBuild engine evaluates all the item definitions that are defined then makes a third pass to evaluate items. At every step of the evaluation, all previously evaluated property values and item values an be used.
4.  MSBuild starts to execute the entry-point targets. These targets can be specifi ed via the /target: command line switch or the default targets defi ned in the project file through the project element's DefaultTargets attribute, or else MSBuild just picks the first target Visual Studio's entry points are fixed: Build, Clean, Rebuild, or Publish.

If the condition on a target is true, MSBuild will make sure all its dependencies are executed then execute the target itself, invoking the tasks in it one by one.
5.  By using the special "MSBuild" task, a project can cause another project to build. If a project references the outputs of another, it will use the MSBuild task to make sure that project is up-todate. Once the referenced project is done building, the MSBuild engine will resume building the referencing project.

To see what's happening in the build, specify the "detailed" or "diagnostic" verbosity level. To do this from the command line, use the /verbosity: switch to toggle the amount of information displayed during the build. In Visual Studio, this can be customized in the Tools/Options menu. On the "Build and Run" node under "Project and Solutions" from the left pane, you'll see a dropdown for "MSBuild project build output verbosity."

BATCHING TASKS
MSBuild can divide item lists into different "batches" using their metadata then execute each batch one at a time. This can be confusing, but once you get used to the idea it feels natural - and powerful.

Here's an example that creates a different folder for each value of the "Culture" metadata on an item list. You'll see that the Culture metadata, referenced with the special metadata ‘%' syntax, is passed into the task: that tells MSBuild to run the task once for each unique Culture value. In this example, the task runs twice.

<ItemGroup>
    <Resource Include="Form1.en-CA.resx;Form2.en-CA.resx">
        <Culture>en-CA</Culture>
    </Resource>
    <Resource Include="Form1.en-NZ.resx">
        <Culture>en-NZ</Culture>
    </Resource>
</ItemGroup>

<Target Name="CreateCultureDirs">
        <MakeDir  Directories="%(Resource.Culture)"/>
</Target>

Here's a trick that sometimes comes in handy: to execute a task once for each item, you can use the well-known item metadata Identity, which usually has a different value for each item.

Hosting the MSBuild Engine
If you like, you can host the MSBuild engine in your application, just as Visual Studio does. By referencing the Microsoft.Build.BuildEngine assembly, you can load, edit, and build projects. Perhaps you're writing a tool for analyzing a build tree, or even a product like Visual Studio that you want to read and write MSBuild format projects.

WORKING WITH OTHER BUILD SYSTEMS
As we mentioned, not all Microsoft project types are in MSBuild format right now. In Visual Studio 2005, Visual C++ projects are in their own format, as are Visual Studio Deployment projects and ASP.NET Web site projects. Visual Studio solution fi les are still in their own format too. Of course, most of us have some of these projects, and we need to build them on the command line too.

MSBuild does its best to interoperate with them. MSBuild can read Visual Studio solution files by translating them internally into MSBuild format. When a Visual C++ project is encountered, MSBuild will try to build it with vcbuild.exe, which ships as part of Visual Studio and the .NET SDK. For ASP. NET Web site projects, MSBuild will launch a tool to pre-compile them. In both cases, MSBuild generally won't require Visual Studio installed to build them. Indeed Visual Studio Team System's Build Server feature is designed to use MSBuild to work on dedicated build machines that don't have the full Visual Studio product installed.

The interoperability isn't perfect. As you'd expect, the different formats can't work together exactly. We hope MSBuild handles them well enough for most people to get by until they are all based on MSBuild. If you don't get the results you need, the fallback is to have Visual Studio installed and build with Visual Studio's devenv.exe application on the command line.


More Stories By Xin Yan

Xin Yan has been a software design engineer at Microsoft for over 7 years. He works on Visual Studio developer tools platform team.

More Stories By Dan Moseley

Dan Moseley is a software developer on the MSBuild and Visual Studio Project team.

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Paul 11/28/07 04:17:42 PM EST

I enjoyed the article on MSBuild, well written, concise, and interesting. But I was most interested in reading about Batching. In that section, you refer to an example using the Culture metadata, but I don't see the example you're referring to. Am I missing something?

@ThingsExpo Stories
What is the best strategy for selecting the right offshore company for your business? In his session at 21st Cloud Expo, Alan Winters, U.S. Head of Business Development at MobiDev, will discuss the things to look for - positive and negative - in evaluating your options. He will also discuss how to maximize productivity with your offshore developers. Before you start your search, clearly understand your business needs and how that impacts software choices.
SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
As popularity of the smart home is growing and continues to go mainstream, technological factors play a greater role. The IoT protocol houses the interoperability battery consumption, security, and configuration of a smart home device, and it can be difficult for companies to choose the right kind for their product. For both DIY and professionally installed smart homes, developers need to consider each of these elements for their product to be successful in the market and current smart homes.
SYS-CON Events announced today that Golden Gate University will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Since 1901, non-profit Golden Gate University (GGU) has been helping adults achieve their professional goals by providing high quality, practice-based undergraduate and graduate educational programs in law, taxation, business and related professions. Many of its courses are taug...
SYS-CON Events announced today that Avere Systems, a leading provider of hybrid cloud enablement solutions, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere Systems was created by file systems experts determined to reinvent storage by changing the way enterprises thought about and bought storage resources. With decades of experience behind the company’s founders, Avere got its ...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, will discuss how by using...
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
SYS-CON Events announced today that Yuasa System will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Yuasa System is introducing a multi-purpose endurance testing system for flexible displays, OLED devices, flexible substrates, flat cables, and films in smartphones, wearables, automobiles, and healthcare.
SYS-CON Events announced today that CAST Software will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CAST was founded more than 25 years ago to make the invisible visible. Built around the idea that even the best analytics on the market still leave blind spots for technical teams looking to deliver better software and prevent outages, CAST provides the software intelligence that matter ...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japanese Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ruby Development Inc. builds new services in short period of time and provides a continuous support of those services based on Ruby on Rails. For more information, please visit https://github.com/RubyDevInc.
SYS-CON Events announced today that Evatronix will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
As businesses evolve, they need technology that is simple to help them succeed today and flexible enough to help them build for tomorrow. Chrome is fit for the workplace of the future — providing a secure, consistent user experience across a range of devices that can be used anywhere. In her session at 21st Cloud Expo, Vidya Nagarajan, a Senior Product Manager at Google, will take a look at various options as to how ChromeOS can be leveraged to interact with people on the devices, and formats th...
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
SYS-CON Events announced today that SourceForge has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. SourceForge is the largest, most trusted destination for Open Source Software development, collaboration, discovery and download on the web serving over 32 million viewers, 150 million downloads and over 460,000 active development projects each and every month.
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities – ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous impor...
SYS-CON Events announced today that TidalScale will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale is the leading provider of Software-Defined Servers that bring flexibility to modern data centers by right-sizing servers on the fly to fit any data set or workload. TidalScale’s award-winning inverse hypervisor technology combines multiple commodity servers (including their ass...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, will lead you through the exciting evolution of the cloud. He'll look at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering ...
As hybrid cloud becomes the de-facto standard mode of operation for most enterprises, new challenges arise on how to efficiently and economically share data across environments. In his session at 21st Cloud Expo, Dr. Allon Cohen, VP of Product at Elastifile, will explore new techniques and best practices that help enterprise IT benefit from the advantages of hybrid cloud environments by enabling data availability for both legacy enterprise and cloud-native mission critical applications. By rev...
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp emp...