MSBuild basics

First posted at: http://blogs.microsoft.co.il/blogs/maordavid/archive/2007/09/30/msbuild-basics.aspx

One of the most technologies I like is MSBuild. I found that I didn’t dedicate too much writing time about it in this blog. I think and feel that I really neglect MSBuild at my blog…:(

This post will be the first of series of posts about this technology.

So lets start with the basics of MSBuild.

The Microsoft Build Engine (MSBuild) is the new build platform for Microsoft and Visual Studio. MSBuild is completely transparent with regards to how it processes and builds software, enabling developers to orchestrate and build products in build lab environments where Visual Studio is not installed.

Quote from Microsoft site.

 

In principle, this definition is really injustice for MSBuild. When I read it I insulted for MSBuild. For me, MSBuild is a high level scripting technology. I can use MSBuild almost for everything. NOT only build!

The introduction of MSBuild as an official utility was very welcome among the development community as it provides close integration with the existing project and solution files created by Visual Studio. This close integration cuts down on the amount of detail necessary for the build scripts.T he MSBuild utility comes with .NET 2.0 and is available with the runtime even if Visual Studio is not installed.

MSBuild based on XML-based project. (like csproj,vbproj…)

The basic elements of the MSBuild project file format are:

  1. PropertyGroup
  2. ItemGroup
  3. Target
  4. Tasks

 

PropertyGroup

Properties are defined in the PropertyGroup element. You can simply add an arbitrary element and enclose the assigned value within that element. Properties represent key/value pairs that can be used to configure builds. Example of PropertyGroup:

<PropertyGroup>
<AppName>My application name</AppName>
<AppDir>C:Apps</AppDir>
<ThirdPartyDir>C:3rdParty</ThirdPartyDir>
</PropertyGroup>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

ItemGroup

Defining lists is done within an ItemGroup element. You will want to use a list with a Task occasionally, such as copying a group of files to another folder. Below is an example of an ItemGroup.Items are declared in the project file by creating an element with the name of the item collection as a child of an ItemGroup element. Example of ItemGroup:

<ItemGroup>
<FilesToCopy Include = "file1.cs"/>
<FilesToCopy Include = "file2.cs"/>
</ItemGroup>

 

You reference item collections throughout the project file with the syntax @(ItemGroupName). In thus case, you reference the item group with @(FilesToCopy).

Targets

Targets group tasks together in a particular order and expose sections of the project file as entry points into the build process. Targets are often grouped into logical sections to allow for expansion and increase readability.

Targets are declared in the project file with the Target element. For example, the target bellow occurs after build finished.

<Target Name="AfterBuild">
Do something....
</Target>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Tasks

Tasks are reusable units of executable code used by MSBuild projects to perform build operations. For example, a task might create directories and copy files. Once created, tasks can be shared and reused.

You execute a task in an MSBuild project file by creating an element with the name of the task as a child of a Target element.

MSBuild shipped with a alot of built in tasks. For example: MakeDir,Copy and more.

See below an example for using tasks:

<Target Name="AfterBuild">
<MakeDir Directories="$(AppDir)" />
<Copy SourceFiles="$(FilesToCopy)" DestinationFolder="$(AppDir)" />
</Target>

Next in the series I’ll dive deeper with the msbuild script.

The msbuild script below is a demonstration about my earlier sentence: “I can use MSBuild almost for everything”. Save this as .proj file, and execute it from VS2005 command prompt as: msbuild YourSavedFileName

This script only opens windows calculator…

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="Build" >
<Message Text="Executing calculator" />
<Exec Command="calc" />
</Target>
</Project>

 

Technorati Tags:

My blog syndication

I moved to FeedBurner. Please update your subscription to my new Feed.

http://feeds.feedburner.com/MaorDavid

svcutil.exe in Orcas Beta 2 problem

Posted also at: Maor David – The Blog.

When I trying to run WCF test service on VS 2008 beta 2 I got an error:

Unhandled Exception: System.IO.FileLoadException: Could not load file or assembly ’svcutil, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’ or one of its dependencies. Strong name validation failed. (Exception from HRESULT: 0×8013141A)

File name: ’svcutil, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’ —> System.Security.SecurityException: Strong name validation failed. (Exception from HRESULT: 0×8013141A)

It turns out that this is a known issue in Beta2. Svcutil.exe is not signed correctly.

I found a solution for this issue at WCF MSDN forum: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1932994&SiteID=1&pageid=0

The solution is:

1. Open the VS 2008 Beta 2 command prompt as Administrator (important especially in Vista).

2. Browse to the bin directory of the windows SDK ([C]:Program FilesMicrosoft SDKsWindowsv6.0ABin)

3. Type: sn –Vr svcutil.exe.

 

By the way,  sn -Vr will not sign it but rather tell .NET to skip signature verification for that assembly.

Technorati Tags: ,

C# 3.0 Extension Methods

Posted also at: http://blogs.microsoft.co.il/blogs/maordavid/archive/2007/09/27/c-3-0-extension-methods.aspx

How many times have you written wrapper methods for objects that in reality you wished were part of the object itself?For example, we have the following method which returns the first and last char of a given string in upper case:

   1:  namespace MaorDavidsBlogExamples
   2:  {
   3:      public static class Extensions
   4:      {
   5:          public static string UpperFirstAndLast(string str)
   6:          {
   7:              string ret = "{0}{1}{2}";
   8:              ret = String.Format(ret,
   9:                  str.Substring(0, 1).ToUpper(),
  10:                  str.Substring(1, str.Length - 2),
  11:                  str.Substring(str.Length-1).ToUpper());
  12:              return ret;
  13:          }
  14:      }
  15:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 
We called this method:

   1:  static void Main(string[] args)
   2:  {
   3:      string str = "maordavid";
   4:      Console.WriteLine(Extensions.UpperFirstAndLast(str));
   5:      Console.ReadLine();
   6:  }

…when really, what you want is something more readable like this:

   1:  Console.WriteLine(str.UpperFirstAndLast());

That is exactly what Extension methods let you do.

Extension methods new feature of C# 3.0. They are static methods that can be invoked using instance method syntax. In effect, extension methods make it possible to extend existing types and constructed types with additional methods. Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type.

 

Now we want to add this new UpperFirstAndLast() method to the existing string type. Some of us can think that we can create our own class that inherits System.String and add that method there, but it’s impossible – System.String is a seald class. What can we do? use Extension Methods!

Declaring Extension methods

Extension methods are declared by specifying the keyword this as a modifier on the first parameter of the methods. Extension methods can only be declared in static classes.

Let’s rewrite the UpperFirstAndLast:

   1:  namespace MaorDavidsBlogExtensionExamples
   2:  {
   3:      public static class Extensions
   4:      {
   5:          public static string UpperFirstAndLast(this string str)
   6:          {
   7:              string ret = "{0}{1}{2}";
   8:              ret = String.Format(ret,
   9:                  str.Substring(0, 1).ToUpper(),
  10:                  str.Substring(1, str.Length - 2),
  11:                  str.Substring(str.Length-1).ToUpper());
  12:              return ret;
  13:          }
  14:      }
  15:  }

 

The static method above has a “this” keyword before the first parameter argument of type string.  This tells the compiler that this particular Extension Method should be added to objects of type “string”. 

To add this specific Extension Method implementation to string instances within my code, I simply use a standard “using” statement to import the namespace containing the extension method implementation. (Line 6 below)

The compiler will then correctly resolve the UpperFirstAndLast() method on any string.

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:   
   6:  using MaorDavidsBlogExtensionExamples;
   7:   
   8:  namespace MaorDavidsBlogExamples
   9:  {
  10:      class Program
  11:      {
  12:          static void Main(string[] args)
  13:          {
  14:              string str = "maordavid";
  15:              Console.WriteLine(str.UpperFirstAndLast());
  16:              Console.ReadLine();
  17:          }
  18:      }
  19:  }

 

The intellisense will help you to find the extension method: new icon indicates an “extension method.

 

 

Another posts about C# 3.0:

C# Automatic Properties

First posted at: http://blogs.microsoft.co.il/blogs/maordavid/archive/2007/09/26/c-automatic-properties.aspx

Visual Studio 2008 and .NET 3.5 introduces us new feature: Automatic Properties.

You probably write classes with properties like this:

   1:  public class Student
   2:  {
   3:      private string _firstName;
   4:   
   5:      public string FirstName
   6:      {
   7:          get { return _firstName; }
   8:          set { _firstName = value; }
   9:      }
  10:   
  11:      private string _lastName;
  12:   
  13:      public string LastName
  14:      {
  15:          get { return _lastName; }
  16:          set { _lastName = value; }
  17:      }
  18:   
  19:      private string faculty;
  20:   
  21:      public string Faculty
  22:      {
  23:          get { return faculty; }
  24:          set { faculty = value; }
  25:      }
  26:   
  27:  }

 

Usually, you aren’t actually adding any logic in the getters/setters of your properties – instead you just get/set the value directly to a field.

Basically, automatic properties allow you to replace this common pattern with this one:

   1:  public class Student
   2:  {
   3:      public string FirstName
   4:      {
   5:          get; set;
   6:      }
   7:   
   8:   
   9:      public string LastName
  10:      {
  11:          get; set;
  12:      }
  13:   
  14:   
  15:      public string Faculty
  16:      {
  17:          get; set;
  18:      }
  19:  }

No fields, only properties and declarations of get/set. The compiler can automate creating the private field and the default get/set operations for you.

This is certainly much more compact and requires fewer steps. When the compiler sees this class, (according to Reflector) it translates it to:

public class Student
{
// Fields
[CompilerGenerated]
private string <Faculty>k__BackingField;
[CompilerGenerated]
private string <FirstName>k__BackingField;
[CompilerGenerated]
private string <LastName>k__BackingField;

// Methods
public Student();

// Properties
public string Faculty { [CompilerGenerated] get; [CompilerGenerated] set; }
public string FirstName { [CompilerGenerated] get; [CompilerGenerated] set; }
public string LastName { [CompilerGenerated] get; [CompilerGenerated] set; }
}

There are a few things to look out for when using this syntax. The compiler forces you to declare properties with both a get and a set. You also don’t get any kind of “safety” features, such as ensuring that you don’t allow a null value to be assigned to a string property. If you want these more “advanced” features, you’ll still need to define your property with the “old way”.

Google Presentation

Posted at Maor David’s blog: http://blogs.microsoft.co.il/blogs/maordavid/archive/2007/09/26/google-presentation.aspx

Google updated recently their Applications suite with the addition of Google Presentation. It was added to all of docs.google.com including Google Apps For Your Domain, which I also use.

Nice things in this application

  • It looks just like PowerPoint!
  • Great Revisions support – many copies are saved all the time, so you’ll never lose anything.
  • You can start a presentation then give folks a URL and they can join up and watch.
  • Upload a PPT .
  • You can chat about the presentation being watched.
  • Save as a ZIP file. They’ll create a “self-contained” ZIP with a single HTML file and the assets you need to run the presentation using any browser.

But there also annoying things:

  • No spellcheck support.
  • Can’t link to pictures online, have to upload.
  • No animations, shapes, auto-layouts, wizards, etc.
  • Very basic. No PowerPoint-like experience on the web.
  • JavaScript errors.
  • You can upload PPT, but you can’t Save As PPT.

    Nice application but I think I’ll wait to the next versions.

    Also posted at: http://blogs.microsoft.co.il/blogs/maordavid/archive/2007/09/26/google-presentation.aspx

  • Getting started with LINQ – Maor David's Blog

    Getting started with LINQ – Maor David’s Blog

    %d bloggers like this: