Sunday, September 30, 2007

MSBuild basics

First posted at:

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



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:

<AppName>My application name</AppName>


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:

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


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


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....


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)" />

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="">
<Target Name="Build" >
<Message Text="Executing calculator" />
<Exec Command="calc" />


Technorati Tags:

Saturday, September 29, 2007

September TFS Powertool released!

September version (1.3) of the Power Tool for TFS 2005 is now available for download.

This release includes new features:

  • Team Foundation Server Best Practice Analyzer: This tool helps a TFS Administrator gather configuration information about TFS deployment, perform tests on a server, analyze test results and more. In addition, this tool can be used to perform these tasks:
    • Determine configurations that differ from default, recommended, or required settings.
    • Verify a TFS deployment is configured according to recommended best practices.
  • WorkItem templates: supports the ability to create, apply, capture, and set default work item templates. Templates can be used to create or update work items, and they can automatically set field values.

This release is only compatible with Visual Studio 2005 Team Foundation Server. Visual Studio 2008 support are planned for December.


For more details, check out Brian Harry's post.

Technorati Tags:

My blog syndication

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

Friday, September 28, 2007

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=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’ or one of its dependencies. Strong name validation failed. (Exception from HRESULT: 0×8013141A)

File name: ’svcutil, Version=, 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:

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 Files\Microsoft SDKs\Windows\v6.0A\Bin)

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: ,

Thursday, September 27, 2007

Moving TFS Databases to new destination

Do you need to move TFS databases files to new location? Read about it here.

Technorati Tags:

C# 3.0 Extension Methods

Posted also at:

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:  }

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;
   6:  using MaorDavidsBlogExtensionExamples;
   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:

Wednesday, September 26, 2007

C# Automatic Properties

First posted at:

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;
   5:      public string FirstName
   6:      {
   7:          get { return _firstName; }
   8:          set { _firstName = value; }
   9:      }
  11:      private string _lastName;
  13:      public string LastName
  14:      {
  15:          get { return _lastName; }
  16:          set { _lastName = value; }
  17:      }
  19:      private string faculty;
  21:      public string Faculty
  22:      {
  23:          get { return faculty; }
  24:          set { faculty = value; }
  25:      }
  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:      }
   9:      public string LastName
  10:      {
  11:          get; set;
  12:      }
  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
private string <Faculty>k__BackingField;
private string <FirstName>k__BackingField;
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:

Google updated recently their Applications suite with the addition of Google Presentation. It was added to all of 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:

  • Monday, September 24, 2007

    Tuesday, September 18, 2007

    Astoria CTP Refresh for Visual Studio 2008 Beta 2

    The Astoria team has just released a refresh of the Astoria Prototype CTP to work with Visual Studio Beta 2 and the Entity Framework Beta 2.
    The Astoria September 2007 CTP is now available for download.
    This CTP is a refresh of the May CTP/Prototype bits recompiled so they run with Visual Studio 2008/Entity Framework Beta 2.
    You can visit the Astoria Team Blog for more information.
    Technorati Tags: ,

    The post also avalable at:

    Saturday, September 15, 2007

    C# 3.0 var keyword

    C# 3.0 has many-a-new features. This post will explain the 'var' keywork and the concept of Implicitly Typed Variables.

    The var keyword is not a late-bound or un-typed variable reference. The var keyword always generates a strongly typed variable reference. The main idea is that the developer is not required to define the type of the variable at the time of declaration, but it is the task of the compiler to decide what type of the object the variable is. The compiler infer the type of the variable from the expression used to initialize the variable when it is first declared.

    Important points about var keyword:

    • The type of the variable is defined by the value declared and decided at the compile time. (Size depends on the type of the value initialised)
    • Type casting is simple and handled by CLR.
    • Explicit functions for parsing to specific type.
    • Can be used to reference any type in C#.
    • The CLR actually never knows that the var keyword is being used.

    What rules shuold you force to use the var keyword?

    When you declare variable with the var keyword, you must to always do an initial value assignment.  This is because the var keyword produces a strongly-typed variable declaration. Hence, the compiler needs to be able to infer the type to declare based on its usage.   If you don't, the compiler will produce a compiler error.

       1: var vAge = 32; 
       2: var vHeight = 175.2; 
       3: var vName = “Maor David“;  


    The compiler will infer the type of the "age", "height" and "name" variables based on the type of their initial assignment value. This means it will generate IL that is absolutely identical to the code below:

       1: int age = 32;
       2: double height = 175.2;
       3: string name = "Maor David";

    You can also use it to other data types:

       1: foreach (var vTable in ds.Tables) 
       2: {
       3:     foreach (var vRow in ((DataTable) vTable).Rows) 
       4:     {
       6:     }
       7: }

    This is equal to:

       1: foreach (DataTable table in ds.Tables)
       2: {
       3:     foreach (DataRow vRow in table.Rows)
       4:     {
       5:     }
       6: }

    Technorati Tags: , ,

    You can read this post also at Maor David's Blog:

    Monday, September 10, 2007

    Microsoft Launches Translation Service

    Microsoft launched a service for automatic translation called Windows Live Translator. The site lets you translate a text limited to 500 words or a web page from English to German, Dutch, French, Spanish, Portuguese, Italian, Korean, Chinese, Japanese, Russian.

    Microsoft uses Systran to produce most of the translations, but also offers an option to translate computer-related texts using a machine translation system developed in-house. Microsoft's translation technology has been used to translate technical materials, including MSDN Library.

    Saturday, September 8, 2007

    Building .NET 3.0 projects from Team Foundation Build 2005 not supported

    Building .NET 3.0/3.5 projects from Team Foundation Build 2005 not supported. Team Foundation Build 2005 will always invoke the 2.0 Framework's MSBuild.exe, which does not support building solutions that target the 3.5 Framework.  (The 3.0 Framework shipped with Vista, while the 3.5 Framework is shipping with VS 2008.)

    The 3.5 Framework includes new MSBuild bits which allow multi-targeting - i.e. MSBuild 3.5 can target the 2.0 Framework.

    We can convert our solution to VS2008 beta 2 and target the solution to .NET framework 2.0. It's not enough. When we'll try to build this solution with Team Foundation Build 2005, we'll get an error MSB5014 - File format version is not recognized.

    The MSBuild blog has great post about MSBuild, Orcas, and Multi-targeting. Find it here.

    SqlBuildTask timeout

    I built a big DB Dude project from MSBuild command line and got a timeout error.

    MSBUILD : Build error TSD158: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

    The default timeout for query execution is 60 seconds and stored in the registry. We can extend the query timeout by changing these values. The registry entries are:



    Friday, September 7, 2007

    Lambda expressions introduction

    NET 2.0 introduced Anonymous Methods. The idea behind anonymous methods it to write methods inline to the code. They are mainly used for small methods that don't require any need for reuse. For example, we have this code:

       1: bool isGreaterThan5(int n)
       2: {
       3:     return n > 5;
       4: }
       6: ...
       8: int GetGreatersThanFives(List<int> numbers)
       9: {
      10:     return numbers.Find(isGreaterThan5);
      11: }

    We can code it with anonymous method:

       1: int GetGreaterThanFives(List<int> numbers)
       2: {
       3:   return numbers.Find(
       4:         delegate(int n) { return n > 5; }
       5:     );
       6: }

    c# 3.0 represent cool thing: Lambda expressions.
    Lambda Expressions make things easier by allowing you to avoid the anonymous method and that annoying statement block.


       1: delegate(int n){ return n > 5; }

    We can write:

       1: n =>  n > 5

    The form of Lambda expressions is:

    argument-list => expression

    Parameters to Lambda Expressions

    The parameters of a lambda expression can be explicitly or implicitly typed. In an explicitly typed parameter list, the type of each expression is explicitly specified. In an implicitly typed parameter list, the types are inferred from the context in which the lambda expression occurs:

       1: (int x) => x + 100         // explicitly typed parameter
       3: (x,y) => return x * y;    // implicitly typed parameter

    Lambda Expressions with Multiple Parameters

       1: (x, y) =>  return x * y

    Lambda Expressions without Parameters

       1: () => Console.WriteLine("Hello world!")      // No parameters

    I think that's enough intro to Lambda Expressions.
    I will follow up with a part 2 to show more about this cool fteature: Expression Trees, how LINQ uses it to pass code as parameters and more.

    SqlMetal for Linq

    SqlMetal builds a data access layer in seconds. The output is not just a first generation data access; SqlMetal's output includes all defined relationships (based foreign keys) between your tables. SqlMetal will produce a class for each table and, optionally, classes for all views, stored procedures and user-defined functions.

    SqlMetal can generate strongly typed interfaces for stored procedures and user-defined functions. From the developer point of view, it is now a complete breeze to call either a stored proc and/or a user-defined function.

    SqlMetal can generate a DataContext for your entire database with a single command.

    This is very useful if you have a large number of tables in your system, as dragging and dropping them onto the designer would have got boring very quickly. You can find SqlMetal at [C:]\Program Files\Microsoft SDKs\Windows\v6.0A\bin\.

    Lets create Northwind datacontext:

    C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin>sqlmetal /server:.\sqlexpress
    /database:northwind  /code:"c:\temp\northwind.cs"

    We can then include the class within our project and use it as if the designer had created it. We can also get SqlMetal to include all of our views, functions and stored procedures. (use /sprocs /views /functions to extract these objects).

    SQLMetal can also output the dbml (/dbml:file.dbml) or mapping (/map:file.xml) file for the database.

    C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin>sqlmetal /server:.\sqlexpress
    /database:northwind /dbml:"c:\temp\northwind.dbml"

    SqlMetal has also generated an external XML Mapping File that maps the classes generated to the database tables, which is much more complete than what I had done my self...

    C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin>sqlmetal /server:.\sqlexpress
    /database:northwind /map:"c:\temp\"


    The SqlMetal tool is useful to generate C# or VB.NET objects mapped on SQL Server database. It provides classes with members and properties mapped on table and view columns. It reflects the relationships between tables. It provides also a class derived from base class DataContext which maps, on request, functions and stored procedures, making difference between table functions and scalar functions and between stored procedures which returns a rowset and those who perform only operations such as insert, update and delete.

    From my point of view: great and useful tool.


    Technorati Tags:

    Thursday, September 6, 2007

    Windows Live Writer Beta 3 Released

    Highlights of the Windows Live Writer Beta 3 Release:

    • Insert videos using our new 'Insert Video' dialog
    • Upload images to Picasaweb when publishing to your Blogger blog
    • Publish XHTML-style markup
    • Use Writer in 28 additional languages
    • Print your posts
    • Justify-align post text
    • Better image handling (fewer blurry images)
    • Resolved installation issues from last release
    • Many other bug fixes and enhancements

    Download here.

    Wednesday, September 5, 2007

    Deploy .NET Apps with ClickOnce

    I wrote a post about it. You can read it here.

    Technorati Tags: Tags:

    Object Initializers in C# 3.0

    C# 3.0 includes a new language feature called object initializers.

    Object initializers enable you to initialize the state of an object with a single expression that does not require use of parameterized constructors.

    Basically, this feature allows you to initialize an object by both creating the object instance (i.e. a new expression) as well as assign values to one or more properties in a single sentence, or to initialize a collection with a set of values to add to it in a single expression.

        class Program
    static void Main(string[] args)
    Customer cus1 = new Customer() { Name = "Maor", City = "Herzliya" };
    Customer cus2 = new Customer() { Name = "Guy", City = "Ramat Hasharon" };

    List<Customer> customers = new List<Customer>() { cus1, cus2 };


    class Customer
    public string Name { get; set; }
    public string City { get; set; }


    The first & the second lines initialize a Customer object with the default constructor (though you could call a constructor with parameters here), and assigns explicit values to the Name and City properties.

    The third line initializes a collection of type List<Customer> with the objects cus1 and cus2. Tags:

    Technorati Tags: