An another interesting aspect about Rob Eisenberg MVVM sample application is how it handles binding solely through conventions. That is no binding expressions in the XAML and no event hookups in the code behind. This is accomplished through a class named ViewModelBinder. This class takes a view model instance and a view instance. For each public property on the view model it will try to find a corresponding control with that name in the view, if found it will define the binding expression in code.

A simplified version of the method that handles the property bindings:

private static void BindProperties(FrameworkElement view, IEnumerable<PropertyInfo> properties)
{
    foreach (var property in properties)
    {
        var foundControl = view.FindName(property.Name) as DependencyObject;
        if(foundControl == null)
            continue;

        DependencyProperty boundProperty;

        if(!_boundProperties.TryGetValue(foundControl.GetType(), out boundProperty))
            continue;
        if(((FrameworkElement)foundControl).GetBindingExpression(boundProperty) != null)
            continue;

        var binding = new Binding(property.Name)
        {
            Mode = property.CanWrite ? BindingMode.TwoWay : BindingMode.OneWay,            
        };
        
        BindingOperations.SetBinding(foundControl, boundProperty, binding);        
    }
}

When a control matching a property is found it will lookup in a dictionary the DependencyProperty that the view model property should be bound to. For example for a TextBox control it will bind to the TextBox.TextProperty. In the complete version of this method (please check the sample app) it handles hookup of bool properties to a Border control's visibility property, automatically configuring a BoolToVisibility converter on the binding. An important part of the method is where it checks if any manual (in the XAML) binding exists, if it already exists it skips the property/control. This allows you to override the conventions with manual bindings in edge cases.

There is a similar method that handles binding of public methods to commands:

private static void BindCommands(object viewModel, FrameworkElement view, IEnumerable<MethodInfo> methods, IEnumerable<PropertyInfo> properties)
{
    foreach(var method in methods)
    {
        var foundControl = view.FindName(method.Name);
        if(foundControl == null)
            continue;

        var foundProperty = properties
            .FirstOrDefault(x => x.Name == "Can" + method.Name);

        var command = new ReflectiveCommand(viewModel, method, foundProperty);
        TrySetCommand(foundControl, command);
    }
}

If a method with the same name as control is found it will create a new ReflectiveCommand and define the command binding. For example a method named ExecuteSearch matches the name of a button in the view. It will also look for a property that begins with Can and ends with the method name (for example CanExecuteSearch), if this property is found it will be used to determine if the command can be raised (which will disable and enable the button for example). Raising a property change for this CanExecuteSearch property will result in the ReflectiveCommand raising the CanExecuteChanged (defined on the ICommand WPF interface). This is pretty great, now all that boring command setup will be handled by infrastructure code! I am in the process of trying to incorporate some of these ideas into parts of a system I currently working on. The conventions defined in the Robs sample app will only get you so far, the nice thing is that it is now very easy to add new ones. The scenario I was working on today was how to hookup a DoubleClick event on a grid item to a method on the view model. If the convention based binding could look for a method ending with "_OpenGridItem" it could then check for the first part of the method, try to find a control matching that first part and hookup the DoubleClickEvent and then call the view model method. First we need to refactor the BindCommands method into something more extendible.

Fist we need an interface:

public interface IMethodBindingConvetion
{
    void Apply(object viewModel, FrameworkElement view, MethodInfo method, IEnumerable<PropertyInfo> properties);
}

Now we can move the already existing convention into it's own class:

public class CommandToMethodBindingConvention : IMethodBindingConvetion
{
    public void Apply(object viewModel, FrameworkElement view, MethodInfo method, IEnumerable<PropertyInfo> properties)
    {
        var foundControl = view.FindName(method.Name);
        if (foundControl == null)
            return;

        var foundProperty = properties
            .FirstOrDefault(x => x.Name == "Can" + method.Name);

        var command = new ReflectiveCommand(viewModel, method, foundProperty);
        TrySetCommand(foundControl, command);
    }
    
    //...
}

Now lets try to create the convention that captures DoubleClick on a infragistic Grid and calls the corresponding OpenGridItem method on the view model.

public class DoubleClickGridToMethodConvention : IMethodBindingConvetion
{
    public void Apply(object viewModel, FrameworkElement view, MethodInfo method, IEnumerable<PropertyInfo> properties)
    {
        if (!method.Name.EndsWith("_OpenItem"))
            return;

        var gridName = method.Name.Replace("_OpenItem", "");
        var gridControl = view.FindName(gridName) as XamDataGrid;
        
        if (gridControl == null)
            throw new ConventionBindingException("Could not find matching control for the method " + method.Name);

        gridControl.MouseDoubleClick += (sender, e) =>
        {
            var item = FindClickedItem(sender, e);

            method.Invoke(viewModel, new object[] {item});
        };
    }  
}

If you want the method to be able to return IEnumerable<IResult>, something I talked about in yesterdays post (async programming using coroutines), then you need to handle the return value of the method invocation and pipe that through a ResultEnumerator.

Now that we have delegated the method conventions to specific classes the BindCommands method now looks like this:

private static readonly IList<IMethodBindingConvetion> _methodBindingConventions =
            new List<IMethodBindingConvetion>()
                {
                    new CommandToMethodBindingConvention(),
                    new DoubleClickGridToMethodConvention()

                };

private static void BindCommands(object viewModel, FrameworkElement view, IEnumerable<MethodInfo> methods, IEnumerable<PropertyInfo> properties)
{
    foreach(var method in methods)
    {
        foreach (var methodBindingConvention in _methodBindingConventions)
            methodBindingConvention.Apply(viewModel, view, method, properties);
    }
}

This method should perhaps be renamed to BindMethods. Anyway the point of this post was really to show how the convention based binding ideas in Robs sample application can be expanded to fit the application you are building.

If you work with WPF or Silverlight then you really should check out Rob Eisenberg presentation at MIX10 titled Build Your Own MVVM Framework. In that presentation he goes through a sample application that utilizes no code behind and no data binding or command binding expressions, all is hooked up through conventions and is driven solely from the presentation model. The sample app has about 500 lines of framework or infrastructure code that handles the view look up and convention based binding. I urge you to download it and really dig through it, it contains some awesome code and ideas.

But I will focus this blog post on one aspect of that sample app which is how Rob implemented async workflows. It might be a long post with a lot of code :)

Sequential async workflow:

public IEnumerable<IResult> ExecuteSearch()
{
        var search = new SearchGames
        {
                SearchText = SearchText
        }.AsResult();

        yield return Show.Busy();
        yield return search;

        var resultCount = search.Response.Count();

        if (resultCount == 0)
                SearchResults = _noResults.WithTitle(SearchText);
        else 
                SearchResults = _results.With(search.Response);

        yield return Show.NotBusy();
}

Before I dig into what the above code does and how it works I need to explain the problem. Anyone who has worked with WinForms/WPF/Silverlight knows that backend calls and other long running work needs to be done on a background thread. However all UI updates needs to be done on the UI thread. If you use ThreadPool.QueueUserWorkItem and you want to notify the UI that something has updated (issue a NotifyPropertyChanged for example) then you need to marshal the the call via the WPF dispatcher so the NotifyPropertyChanged happens on the UI thread. Another option is to use the BackgroundWorker that automatically executes the event RunWorkerCompleted on the same thread that called RunWorkerAsync.

Example:

private void ExecuteSearch()
{
      IsBusy = true;

        var worker = new BackgroundWorker();
        
        IEnumerable<SearchResult> results;
        
        worker.DoWork += (e, sender) =>
        {
                results = searchService.SearchGames(SearchText);
        };
        
        worker.RunWorkerCompleted += (e, sender) =>
        {
                if (results.Count == 0)
                        SearchResults = _noResults.WithTitle(SearchText);
                else 
                        SearchResults = _results.With(results);
                        
                IsBusy = false;        
        };

        worker.RunWorkerAsync();
}

This does not look so bad, we still have all the code in one method thanks to the lambdas. But imagine that we need to fetch the game (another backend call) and open the game screen if the returned search result only match exactly one game. In that case we would need to new up another BackgroundWorker inside the RunWorkerCompleted lambda and then hookup DoWork and RunWorkerCompleted. The code would be very messy (nested lambda callbacks) and it would be hard to read the sequential flow of the process.

Coroutines to the rescue. Wikipedia definition reads:

Coroutines are program components that generalize subroutines to allow multiple entry points for suspending and resuming execution at certain locations
But C# does not have that! Well it kind of does. You can get the same effect if you define an enumerator using yield returns. In a method that returns IEnumerable you can use yield return. The C# compiler will turn that method into a state machine (to implement the enumerator). Each time someone calls MoveNext (which happens once each foreach loop) the execution of the method will continue until the next yield return.

Example:

public IEnumerable<string> GetStrings()
{
    yield return "Hello";
    
    Console.WriteLine("execution continued");
    
    yield return "Good bye";
    
    Console.WriteLine("Nothing left");
}

This method will be turned into a MoveNext method on a generated class that implements IEnumerator:

private bool MoveNext()
{
    switch (this.<>1__state)
    {
        case 0:
            this.<>1__state = -1;
            this.<>2__current = "Hello";
            this.<>1__state = 1;
            return true;

        case 1:
            this.<>1__state = -1;
            Console.WriteLine("execution continued");
            this.<>2__current = "Good bye";
            this.<>1__state = 2;
            return true;

        case 2:
            this.<>1__state = -1;
            Console.WriteLine("Nothing left");
            break;
    }
    return false;
}

Ok, so now that we know how yield works we can use that to get something like Coroutines.

public IEnumerable<IResult> ExecuteSearch()
{
   // yield returns...
}

public interface IResult
{
   void Execute(); 
   event EventHandler Completed;
} 

Back to Robs sample app. The ExecuteSearch method above returns an IEnumerable of IResult, an interface that has an Execute method and a Completed event. The magic happens in how this enumerable is consumed, which is handled by the ResultEnumerator class:

public class ResultEnumerator
{
        private readonly IEnumerator<IResult> _enumerator;

        public ResultEnumerator(IEnumerable<IResult> children)
        {
                _enumerator = children.GetEnumerator();
        }

        public void Enumerate()
        {
                ChildCompleted(null, EventArgs.Empty);
        }

        private void ChildCompleted(object sender, EventArgs args)
        {
                var previous = sender as IResult;

                if(previous != null)
                        previous.Completed -= ChildCompleted;

                if(!_enumerator.MoveNext())
                        return;

                var next = _enumerator.Current;
                next.Completed += ChildCompleted;
                next.Execute();
        }
}

