Friday, January 30, 2009

How to quickly wrap a single item into a collection

The situation

I just started to play with WPF and I like that very much. Its a lot easier to do many things that were very hard to do in Win Forms.

I’m working on a software that need a tree view. In win form you have to build the entire tree a node at a time, adding them recursively until done. In WPF though, there is a faster way to do that.

First let say we have a tree structure like this:

public class TreeNode
{
    private BindingList<TreeNode> _children;

    public BindingList<TreeNode> Children
    {
        get { return children; }
        set { /* setter code */ }
    }
}

Later in your code you define a property of that type to bind to:

public TreeNode Root
{
    get { return _root; }
}

With this code you can build a structured tree of nodes. Then you can use a TreeView object in your xaml file:

<TreeView Name="treeView1"
          ItemsSource="{Binding ElementName=Win,Path=Root}"
          ItemTemplate="{StaticResource NodeTemplate}" />

The Problem

The problem with this is that the TreeView needs a collection or at least an enumerable source as its ItemSource. What if we don’t want to bind to the Children property of the root? What if we have some interesting property to show on the root node?

The Solution

We can build a temporary collection to pleased the TreeView:

public List<TreeNode> Root
{
	get 
	{
		var list = new List<TreeNode>;
		list.Add(_root);
		return list;
	}
}

Of course this will work. But isn’t a little too much having to create an instance of a list object to do that? Here is a simpler an more efficient way to achieve the same result.

public IEnumerable<TreeNode> Root
{
	get { yield return _root; }
}

Wow! That’s short! If you don’t know what “yield return” keyword is, you may find this code sample a little odd. “yield return” is what LINQ uses internally to iterate thru any IEnumerable data source without having to build an internal list. In our case we only need a list of one item, so using this technique can optimise your code.

Wednesday, January 28, 2009

My first computer (part2)

For those of you who still trying to find what was my first computer, here it is:

http://oldcomputers.net/adam.html

http://en.wikipedia.org/wiki/Coleco_Adam

adam-name

adam

Tuesday, January 27, 2009

My first computer

Does anybody know what it is?

adam3

Debugging Windows Service Without Deploying It

Code available on Code Project: http://www.codeproject.com/KB/tips/EasyDebugWindowsServices.aspx

Introduction

At the beginning, there was no easy way to build a Windows service using Visual Studio and .NET Framework. Now that Microsoft has integrated this functionality as a template and a class library, it's much more easy to do that. This is good, but to test your newly created service you have to deploy it. That means you must add an installer and build a whole MSI file and run it in your environment. Once deployed, you can start it with Windows Service controller and attach a debugger to it.

I don't know how this sounds to you, but to me it is too much unneeded work to do a quick test. This article describes a much more easy way to do that.

Using the Code

You will find a sample application using this concept. Here is how it works.

First you need a working Windows service. (For more information, refer to this.)

In Visual Studio, building a Web service is easy. Create a new project and select Windows Service template.

Then add ServiceDebuggerHelper project to your solution and a reference to it. You can find it in the sample code.

By default, when you create a Windows service project, Visual Studio will create two classes: a Program class and a Service1 class. Here is what the program class looks like:

static class Program 
{ 
    /// <summary>
    /// The main entry point for the application. 
    /// </summary>
    static void Main() 
    { 
        ServiceBase[] ServicesToRun = new ServiceBase[] { new Service1() }; 
        ServiceBase.Run(ServicesToRun); 
    } 
}

The first thing we have to do is to surround that code with a conditional statement to let us control if we want to run as a real service or just in debugging mode.

 static class Program 
{ 
    /// <summary>
    /// The main entry point for the application. 
    /// </summary>
    static void Main() 
    { 
        if (args.Length > 0 && args[0].ToLower().Equals("/debug")) 
        { 
            Application.Run(new ServiceRunner(new Service1())); 
        } 
        else 
        {        
            ServiceBase[] ServicesToRun = new ServiceBase[] { new Service1() }; 
            ServiceBase.Run(ServicesToRun); 
        }
    } 
}

In this new Program class, ServiceRunner will be acting as a service host. To make it work, you have to add the "/debug" command line option in your project properties.

Go to Project -> ... Properties -> Debug and type /debug in the command line arguments field.

From there, you have two options to make your service debuggable. Either you implement IDebuggableService or inherit from DebuggableService base class.

Implementing IDebuggableService Interface

If you already subclass ServiceBase and use that subclass for all your services or if you just want to have full control over the implementation, you should implement theIDebuggableService interface. Here is its definition:

