Welcome!

Microsoft Cloud Authors: Nick Basinger, Kevin Benedict, Pat Romanski, Liz McMillan, Lori MacVittie

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

In Visual Studio 2003 and earlier, the build process for Visual Basic and C# projects was hard-coded, and built into Visual Studio itself. The only build scripting tool that Microsoft offered was nmake, and a companion tool called build.exe that provided some support for concurrent builds. Visual Studio users whose build systems were based on makefiles had to maintain project files in parallel. For Visual Studio 2005, we thought it would be great if it was possible to completely customize the build process, and to build Visual Studio projects on machines that didn't even have Visual Studio installed, exactly the same as they built inside Visual Studio. We also wanted to be able to plug in reuseable build loggers and build steps.

MSBuild shipped in .NET Framework 2.0, and Visual Studio 2005 was based on it. To date we've only released build processes for Visual Basic and C#, but our vision is to make this truly the common build platform for Microsoft technologies. It's fair to say that internal Microsoft needs have motivated MSBuild almost as much as the needs of our customers. We're making exciting progress towards this goal, and we'll talk about our future plans later in this article.

MSBuild File Format
If you use Visual Studio 2005, you don't necessarily have to know anything about MSBuild syntax. Visual Studio's Visual Basic and C# project files are MSBuild format, and you can go right ahead and build them on machines without Visual Studio installed.

However if you want to customize the build process or create your own from scratch, you'll need to know something about the MSBuild syntax. We tried to make the file format as simple as possible, so it's easy to learn. It's XML, so any XML tool can work with it, and there are only a few different tags to know about. Let's do a quick tour.

PROPERTIES
MSBuild properties represent key/value pairs used during the build process. A property can only take one value at a time. Properties are always inside a PropertyGroup tag. If you open a Visual Basic or C# project file you'll see it uses properties to store whether the compiler should build with optimizations (the "Optimize" property), the output path (the "OutputPath" property), and what warning level it should use (the WarningLevelproperty). Think of properties as scalars. You can get their values with an expression like "$(PropertyName)".

ITEMS
MSBuild Item lists are just ordered bags, like arrays. An item list contains multiple MSBuild items of the same type. Each has a value and optional metadata. The syntax to access their values is different than properties: "@(ItemType)." The items in an item list are often file paths, but don't have to be - MSBuild doesn't care. Take a look at a Visual Basic or C# project again and you'll see items used to store all the source files (the "Compile" items) and references (the "Reference" items) in your project. They don't have to be hard-coded though. You can have MSBuild generate a list of items using wildcards such as "*.txt".

Like properties, items have an ItemGroup tag they always sit inside. Unlike properties, items can have arbitrary "metadata" attached to each one, which you can define with sub-elements below the item's element. Here's an example of metadata used to represent a Culture value on a resource item:

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

Metadata is accessed with yet another kind of expression that looks like this "%(MetadataName)" or "%(ItemType.MetadataName)". There's also a variety of built-in metadata such as "Filename" and "Full-Path", which are useful if the item represents a file.

One item list can be converted to another by a transform operation. For example, if you write "@(Compile -> ‘%(Filename).obj'") you'll get the collection of "Compile" items, but the extension of each item will be changed to "obj". That can be useful for specifying the outputs of a target or constructing a command line string.

TARGETS
Targets are the unit of build: it's not possible to build only part of a target. This time open up your Microsoft.CSharp.targets file, which you'll find in the .NET Framework install folder, e.g., Windows\ Microsoft.NET\Framework\v2.0.50727. (By convention, targets are stored in files that have the ‘.targets' extension.) Now look for the ‘Target' tag. A target groups a collection of tasks together in a particular order to form a unit of build. For example, the "CoreCompile" target contains the "CSC" task that will invoke the C# compiler. Like every other MSBuild tag, Target tags can have conditions on them, but you can also add Input and Output attributes, which MSBuild will compare to see if the target is up-to-date already: if the target is up-todate, MSBuild will skip the tasks within it in part or entirely. A "DependsOnTargets" attribute lets you define what targets need to run beforehand so you can organize the order in which targets run. Targets can override previous targets with the same name. Targets have some other powers: partial incremental build and target batching; you can find out more about these on MSDN.

TASKS
Tasks are reuseable build actions that define the steps in a target. Tasks are always inside a target. Each task is implemented as a .NET class, and the parameters to a task - where you pass in the items and properties it needs - are just the .NET properties on that task. MSBuild comes with a set of built-in tasks like Delete, Message, GenerateResource (which is much like resgen.exe), plus tasks for the Visual Basic and C# compilers. There's also a special MSBuild task that runs MSBuild on another project. If those aren't enough, you can write your own - start by deriving from Task or ToolTask. Use a "UsingTask" tag to help MSBuild to find the assembly that implements your task. Tasks can also emit items and properties back into the build using Output sub-elements for subsequent tasks and targets to consume.

CONDITIONS
Every element in MSBuild syntax can have a Condition attribute. These have simple syntax something like conditions in XSL: logical operators "and", "or". parentheses, and so on. You can also use Choose, When, and Otherwise elements to make decisions. Here are some examples, so you can see what they look like:

<Compile Include="MyFile.cs" Condition="'$(Confi guration)'=='debug'"/>

In this example, the item "MyFile.cs" will be created only when the project is building in the debug configuration.

<Target Name="CreateOutputDirectory" Condition="!Exists(‘$(OutputDir)')" />

In this example, the target CreateOutputDirectory and the targets it depends on will run only if the output directory doesn't exist.


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)

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.


IoT & Smart Cities Stories
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
Whenever a new technology hits the high points of hype, everyone starts talking about it like it will solve all their business problems. Blockchain is one of those technologies. According to Gartner's latest report on the hype cycle of emerging technologies, blockchain has just passed the peak of their hype cycle curve. If you read the news articles about it, one would think it has taken over the technology world. No disruptive technology is without its challenges and potential impediments t...
If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...