This class might take some time to get your head around. What happens is that we take the first IResult by calling MoveNext, we then hook up the Completed event and then call the Execute method. The interesting thing is that the Completed event is hooked up the the same method that we are in. The result is that the first IResult controls when the next IResult is fetched (the next IResult won't be fetched until the one before executes the Completed event). Ok, think about this until you understand it :)

Now lets look at how we can use this. Lets try to create a IResult that executes a lambda in a background thread then executes the Completed event on the UI thread.

public class BackgroundResult : IResult
{
        private readonly Action action;

        public BackgroundResult(Action action)
        {
                this.action = action;
        }

        public void Execute()
        {
                var backgroundWorker = new BackgroundWorker();
                backgroundWorker.DoWork += (e, sender) => action();
                backgroundWorker.RunWorkerCompleted += (e, sender) => Completed(this, EventArgs.Empty);
                backgroundWorker.RunWorkerAsync();
        }

        public event EventHandler Completed = delegate { };
}

Lets look at our example that used BackgroundWorker but rewrite it to use our new BackgroundResult:

private IEnumerable<IResult> ExecuteSearch()
{
    IsBusy = true;
    
    IEnumerable<SearchResult> results;

    yield return new BackgroundResult(() => 
    {
        results = searchService.Search(SearchText);
    });
    
    if (results.Count == 0)
       SearchResults = _noResults.WithTitle(SearchText);
    else 
       SearchResults = _results.With(results);
                
    IsBusy = false;            
}

Looks better doesn't it? The BackgroundResult will block the execution of the method until the action completes which will fire the Completed event (which happens on the UI thread) which in turn will resume the execution of the ExecuteSearch method. The requirement to show the game screen when there is only one match is now much easier to handle as we can yield another BackgroundResult to fetch the game. The method logic happens in the sequential order that it is written, making it much easier to read, test and debug.

Now to the complete version of the method from Robs example app:

public IEnumerable<IResult> ExecuteSearch()
{
        var search = new SearchGames
        {
                SearchText = SearchText
        }.AsResult();

        yield return Show.Busy();
        yield return search;

        var resultCount = search.Response.Count();

        if (resultCount == 0)
                SearchResults = _noResults.WithTitle(SearchText);
        else if (resultCount == 1 && search.Response.First().Title == SearchText)
        {
                var getGame = new GetGame
                {
                        Id = search.Response.First().Id
                }.AsResult();

                yield return getGame;
                yield return Show.Screen<ExploreGameViewModel>()
                        .Configured(x => x.WithGame(getGame.Response));
        }
        else SearchResults = _results.With(search.Response);

        yield return Show.NotBusy();
}

In the complete version he handles the case where there is only one match, in that case GetGame query is also issued to the backend. Before I end this post I will just highlight another interesting aspect of this sample and that is how Rob handles backend interaction. Instead of directly calling a IBackend service he returns an IQueryResult or ICommandResult which will handle the execution of the backend call and the thread marshalling. This improves the testability as the method will not require any mocking to test.

It's not trivial stuff, it takes some time to get your head around how the ResultEnumerator works and what it makes possible. But I think it is a pretty brilliant solution to keep complex async workflows in the same place and be able to read them sequentially. I am not sure if it is the same thing but if I remember correctly I think the C# team is looking at making this easier in C# 5 with an async keyword. Does anyone know how this implementation of coroutines compares to the async features in F#?

Check out the full sample application

If you use NHibernate heavily then you have a lot to gain from NHProfiler. It is a great tool for identifying problems with how you use NHibernate and how you access and update data. But I think its greatest strength is as a learning tool, as it is makes it easy to understand how NHibernate works and what the consequences of each mapping setup are.

Ok, this post is not just going to be free advertising for Ayende. A nice feature in NHProfiler is that it will show you the context of the data access. For web apps it will show the URL that triggered the data access, for WCF apps it will show the WCF service and operation name.

Example:
image

Here you see that ContractService and operation GetContractStatuses was called and generated one database call. This context is very nice to have when profiling and tuning your application. However in the current project that I am working on we have moved from classic WCF with services and operations to a generic WCF command & query service with just two operations  (SendCommand & SendQuery). This makes the context not so useful anymore.

image

Sorry for the censored image, it hides the project name. Anyway here the WCF service and operation name is not helping much as we do not se what command or query was issued. Fortunately NHProfiler offers a way to programmatically set the context. In order to set the context for this generic command & query service I implemented a ParameterInspector (a WCF extensibility point) in which I set the NHProfiler context.

Here is the code:

public class NHProfMessageInspector : IParameterInspector
{
        public object BeforeCall(string operationName, object[] inputs)
        {
                
                var typeName = inputs[0].GetType().Name;
                var commandOrQuery = "";
                
                if (typeName.EndsWith("Query"))
                {
                        commandOrQuery = "Query";
                        typeName = typeName.Substring(0, typeName.Length - 5);
                }
                if (typeName.EndsWith("Command"))
                {
                        commandOrQuery = "Command";
                        typeName = typeName.Substring(0, typeName.Length - 7);
                }

                var contextString = string.Format("{0} : {1}", commandOrQuery, typeName.ToSentenceStyle());
                SetContext(contextString);

                return null;
        }

        public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
        {
                SetContext(null);
        }

        private void SetContext(string value)
        {
                Assembly profilerAsm = null;

                try
                {
                        profilerAsm = Assembly.Load("HibernatingRhinos.Profiler.Appender");
                }
                catch (Exception) { return; }

                if (profilerAsm == null)
                        return;

                var profilerIntegration = profilerAsm.GetType("HibernatingRhinos.Profiler.Appender.ProfilerIntegration");
                if (profilerIntegration == null)
                        return;

                var currentContext = profilerIntegration.GetProperty("CurrentSessionContext");

                currentContext.SetValue(null, value, null);
        }
}

The BeforeCall method checks the first input type and creates a nice context string based on the type name. The SetContext method does the integration with NHProfiler. This is done through some reflection (in order to not have a strong reference to HibernatingRhinos.Profiler.Appender.dll and be version independent).

The result:
image

Now the context is much more useful! The same approach should be interesting for other people who also use a generic WCF interface or for example NServiceBus. Another option is to set the NHProfiler context in an integration test base class. This could be useful for example if you have a suite of repository tests and you want the text fixture name to appear as the context in NHProfiler.

imageA couple of hours ago I finished a presentation about NHiberante at the Developer Summit 2010 conference being held here in Stockholm.

I have worked with NHibernate in many projects, some greenfield projects but mostly replacing an existing data layer. I have introduced it to many teams. In those teams I have always been the NHibernate guy. The person that people turn to when faced with some NHibernate related problem. So when I started to prepare for this presentation I asked myself what is it that is causing these problems, what is it that people are missing in there understanding?

So the focus of the talk centered around these areas:

Identity Map (L1 Cache)
Understanding how the identity map is an integral part of NHibernate is very important. If you are not aware that you share instances for entities with the same id you can run into some strange bugs and side effects. The identity map is probably one of the main causes of problems when replacing an old DAL layer (that do not use an identity map) with an ORM.

Unit Of Work
Of course it is important to know how the Unit Of Work in NHibernate works, it’s relation to Flush and Transaction (FlushMode Commit).

Session Managementimage
Important to use the session correctly (i.e. do not open and close it in the data layer).   

Cascading
Understanding cascading can be tricky, especially how correctly to use cascade=”none” and how that works in relation to transient instances (it doesn’t). It is important to understand that NHibernate persists all changes to modified entities that are associated with an open session, no matter if you set cascade to none. 

Attached & Detached
It is very important to understand what it means that an instance is attached/associated with an open session. In the talk I show the result when you try to persist a modified detached instance. I also show how you can solve that issue by associating the detached instance with an open session (before the modification) by calling session.Lock and how you can as your last option use session.Merge to update modified detached instances.

Lazy Loading & Proxy Objects
In the talk I show how NHibernate’s lazy loading works via proxy objects and what issues you might run into. For example trying to check the concrete type in an inheritance chain won’t work as the type will always be the proxy object.

ID Generation & unsaved-valueimage
It is important to understand how NHibernate determines if an instance is transient or not and how that plays into id generation. If you need to use assigned id you can still let NHibernate know if an instance is transient or not by using a version column.

Concurrency
I ended the talk by showing how to handle concurrency (by using a version column).

 

If all NHiberante users have a good grasp of the above areas I think they would experience a lot less bugs and head aches. So for those that attended the talk I hope they will not be making the same mistakes I have made and have seen others make. 

Here is a link to download the powerpoint slides