Wednesday, July 22, 2009

How to use INotifyPropertyChanged, the type-safe way (no magic string)

Implementation of the INotifyPropertyChanged interface is quite simple. There is only one event to implement. Take for example the following simple model class:

public class Model : INotifyPropertyChanged
{
    private string _data;

    public string Data
    {
        get { return _data; }
        set
        {
            if (_data == value)
                return;

            _data = value;

            // Type un-safe PropertyChanged raise 
            PropertyChanged(this, new PropertyChangedEventArgs("Data"));
        }
    }

    #region Implementation of INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged = null;

    #endregion
}

This is a pretty standard way to implement a bindable property. The problem here is the “Data” string to specify which property changed. If someone change the name of the property without changing the content of the string, the code will compile fine but won’t work. In a big application with may properties it can be hard to detect and find the problem.

The best solution is to rely on the compiler to warn us. But because the property name is a string it can’t. So let’s change that line with a type-safe one.

public class Model : INotifyPropertyChanged
{
    private string _data;

    public string Data
    {
        get { return _data; }
        set
        {
            if (_data == value)
                return;

            _data = value;

            // Type safe PropertyChanged raise
            PropertyChanged.Raise(() => Data);
        }
    }

    #region Implementation of INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged = null;

    #endregion
}

What is the trick? Raise is an extension method that takes a lambda expression to specify the name of the property in a type safe way. The Raise method resolve this expression to extract the name of the property and pass it to the PropertyChanged event.

public static class PropertyChangedExtensions
{
    public static void Raise(this PropertyChangedEventHandler handler, Expression<Func<object>> propertyExpression)
    {
        if (handler != null)
        {
            // Retreive lambda body
            var body = propertyExpression.Body as MemberExpression;
            if (body == null)
                throw new ArgumentException("'propertyExpression' should be a member expression");

            // Extract the right part (after "=>")
            var vmExpression = body.Expression as ConstantExpression;
            if (vmExpression == null)
                throw new ArgumentException("'propertyExpression' body should be a constant expression");

            // Create a reference to the calling object to pass it as the sender
            LambdaExpression vmlambda = Expression.Lambda(vmExpression);
            Delegate vmFunc = vmlambda.Compile();
            object vm = vmFunc.DynamicInvoke();

            // Extract the name of the property to raise a change on
            string propertyName = body.Member.Name;
            var e = new PropertyChangedEventArgs(propertyName);
            handler(vm, e);
        }
    }
}

All you have to do is to put this extension method in your code and the jib is done. Of course at the end a string will be used to raise the PropertyChanged event but because you don’t have to type it, you don’t have to maintain it.

Tuesday, July 21, 2009

How to use INotifyPropertyChanged, the type-safe way (no magic string)

Implementation of the INotifyPropertyChanged interface is quite simple. There is only one event to implement. Take for example the following simple model class:

public class Model : INotifyPropertyChanged
{
    private string _data;

    public string Data
    {
        get { return _data; }
        set
        {
            if (_data == value)
                return;

            _data = value;

            // Type un-safe PropertyChanged raise 
            PropertyChanged(this, new PropertyChangedEventArgs("Data"));
        }
    }

    #region Implementation of INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged = null;

    #endregion
}

This is a pretty standard way to implement a bindable property. The problem here is the “Data” string to specify which property changed. If someone change the name of the property without changing the content of the string, the code will compile fine but won’t work. In a big application with may properties it can be hard to detect and find the problem.

The best solution is to rely on the compiler to warn us. But because the property name is a string it can’t. So let’s change that line with a type-safe one.

public class Model : INotifyPropertyChanged
{
    private string _data;

    public string Data
    {
        get { return _data; }
        set
        {
            if (_data == value)
                return;

            _data = value;

            // Type safe PropertyChanged raise
            PropertyChanged.Raise(() => Data);
        }
    }

    #region Implementation of INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged = null;

    #endregion
}

What is the trick? Raise is an extension method that takes a lambda expression to specify the name of the property in a type safe way. The Raise method resolve this expression to extract the name of the property and pass it to the PropertyChanged event.

public static class PropertyChangedExtensions
{
    public static void Raise(this PropertyChangedEventHandler handler, Expression<Func<object>> propertyExpression)
    {
        if (handler != null)
        {
            // Retreive lambda body
            var body = propertyExpression.Body as MemberExpression;
            if (body == null)
                throw new ArgumentException("'propertyExpression' should be a member expression");

            // Extract the right part (after "=>")
            var vmExpression = body.Expression as ConstantExpression;
            if (vmExpression == null)
                throw new ArgumentException("'propertyExpression' body should be a constant expression");

            // Create a reference to the calling object to pass it as the sender
            LambdaExpression vmlambda = Expression.Lambda(vmExpression);
            Delegate vmFunc = vmlambda.Compile();
            object vm = vmFunc.DynamicInvoke();

            // Extract the name of the property to raise a change on
            string propertyName = body.Member.Name;
            var e = new PropertyChangedEventArgs(propertyName);
            handler(vm, e);
        }
    }
}

All you have to do is to put this extension method in your code and the jib is done. Of course at the end a string will be used to raise the PropertyChanged event but because you don’t have to type it, you don’t have to maintain it.

Monday, July 20, 2009

Silverlight MVP Creates PRISM Videos and Interviews!

via The Microsoft MVP Award Program Blog by Jas Dhaliwal on 7/20/09

PRISM is a collection of tools for building maintainable and scalable Silverlight applications. It was created by the Microsoft's Patterns and Practices team, and is a collection of libraries, code, documentation and samples.

Silverlight MVP Erik Mork has created a great suite of resources that can help the community to get started with the technology. Check out the list of video, blog posts and podcasts below for further information!

5 minute introduction to PRISM - 10 Things to Know About Silverlight PRISM. This post covers the essential things that web developer should know about PRISM.

Hyper-Videos - These are screencasts in a rich Silverlight Player. They include code that can be copied and pasted while watching the video. In addition, there is video navigation and deep linking support.

Intro to Silverlight PRISM - Silverlight PRISM Video Testing/Module Catalog/Unity - Modularity in PRISM Video

Regions (including Region Scope, Region Adapter and Region Context) - PRISM Regions Video Commanding (including creating new commands) - Commanding in PRISM Video Eventing - Eventing in PRISM Video

Podcast Interviews - These interviews were recorded with the Patterns and Practices team.

· What is PRISM - What is PRISM Interview

· How Modularity Works in PRISM - PRISM Modularity Interview

· When to use PRISM - When to use PRISM Interview

· How Regions Work in Prism - Regions in PRISM Interview

· View or Presenter First? - View or ViewModel First Interview

· How Commanding Works in PRISM- Commanding in PRISM Interview

· Loosely Coupled Communications in PRISM - Event Aggregator in PRISM Interview

Blog Posts - Helper resources for PRISM

PRISM Overview Post - 10 Things to Know about Silverlight PRISM (overview of all resources) Downloading and Building Prism - Finding and Building PRISM Post

Learning new technologies, who should pay the price?

Sometimes I’m wondering, what am I doing in computer science? I’m good at it, or I think I am, but there always something new to learn.

Ever since the beginning of my career and may be before that I have to learn new things, new concepts, new technologies, new practice to do my job. I’m not complaining, I love to learn. It keeps me motivated, but who should pay the price.

I rarely did the same kind of project twice. Anyway it would be boring. I’m the kind of guy that like to build new things, to boldly go where no one has gone before (Start Trek). But this time I think I took the biggest leap of my career.

In my current project I use many new and emerging technologies, and beside the fact I’m coding in C# it’s all new to me.

Microsoft CRM 4.0

First our whole project is built on top of Microsoft CRM 4.0, it acts as our repository. We chose CRM because it has most of the data structure we need for our project. Hopefully I’m working with Alexandre Leduc who knows all the bells and whistles of MS CRM.

LINQ to CRM

One of the technology we use to connect our application to CRM is Linq to CRM. This is a fairly new project on codeplex, in fact it’s not final yet. There still many Linq command missing from this framework. But because it uses CRM as an IQueryable<T>, it gives us the performance we need.

ADX Studio CRM Metal

Because entities generated by linq to CRM are somewhat hard to manage (all the names are lower case and some of them have custom prefix), we use CRM Metal to generate our plain domain model. CRM Metal annotate all the classes and properties with attributes that helps to find the underlying linq to CRM types. We use those information as mapping when we load a new object in memory.

RegEx

Because we want to be able to bind our UI to our domain model and it doesn’t implement INotifyPropertyChanged we use a find and replace regular expression to change all auto properties to properties with a backing field and a RaisePropertyChanged. At first we used PostShap to do that but it was way too slow to compile and because our data model is so big it was generating OutOfMemoryException every once in a while.

Windows Presentation Framework (WPF)

Just because its the new trend and a little because we want to be able to style our application, we chose to use WPF for our front end application. This is my first real experience with WPF, so I have everything to learn. I have to rethink the way I build an application layout. Expression Blend is an awesome tool when you finally understand how it works.

Composite Application Block for WPF and Silverlight 2.0 (formerly known as Prism)

I merely had the chance to work with the CAB framework with winform in a previous project, so Prism was almost all new stuff for me. Besides all the CAB concepts of shell, modules, views, services, commands, messages, Prism introduce Unit Application Block. Unity is an Inversion Of Control (IOC) container and a Dependency Injection (DI) framework. The basic concept is, the framework will handle the discovery and/or the creation of instance and will give you that instance on demand when you request it by its interface. This saves a lot of code and removes hard dependencies. When you start a new module (class) you only have to declare interfaces arguments to your constructor and Unity will handle you the appropriate instance. It a little overwhelming at first because you look like you loose control of your code. After a while you get used to it.

Who should pay the price?

As you can imagine, learning all that takes time, and the project still has a budget and a timeframe. It’s hard to throw all those costs to the customer. So, I take most of that on my shoulder hoping that someday I will reuse all this knowledge.

Saturday, July 18, 2009

Plenty of Color Resource for Expression

via Canadian UX Blog by qixing on 7/17/09

Thinking about a color palette for your new website or application project? I've been using the site Colourlovers.com to get color inspirations. It's a virtual color library where you can find thousands of color palettes, articles on color design, and follow color trends from magazine and websites.

What's more useful about the site is that you can import the color palettes into Expression Design as swatches or add them into Expression Blend as application resources. Let me show you an example:

Summer is in the air and a mixed berry lemonade sounds good. :) I found the follow color palette on the site.

mixed berry lemonade color palette

Once you registered as a site user, you can download the palette and import into Expression Design as a Swatch Library (below left).

Swatch image

Or, you can download the XAML file and copy the content into your Silverlight application's App.xaml file (see below). Make sure to insert the the code into the Application.Resource section of your App.xaml. You can see the result in Blend as the one on the right above. Simply just drag and apply brush onto the objects on canvas.

image

Color is an important element of graphics design. Here's a nice article talks about the Color Basics: Do's and Don'ts. Check out the article and have fun with color in Expression.

Monday, July 13, 2009

Microsoft Office 2010 Web Apps to be Free; Testing Starts Today [Microsoft]

via Gizmodo by John Herrman on 7/13/09

After Microsoft's initial announcement, the forthcoming Google-docs-like Office web apps—"Office Web"—kinda fell off the radar. Today, we get confirmation that the online suite will be free, and that Office 2010 will start semi-private testing today.

With free or cheap alternatives from Google, Zoho, Apple and Adobe, Microsoft didn't really have much a choice when it came to pricing the online suite: it'd either be free, or a failure. Thankfully, the apps, which include Word, PowerPoint, Excel and OneNote, will be available to anyone with a Live account, and judging by the (lone) screenshot above, will aim to compete directly, feature-wise, with other companies' offerings—although hopefully with better handling of complex formatting.

This announcement is paired with news that the actual suite, shown in the gallery above, has hit the "Technical Preview" stage, and that it'll be available for testing to tens of thousands of users, albeit by invitation. (Although for the rest of us, it's already been leaked) There aren't a ton of surprises in the announcements, but PowerPoint video editing, new grou-editing tools, and a bevy of small tweaks and feature-adds can be expected. [Microsoft]

Office 2010 Hits Major Milestone and Enters Technical Preview Microsoft showcases new product capabilities and announces Office Web applications will be available to nearly half a billion people at launch.

NEW ORLEANS, La. - July 13, 2009 - Today, at its Worldwide Partner Conference, Microsoft Corp. announced Office 2010, SharePoint Server 2010, Visio 2010 and Project 2010 have reached the technical preview engineering milestone. Starting today, tens of thousands of people will be invited to test Office and Visio as part of the Technical Preview program. "Office 2010 is the premiere productivity solution across PCs, mobile phones and browsers," said Chris Capossela, senior vice president, Microsoft Business Division. "From broadcast and video editing in PowerPoint, new data visualization capabilities in Excel and co-authoring in Word, we are delivering technology to help people work smarter and faster from any location using any device." Office 2010 and related products will deliver innovative capabilities and provide new levels of flexibility and choice that will help people:

• Work anywhere with Office Web applications—the lightweight, Web browser versions of Word, PowerPoint, Excel and OneNote-that provide access to documents from anywhere and preserve the look and feel of a document regardless of device.

• Better Collaborate with co-authoring in Word, PowerPoint and OneNote, and advanced email management and calendaring capabilities in Outlook, including the option to "ignore" unwanted threads.

• Bring ideas to life with video and picture editing, broadcast capability in PowerPoint, easy document preparation through the new Microsoft Office Backstage view, and new Sparklines in Excel to visualize data and spot trends more quickly;

Microsoft also announced that it is streamlining the number of Office editions from eight to five and enhancing each edition with additional applications and features. The company also announced that Office Web applications will be available in three ways: through Windows Live, where more than 400 million consumers will have access to Office Web applications at no cost; on-premises for the more than 90 million Office annuity customers; and via Microsoft Online Services, where customers will be able to purchase a subscription as part of a hosted offering. Partner Opportunities: Microsoft also is preparing partners for the release of Office 2010 and SharePoint Server 2010 through a number of new and refreshed readiness tools and training programs. These include: the Ignite program for SharePoint, Office and Exchange; Business Productivity Infrastructure Optimization (BPIO) University; Masters and Architect Certification for SharePoint; new Partner Business Productivity Online Services features and distributor model; and, Exchange 2010 Readiness Webcast Series and Demo Showcase. More information on these programs can be found at: http://partner.microsoft.com/businessproductivity

Availability: All Microsoft Worldwide Partner Conference attendees will receive invitations to participate in the Technical Preview program. Microsoft Office 2010 and related products will be available in the first half of 2010. More information about Office 2010 can be found at www.microsoft.com/Office2010 .

Wednesday, July 1, 2009

I’m am an MVP

mvp Finally I’m now a member of the MVP family.

I will have access to things I can talk about but I will be able to advice anybody with better suggestions because of that knowledge.

Feel free to talk to me as I am to talk to you.

Tuesday, June 2, 2009

How to implement “lock” with timeout?

Anybody who did any multithreaded application probably used the “lock” keyword. This is actually a good thing.

“lock” is the most optimized way to lock a resource. First let’s take a look at what lock really do. Here is the simple Account class we will use for this post.

using System.Threading;

namespace Banking
{
    public class Account
    {
        private readonly string _accountNumber;
        private double _balance;

        private Account(string accountNumber, double amount)
        {
            _accountNumber = accountNumber;
            Balance = amount;
        }

        public string AccountNumber
        {
            get { return _accountNumber; }
        }

        public double Balance
        {
            get { return _balance; }
            set { _balance = value; }
        }

        public static Account OpenNew(string accountNumber, double amount)
        {
            return new Account(accountNumber, amount);
        }

        public void Deposit(double amount)
        {
            Interlocked.Exchange(ref _balance, _balance + amount);
        }

        public void Withdraw(double amount)
        {
            Interlocked.Exchange(ref _balance, _balance - amount);
        }

        public static void Transfer(double amount, Account fromAccount, Account toAccount)
        {
            // Bad code here. Potential deadlock.
            lock (fromAccount)
            lock (toAccount)
            {
                fromAccount.Withdraw(amount);
                toAccount.Deposit(amount);
            }
        }

        public override string ToString()
        {
            return string.Format("{0} (Balance = {1})", _accountNumber, _balance);
        }
    }
}

Here are some important things to point out about this class:

  • The constructor is private to limit the creators of this class.
  • The public OpenNew method is the only way to create an instance. This ensure that every Account starts with a name and a balance.
  • Deposit and Withdraw methods are thread safe. They both uses Interlocked class which is has low level methods to modify values.
  • Transfer is not thread safe even though it uses locks. There is a potential deadlock if two thread transfer funds using the same accounts at the same time.

Most of the time the transfer method will work without any problem but the is a slight chance of deadlock. Of course this is a fairly simple method and in fact we can use another private object field to lock on like in this sample.

private static object _syncLock = new object();

public static void Transfer(double amount, Account fromAccount, Account toAccount)
{
    // Bad code here. Potential deadlock.
    lock (_syncLock)
    {
        fromAccount.Withdraw(amount);
        toAccount.Deposit(amount);
    }
}

That mean you will need to use that _syncLock object all the time to be consistent, even if you need to lock only one of the two accounts. And because Transfer is a static method we need to make the _syncLock object static too. That mean that any other call to Transfer will have to wait until this call finish. That is a huge performance issue.

What we really need is to be able to lock actual Account objects and recover from any deadlock. The best way to do this is to use timeouts on the locking process. The caller can catch timeouts and handle it properly instead of waiting forever. Here is a better Transfer method.

public static void Transfer(double amount, Account fromAccount, Account toAccount)
{
    bool fromLock = Monitor.TryEnter(fromAccount, 1000);
    bool toLock = Monitor.TryEnter(toAccount, 1000);
    try
    {
        if (fromLock && toLock)
        {
            fromAccount.Withdraw(amount);
            toAccount.Deposit(amount);
        }
    }
    finally
    {
        if (fromLock)
            Monitor.Exit(fromLock);

        if (toLock)
            Monitor.Exit(toLock);
    }
}

This is a lot more code to write. Actually this is not far from what the lock keyword would do. Because if you look at your code with Reflector you will see that lock does translate to Monitor.Enter and Monitor.Exit (your have to look in IL not in C#). So a simple lock statement like this.

lock(obj)
{
    // do somtehing
    Console.WriteLine("Locked");
}

Would be translated to.

Monitor.Enter(obj);
try
{
    // do somtehing
    Console.WriteLine("Locked");
}
finally
{
    Monitor.Exit(obj);
}

You won’t see it in C# (with Reflector) but if you look at IL code you will see exactly the same sequence twice.

So to solve our problem, would it be nice to have something like this?

public static void Transfer(double amount, Account fromAccount, Account toAccount)
{
    Safe.Lock(new [] {fromAccount, toAccount}, 1000, () =>
    {
        fromAccount.Withdraw(amount);
        toAccount.Deposit(amount);
    });
}

This look pretty much like the well known lock keyword, isn’t it? Now how can we do this? That’s better. The Safe static call has a Lock static method that take care of everything. The fist argument can be a single object or an array of objects. This allow locking multiple object at once. The Lock method use the Monitor.TryEnter to acquire lock on objects. If this can be done before the timeout occur the Action argument is executed.

Of course this code can and should be surrounded with a try-catch block. here is how to do so.

public static void Transfer(double amount, Account fromAccount, Account toAccount)
{
    var retries = 10;

    while (retries-- > 0)
    {
        try
        {
            Safe.Lock(new[] { fromAccount, toAccount }, 1000, () =>
            {
                fromAccount.Withdraw(amount);
                toAccount.Deposit(amount);
            });
            break;
        }
        catch (TimeoutException e)
        {
            if (retries == 0)
                throw;
            Thread.Sleep(100);
        }
    }
}

In this code snippet it will retry at most 10 time to lock toAccount and fromAccount before giving up. Notice that only the TimeoutException is handled, so any other exception will be thrown immediately and stop the process. The break at the end of the try block let us out as soon as it works.

This is a good timeout pattern and easy to implement in your own code. Give it a try and let me know if it works.

Here is the full code for the Safe class.

using System;
using System.Linq;
using System.Threading;

namespace MultithreadHelper
{
    public class Safe : IDisposable
    {
        private readonly object[] _padlocks;
        private readonly bool[] _securedFlags;

        private Safe(object padlock, int milliSecondTimeout)
        {
            _padlocks = new[] {padlock};
            _securedFlags = new[] {Monitor.TryEnter(padlock, milliSecondTimeout)};
        }

        private Safe(object[] padlocks, int milliSecondTimeout)
        {
            _padlocks = padlocks;
            _securedFlags = new bool[_padlocks.Length];
            for (int i = 0; i < _padlocks.Length; i++)
                _securedFlags[i] = Monitor.TryEnter(padlocks[i], milliSecondTimeout);
        }

        public bool Secured
        {
            get { return _securedFlags.All(s => s); }
        }

        public static void Lock(object[] padlocks, int millisecondTimeout, Action codeToRun)
        {
            using (var bolt = new Safe(padlocks, millisecondTimeout))
                if (bolt.Secured)
                    codeToRun();
                else
                    throw new TimeoutException(string.Format("Safe.Lock wasn't able to acquire a lock in {0}ms",
                                                             millisecondTimeout));
        }

        public static void Lock(object padlock, int millisecondTimeout, Action codeToRun)
        {
            using (var bolt = new Safe(padlock, millisecondTimeout))
                if (bolt.Secured)
                    codeToRun();
                else
                    throw new TimeoutException(string.Format("Safe.Lock wasn't able to acquire a lock in {0}ms",
                                                             millisecondTimeout));
        }

        #region Implementation of IDisposable

        public void Dispose()
        {
            for (int i = 0; i < _securedFlags.Length; i++)
                if (_securedFlags[i])
                {
                    Monitor.Exit(_padlocks[i]);
                    _securedFlags[i] = false;
                }
        }

        #endregion
    }
}

Starting a new user group in Montreal area

Maxime Rouiller and I are starting a new user group in the Montreal area.

It’s called Alt.Net Montreal.

Our goal with this user group is to raise the level of expertise of everyone interested. We already did a Coding Dojo couple of weeks ago and it went well.

We need your input to plan the future. Get involve and together we will build something cool.

All suggestions are welcomed.

Monday, June 1, 2009

Code Camp 2009 Montreal, a real Success

CodeCampLogo175.jpg

Code camp 2009 at Montreal was a real success.

There was about 300 people attending and 24 sessions available.

My session on Threading, UI and Data Model, was more than full. There was people standing in the back of the room. I had a lot present but I think I did it well, I hope.

For those of you who were there (and those who were not) you can find all the material on my web site (here).