public interface IDebuggableService
{
    void Start(string[] args);
    void StopService();
    void Pause();
    void Continue();
}

Notice that the stop method is called StopService to avoid conflict with the existing Stop method of the ServiceBase class.

Here is a sample implementation of this interface:

public partial class Service1 : ServiceBase, IDebuggableService        
{
    //
    // Your existing service code
    //
    // ...
    //
    
    #region IDebuggableService Members

    public void Start(string[] args)
    {
        OnStart(args);
    }

    public void StopService()
    {
        OnStop();
    }

    public void Pause()
    {
        OnPause();
    }

    public void Continue()
    {
        OnContinue();
    }

    #endregion
}
Subclassing DebuggableService

Subclassing your service from DebuggableService is even more simple. All you have to do is change the base class from ServiceBase to DebuggableService.

public partial class Service1 : DebuggableService        
{
    //
    // Your existing service code
    //
    // ...
    //
}

All the control methods are already implemented by DebuggableService.

Points of Interest

In my sample code, I added a Windows Form class to let you start, stop and pause your service. You can use it as is, build your own controller interface or just call the methods in your program class. It is up to you.

Of course you should still deploy your service to give it the final test run. One good reason to do this is to test the actual security context in which your service will run. It will not have the same permission as when you run it in Visual Studio, but this technique can speed up the development process.

Code available on Code Project: http://www.codeproject.com/KB/tips/EasyDebugWindowsServices.aspx

Friday, January 23, 2009

A thought on how to hide private backing field

Ever thought of forcing every piece of code in your class to access information about your object via properties instead of fields? Imagine you build a type where you have some logic inside your property that you always want to run.

private string _myField;

public string MyField
{
	get { return _myField; }
	set { 
		if (_myField == value)
			return;

		_myField = value; 
		
		RaisePropertyChanged("MyField");
	}
}
In this classic case of property change notification, nothing prevent anyone to write this somewhere in the class:
_myField = "Something";
…and no PropertyChanged event fires.

Does everybody know about auto-properties?

public string MyField { get; set; }

If you look at the reflected code (with reflector):

[CompilerGenerated]
private string <MyField>k__BackingField;

[CompilerGenerated]
public void set_MyField(string value)
{
    this.<MyField>k__BackingField = value;
}

[CompilerGenerated]
public string get_MyField()
{
    return this.<MyField>k__BackingField;
}

You can see that the field defined at line 2 is written in an invalid C# syntax but it is valid in IL:

.field private string <MyField>k__BackingField
{
    .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor()
}

.method public hidebysig specialname instance void set_MyField(string 'value') cil managed
{
    .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor()
    .maxstack 8
    L_0000: ldarg.0 
    L_0001: ldarg.1 
    L_0002: stfld string PropertyHideBackingFieldTest.Class1::<MyField>k__BackingField
    L_0007: ret 
}

.method public hidebysig specialname instance string get_MyField() cil managed
{
    .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor()
    .maxstack 1
    .locals init (
        [0] string str)
    L_0000: ldarg.0 
    L_0001: ldfld string PropertyHideBackingFieldTest.Class1::<MyField>k__BackingField
    L_0006: stloc.0 
    L_0007: br.s L_0009
    L_0009: ldloc.0 
    L_000a: ret 
}
 

Here is my idea. If we can write code like this:

public string MyField
{
	field string _myField;
	
	get { return _myField; }
	set { 
		if (_myField == value)
			return;

		_myField = value; 
		
		RaisePropertyChanged("MyField");
	}
}

Now we can build a private field that won’t be available anywhere else. We will now have full control over the field itself. Maybe it can be available to the constructor too.

Or if we can at least have an attribute to do that. Like this:

[PropertyAccessOnly]
private string MyField;
Let me know what you think.

Thursday, January 15, 2009

Managed Parallel Computing with Parallel Extensions (Listing)

Here is the complete listing of my previous post. To run it you need to download and install June 2008 CTP of Parallel Extensions

See previous post for more details

using System;
using System.Diagnostics;
using System.Threading.Tasks;

