The last year I have been working on a WPF frontend application that speaks to backend services through WCF. The WCF services were pretty standard request/response style services. For example:

image

The problem with this approach is that the services quickly got bloated. Some operations gut lumped into a MasterDataService which got pretty big. Another problem was that there was no real distinction between service operations that caused side effects (changed domain state) and read only operations.

Since then we have switched to a more simple service contract that looks like this:

image

Now all backend interactions go through this service. All operations in get to be their own command or query, so we get clear distinction between commands that modify state and queries that only read data and have no side effect. This interface requires that all commands inherit from the Command type and all queries inherit from the Query type. When you use inheritance in WCF you need to specify all subtypes using the KnownType attribute on the base type, for example:

image

This sucks, because this means that every time you add a new command you need to remember to add it as a known type to the base class. Fortunately the WCF team provides a way to provide known types at runtime by specify a static method:

image

The KnownTypesHelper will scan the contracts assembly for types inheriting from Command.

The implementation of the Backend service will lookup a command handler based on the type of command coming in. All command handlers implement the generic interface IHandleCommand<TCommand>. These command (and query) handlers are automatically registered in the inversion of control container. I really like the idea of having a separate handler for all service operations, it enforces the single responsibility principle in that each command handler only handles one command (compared to normal service implementations that might handler multiple operations). It also conforms to the open closed principle in that adding a new command and command handler requires no change to any other classes.

Example of a command handler:

image

One could ask why we did not use a message system like NServiceBus. The reason was that we figured that it would be an easier transition to move to a new WCF service contract than bring in a whole new framework. With this service in place it was really easy to rewrite operations (requests) into commands and operations that required a response to queries. Some operations that changed state AND returned data were split into a separate command and query (commands cannot return data).

Anyway, it has been working really well for us so try it out!

Yesterday I held a talk at a cornerstone event titled Pimp My Code at Hard Rock Café in Göteborg. The talk was about convention over configuration. I began by quickly describing the design philosophy and it's origins (in for example ruby on rails) and after that it was all code demo.

The code demo was a walkthrough of an application I had written (with some bits requiring live coding) that showcased a bunch of conventions. The application uses a lot of frameworks, for example Fluent NHibernate, StructureMap and AutoMapper. My point was not to dig deep into these frameworks but show show how they provide support for conventions and how that can be utilized in your application architecture. Among other things I showed how a Command/Query WCF service with automatic handler lookup could be achieved.

The frontend part of the application was taken from Rob Eisenberg MVVM mix talk. I modified it a bit and connected it to a real backend system. This application is treasure trove of brilliant ideas. Ideas that later materialized in the excellent Caliburn Micro framework.

Links

I will be doing the same presentation in Stockholm on december 6th at Debaser Medis. It is fully booked, so for those that have managed to get tickets, see you there!

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

Those who read the tile of this post should have figured out that this post is not about programming but is an account of an interesting trip I recently came home from. An amazing trip that took me through Kazakhstan, Kyrgyzstan and Uzbekistan. So if you want to know something about Central Asia please continue to read otherwise skip this post.

The trip focused on the history of this region and it’s people. The region is famous for it’s huge steps, incredible mountains and vistas and it’s rich history and art. It contains enchanting cities like Samarkand and Bukhara. Cities that has existed for millennia as important centers of commerce along the silk road.   

The most interesting part of the trip, and the one I wish to retell in more detail is the event that happened in Bishkek (the capital of Kyrgyzstan). We were invited to the parliament by Edil Baisalov, the current chief of staff of the interim government. For those who haven’t followed the news of this region: There was recently (April 6-15) and uprising in Kyrgyzstan where the then president Kurmanbek Bakiyev and his government was removed and replaced by an interim government. One of the many reasons for the uprising was the shutting down of news outlets that were critical of him and his son.

Why would a central figure from the new interim government invite a group of Swedish tourists?  Edil Baisalov was recently a political refuge fleeing Kyrgyzstan in late 2007. He feared imprisonment or assassination from president Bakiyev. He ended up in Sweden. He was very moved by the way Sweden accepted him and his family, how they were provided with an apartment, free language education and counsel. Now, when a group of Swedish tourists, in this time of political crisis, dared to enter the partially closed border and go forward with their trip through Kyrgyzstan, I think he felt obliged to say something.  I am not sure exactly what his motives were. 

The meeting took place on the 5th of May. The group of forty Swedish tourists was led into a big round table room in the parliament building. After a few minutes Edil Baisalov entered, greeting us in Swedish. He switched to English and continued to talk a little bit about himself, his history with activism for human rights and against corruption. Baisalov was a very open critic of the Bakiyev government, criticism that finally led to him having to flee from Kyrgyzstan. One thing that struck everyone from the beginning of the meeting was how very candid and honest this person sounded - this was no ordinary politician. And reading his profile in Wikipedia shows that this is a longtime activist, who is not used to have power and to be careful about what he says. 

_DSC0301And what Baisalov said was very interesting. He was asked: "How are you going to fix it?" referring to the current state of political crisis.

Baisalov said that the main focus is to organize free and fair elections this fall. They are working on changing the constitution in the direction to become a parliamentary republic, increase freedom of speech and improve the election and voting system.

Another focus he mentioned was to improve the situation for women - from education and job opportunity standpoint. He said that Kyrgyzstan has a population of very well educated women, almost more so than men (for example his mother was a doctor and his father a driver). This he said was a legacy from the Soviet times, when the situation between men and women were more equal (compared to today) and where everyone could get an education. He said that the situation for women has deteriorated and is regressing. This trend he wishes to reverse.

He was asked about relations to Russia and the States.

He answered by saying that Russia quickly accepted the interim government. Mainly (he thought) because Bakiyev had cheated Russia by accepting money from Russia to build a power station, but in return for the money Bakiyev should have barred the States the use of the military airport. He did not comply with this demand. This and other similar situations caused Russia to be offended by Bakiyev. This Baisalov thought was one of the reasons behind Russia’s quick approval of the uprising and ousting of Bakiyev.

With regards to the interim government and its relations to The States: He said that they were finding evidence that the States had bribed military and government officials in order to use the airport in Bishkek. "They fight for democracy in Afghanistan while they sacrifice democracy in Kyrgyzstan".  But he said that they (the interim government) will continue to allow the USA to use the airport and it is for the next elected government to decide on this issue.

He also mentioned that Bakiyev's son, known as the ‘prince’ and was touted as his almost certain successor, was visiting _DSC0308Washington a few months back (maybe to talk the military air base). He was accepted as an official of the government even though he was dismissing the democratic process in Kyrgyzstan. Baisalov mentioned these two stories as possible causes for the apprehension of the attitude of the USA towards the new interim government knowing that they supported and even encouraged the corruption within Bakiyev’s government.

He was also asked to talk about what happened during the uprising that led to the ousting of president Bakiyev. He mentioned a former minister of defense who was very popular among the military and critical of Bakiyev. This person was sentenced to prison for 8 years on trivial charges. During the uprising this person was freed and due to his popularity within the military helped secure their support for the demonstrators. Baisalov also mentioned that they recently had discovered 8 million dollar in a bank security box belonging to the previous defense minister (the one who had replaced the one who was sent to prison).

When Baisalov continued to describe what happened during the days of the uprising he choked, after multiple tries. It was clear that the pain from losing close friends just weeks earlier was too much and to soon. 88 people were killed and 500 hospitalized during the demonstrations.

He added his view on secularism, about the long term goal of reaching something like the social democracy in Scandinavia, about ways to make politics more about ideology and issues than about clans and individuals. Baisalov expressed following important opinion: “Even if we’ll lose the election we’ll win. The purpose is to gain a democratic system”. Much more was said but I cannot remember more specifics.

The whole group left the event in a strange mood. What we just had heard was so very unexpected and unique. It is not often you get the possibility to visit a parliament after an uprising and talk to one of the leading opposition leaders and activists in the country, or listen to a politician that felt so honest and human. Everyone walked out from that meeting with a great hope that Kyrgyzstan might be the first real democracy in Central Asia, if the elections and everything pan out. But because of Baisalov’s very personal account everyone also walked away with a personal connection to Kyrgyzstan and its fight for democracy and human rights. Personally I and I think many others in the group will be following the events very closely from now on.

In order to thank Baisalov for taking the time to talk to us, I would like to recommend to everyone to visit Kyrgyzstan. It is an amazingly beautiful country with a friendly and fun people.

North Kyrgyzstan, near Issyk-kul lake:
_DSC0155

_DSC0136

A very young goat herder that came and said hello:
_DSC0189

View from hotel I stayed at in central Bishkek:
_DSC0255

Registan in Samarkand:
_DSC0382

The cities were not what I expected, the cities Almaty, Bishkek and Tashkent where much more modern, clean and organized than I expected. But most of all they were green and beautiful, with parks everywhere and trees planted along every street. Still these are very poor countries, with vast differences between rich and poor and low expected living age. For example GDP per capita in Kyrgyzstan is 934$ compared to 52 000$ in Sweden (source Wolfram alpha). But I encourage everyone who wants to experience something different to travel to Central Asia. I will definitely be returning, maybe a hiking trip in Kyrgyzstan! 

I have blogged before about my visual studio color settings.

I just found a new site called Studiostyles that allows you to create visual studio color schemes via an intuitive interface (using javascript). You can then submit the scheme and have other people vote on it. I just submitted my theme: http://studiostyles.info/schemes/coding-instinct-theme  please vote it up!  You cannot select font type in the Studiostyles scheme creator, that is why it is displayed using courier new instead of the better Consolas font. 

Screenshots:

image

image

I would not recommend that you use the NHibernate "bag" mapping option for a many-to-many association, for example:

image

Never mind the strange domain, it is for a upcoming NHibernate presentation and I was too bored with the normal Order > OrderLines example domains.

The reason why using a bag for many-to-many is not recommended is because of the poor update behavior you get. If you were to load an entity (RebelEncounter in this case) that has a ShipsLost many-to-many association and just add another StarDestroyer to the ShipsLost collection like this:

image

This would be issued to the database:

many_to_many_using_bag

As you can see all the existing ships where deleted and then reinserted (along with the single new one you added). You can probably guess that this is far from ideal from a performance stand point. However it is easy to fix. First we have to change the mapping from bag to set:

image

NHibernate will use the HashedSet type from the Iese.Collection framework as the collection type when using the set mapping, that means that the type for the property can no longer be IList<StarDestroyer> since HashedSet does not implement that interface, however it does implement ICollection<T>. So we can change the code to something like this:

image

With this change NHibernate will now only insert the newly added entity:

image

Series Index

  • Part 1: Reusable controller actions & model inheritance
  • Part 2: Custom meta data provider (coming soon)

One of the great new features in ASP.NET MVC 2 is the template system. It is very similar to the template form helper system introduced in MvcContrib for MVC V1. For more information on the MVC template system read Brad Wilsons excellent series

This template system allows you to create convention based views and forms. The scenario that I have been working with the last couple of days is forms for reports. These forms are all very similar, that is they are all built around a couple of report filters/parameters built using dropdowns, checkboxes and datetime pickers.

My idea was that each report would only consist of a new report model and the most of the views, and controller actions could be reused.

Example:

public class ReportController : Controller
{
    public ViewResult ViewRequestForm()
    {
        return View("ViewForm", new RequestReportForm());
    }

    public ViewResult ViewOrderForm()
    {
        return View("ViewForm", new OrderReportForm());
    }

    [HttpPost]
    public ActionResult ViewReport(ReportForm form)
    {
        return View(form.GetReportParameters());
    }
}
The idea is to be able to reuse the same root view and the same action for all forms. The root view is only going look something like this:
<% Html.BeginForm("ViewReport", "Report"); %>

    <%=Html.EditorFor(x => x)  %>
    <input type="submit" value="submit" />

<% Html.EndForm(); %>

The EditorFor helper is going to start the MVC template engine. This template engine is first going to try to find a matching editor template for the report form model, since no specific template exists it is going to fallback to the default template for object, this template loops through all properties defined on the model and applies an editor for each property.

This is how the RequestReportForm and OrderReportForm model looks like:

public class RequestReportForm : ReportForm
{
    [DisplayName("Include canceled requests")]
    public bool IncludeCanceledRequests { get; set; }

    [DisplayName("Some parameter")]
    public string SomeParameter { get; set; }
    
    public override string GetReportParameters()
    {
        return "RequestFilter=" + IncludeCanceledRequests;
    }
}

public class OrderReportForm : ReportForm
{
    [DisplayName("Group by status")]
    public bool GroupByStatus { get; set; }

    [DisplayName("Some other paramater")]
    public string SomeOrderParameter { get; set; }

    public override string GetReportParameters()
    {
        return "something";
    }
}   

With the default templates built into MVC these models will be rendered like this:

RequestReportForm:

image

OrderReportForm:

image

If we would like to override these templates all we have to do is create our own partial view and name it string.ascx or bool.ascx and place it in a view folder named EditorTemplates, hopefully more on that in a later part in this blog series.

So sharing the same view for both of these report models seems to be very easy with the template system built into MVC 2 but how do we use the same controller action? We want to use the the controller action ViewReport that takes the base type ReportForm as a parameter. The standard DefaultModelBinder will not know which concrete class to bind to. The solution to this problem should be to create a custom model binder that will figure out which concrete form model to instantiate based on some field coming in the post data from the browser.

Example:
public class ReportFormModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var reportFormTypeName = bindingContext.ValueProvider.GetValue("ReportFormTypeName");

        var reportFormType = Type.GetType("MvcApplication1.Models.ReportForms." + reportFormTypeName.AttemptedValue);

        var model = bindingContext.ModelMetadata.Model;
        
        bindingContext.ModelMetadata = new ModelMetadata(ModelMetadataProviders.Current, 
                bindingContext.ModelMetadata.ContainerType,
                () => model, reportFormType, bindingContext.ModelMetadata.PropertyName);
        
        return base.BindModel(controllerContext, bindingContext);
    }
}

This custom model binder looks for a form data field "ReportFormTypeName". With this name it is possible to get the .NET Type (based on some namespace convention) and thereby create a new ModelMetadata object, now we can call the base implementation. All we need to do now is to add this ReportFormTypeName field as a hidden field to our form. Lets add it to the base class ReportForm, like this:

public abstract class ReportForm
{
    [HiddenInput(DisplayValue = false)]
    public string ReportFormTypeName
    {
        get { return this.GetType().Name; }
    }

    public abstract string GetReportParameters();

}

This is actually all we have to do to get the MVC template system to generate a hidden field named ReportFormTypeName that will contain the name of the concrete Type. Since both RequestReportForm and OrderReportForm inherit from ReportForm and since the default template for object will loop through all properties (including inherited properties) the hidden field will be included for all report forms.

So what have we accomplished? We can generate different report forms by only creating a new form model, the view rendering is shared and the controller action to generate the report is also shared. The controller action that handles the viewing of the report is in my case only responsible for concatenating all report parameters into a querystring to then pass to the report system, since this is so generic it can be handled in the same controller action for all report forms. I hope some of you understand what I am trying to show here, and I also hope to expand on the ideas in this post in later posts. Specifically how to make the report parameters more rich and how to control and override the layout using custom editor templates and custom metadata.

kick it on DotNetKicks.com