internal class Program
{
    private static void Main()
    {
        Console.WriteLine("Building the tree");
        Tree tree = Tree.Create();
        Console.Out.WriteLine("Pause");
        Console.ReadLine();
        Console.Out.WriteLine("Calculating");

        while (true)
        {
            Stopwatch sw = Stopwatch.StartNew();
            int sum = tree.Sum();
            sw.Stop();
            Console.WriteLine("Sum is {0} in {1}", sum, sw.ElapsedMilliseconds);

            Console.Out.WriteLine("Pause");
            Console.ReadLine();

            sw = Stopwatch.StartNew();
            sum = tree.ParallelSum1();
            sw.Stop();
            Console.WriteLine("ParallelSum1 is {0} in {1}", sum, sw.ElapsedMilliseconds);

            Console.Out.WriteLine("Pause");
            Console.ReadLine();

            sw = Stopwatch.StartNew();
            sum = tree.ParallelSum2();
            sw.Stop();
            Console.WriteLine("ParallelSum2 is {0} in {1}", sum, sw.ElapsedMilliseconds);

            Console.Out.WriteLine("Pause");
            Console.ReadLine();

            sw = Stopwatch.StartNew();
            sum = tree.ParallelSum3();
            sw.Stop();
            Console.WriteLine("ParallelSum3 is {0} in {1}", sum, sw.ElapsedMilliseconds);

            Console.Out.WriteLine("Pause");
            Console.ReadLine();
        }
    }
}

internal class Tree
{
    public Tree Left { get; set; }
    public Tree Right { get; set; }
    public int Value { get; set; }

    public static Tree Create()
    {
        return Build(1, 22);
    }

    public static Tree Build(int start, int level)
    {
        Tree tree = new Tree {Value = start};
        if (level <= 0) return tree;
        var left = Build(start + 1, level - 1);
        var right = Build(start + 1, level - 1);
        tree.Left = left;
        tree.Right = right;
        return tree;
    }

    public int Sum()
    {
        int left = Left == null ? 0 : Left.Sum();
        int right = Right == null ? 0 : Right.Sum();

        return Value + left + right;
    }

    public int ParallelSum1()
    {
        int left = 0;
        int right = 0;

        Task[] tasks = new[]
        {
            Task.Create(x => left = Left.Sum()),
            Task.Create(x => right = Right.Sum())
        };

        Task.WaitAll(tasks);
        return Value + left + right;
    }

    public int ParallelSum2()
    {
        Future<int> futureLeft = Future<int>.Create(() => Left == null ? 0 : Left.Sum());
        Future<int> futureRight = Future<int>.Create(() => Right == null ? 0 : Right.Sum());
        return Value + futureLeft.Value + futureRight.Value;
    }

    public int ParallelSum3()
    {
        Future<int> futureLeft = Future<int>.Create(() => Left == null ? 0 : Left.ParallelSum3());
        int futureRight = Right == null ? 0 : Right.Sum();
        return Value + futureLeft.Value + futureRight;
    }
}

Managed Parallel Computing with Parallel Extensions

Full Listing

In my last post I told you about how I like to do talks about my passion. One of the subject I,m interested in at the moment is managed parallel computing, especially with what is coming from Microsoft Research: Parallel Extensions.

Parallel Extension is a new framework that will help us build software that can harvest all the power of a multi-core system without all the complexity of managing thread ourselves. I’m also presenting a lot on this subject, so if you are a member of a local user group I will be pleased to get invited.

What exactly is parallel extension. Like it says, it’s an extension. Actually it’s a replacement of the System.Threading library that add a lot of new types to deal with parallelism. By now, you should be aware of the existence of the thread pool class in the framework. But building multi-threaded application with that requires you to handle all the threads you create yourself. Of course the thread pool will make it easy to create threads, but the first question you have to ask is: how many threads do I need? The answer depend on many things. First, what are you trying to do? Are you just trying to use your idle CPU to some background processing or are your trying to complete an intensive process as fast as possible? How many available core do you have? Is it the only application that need processor power at the moment? The beauty of the Parallel Extensions framework is that it turn those those questions to be almost obsolete.

The power of that framework lives in it task scheduler. Wait! We are talking about Task now! What about thread? Yes, Parallel Extensions adds another layer of abstraction to resolve the problem. Isn’t that always what we do. That Task layer is very convenient. Now we don’t have to bother anymore about thread we just have to break our process into tasks. To put it simply, a task should be the smallest unit of work that can run independent of others.

I know how must you like to see code so here is a little sample for you.

internal class Program
{
    private static void Main(string[] args)
    {
        Tree tree = Tree.Create();
        int sum = tree.Sum();
		Console.WriteLine("Sum is {0}", sum);
    }
}

This is the main code to calculate the sum of a binary tree. Of course we have to implement the Sum method.

    public int Sum()
    {
        int left = SumLeft();
        int right = SumRight();

        return Value + left + right;
    }

The Sum method call two internal function to do the job. It gets the sum of the left part and add it to the sum of the right part. In this sample, we have to wait for the whole calculation of the left part before starting to calculate the right one. This tree can be deep, so SumLeft may take time to process. On a single core system you will have to do it sequentially. But if you have a multi core system you can do at least to calculation at the same time. What if later you move your program to a 16 cores system. With thread you would have to know how may cores are available and then start creating just enough thread to do the processing. Too little, you will waste valuable CPU time, too many you will take too much memory because every managed thread takes 1 Meg of memory. Parallel Extension framework will automatically use all available cores to do the job without interfering with the rest of the system. By default two thread per core will be created with an average priority. Of course you have full control those over those defaults by creating your own TaskManagerPolicy, but we will see that in another post.

Take a look at how to parallelize this task.

public int ParallelSum1()
{
    int left = 0;
    int right = 0;

    Task[] tasks = new Task[]
    {
        Task.Create(x => left = Left.Sum()),
        Task.Create(x => right = Right.Sum())
    };

    Task.WaitAll(tasks);
    return Value + left + right;
}

This is how you could do it with a simple task structure, but this code smells. The problem is that left and right variables are define outside of the scope of the task structure. Let see how to do it better and why.

public int ParallelSum2()
{
    Future<int> futureLeft = Future<int>.Create(() => Left == null ? 0 : Left.Sum());
    Future<int> futureRight = Future<int>.Create(() => Right == null ? 0 : Right.Sum());
    return Value + futureLeft.Value + futureRight.Value;
}

In this snippet futureLeft and futureRight are tasks that will be potentially evaluated on another thread if there is some resource available. If not they will be executed on the current thread when we ask for their Value property. With this method we will use only two cores even though we may have more in the future. But if we try to replace Sum() by ParalaleSum2() on line 3 and 4, it will not work properly. We will end up creating way too many task and it will run slower that the sequential version. Here is a solution to get the scalability we need.

public int ParallelSum3()
{
    Future<int> futureLeft = Future<int>.Create(() => Left == null ? 0 : Left.ParallelSum3());
    int futureRight = Right == null ? 0 : Right.Sum();
    return Value + futureLeft.Value + futureRight;
}

This time we only compute one path of the tree in parallel the other one will be calculated sequentially.

In conclusion even if we have more tools to build our software to do work in parallel, it is not always easy to get it right.

Inspiration comes from Daniel Moth.
http://www.danielmoth.com/Blog/2008/12/introducing-new-task-type.html
http://channel9.msdn.com/pdc2008/TL26/

Monday, January 12, 2009

I’m a presentation junkie

Presentation is like a drug. First time you see someone doing it you think “that guy will ruin his life”. Then, when you look carefully they seems to really enjoy it. And one day someone offer you to do one yourself. The first time you don’t know what to expect. You start talking in front of all those people. The time seems to stop but it runs, and it runs fast. Soon, someone at the back start showing you his watch. No, it’s not a new watch, he’s here to remind you to wrap up because they want to have enough time for the draw.

After that session you start thinking of what else you can present next time because you liked that feeling. You want to feel it again. That’s what happened to me some time ago.

I gave my first talk at 12 years old. I was too young back then to appreciate it like I do today. It was around 1983. I was giving a presentation on Logo. You know that small arrow in the middle of the screen to which you can give some instruction follow. That was a great language to start programming because you have an immediate feedback of what you tell it to do. Debugging was easy. If it looks great you succeeded if not, try harder. Now with all those new game with astonishing graphics that old logo isn’t that much attractive to young programmer to be. But Microsoft is working now on something new in that space: Kodu (formerly Bôkù).

Kodu is a game where, pretty much like Logo, you tell your character what to do. In this game the character is not a plain arrow but an animated 3D robot flying around your world. Another big difference is you don’t really tell it directly what to do. Instead you teach it some behaviours. For example you can tell if you see something red go toward it. And then you put your character and a red apple in a 3D environment and hit the play button. You character start to move toward the red apple until it get over it. You can tell your character once it get close enough. As with Logo it takes time to master all the commands you can use but it is as rewarding to see it in action. This game is planed to be released somewhere this spring on XBox Live.

All that to say that it is important to have a passion about something. Now I have the chance to combine two thing that make me feel good, software development and spreading my knowledge of it.

Stay tuned for more.