<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://nhforge.org/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>NHibernate blog : WPF</title><link>http://nhforge.org/blogs/nhibernate/archive/tags/WPF/default.aspx</link><description>Tags: WPF</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP1 (Build: 31106.3070)</generator><item><title>NHibernate and WPF: Asynchronous calls</title><link>http://nhforge.org/blogs/nhibernate/archive/2009/11/22/nhibernate-and-wpf-asynchronous-calls.aspx</link><pubDate>Mon, 23 Nov 2009 01:48:18 GMT</pubDate><guid isPermaLink="false">45f813f2-f1c4-4eda-a619-288e3cadc793:548</guid><dc:creator>Jose Romaniello</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://nhforge.org/blogs/nhibernate/rsscomments.aspx?PostID=548</wfw:commentRss><comments>http://nhforge.org/blogs/nhibernate/archive/2009/11/22/nhibernate-and-wpf-asynchronous-calls.aspx#comments</comments><description>&lt;p&gt;I will show in this article an approach to make an asynchronous call to the model, to prevent the user interface to freeze. If you read about WPF, you will see there is a lot of information and claims “don’t freeze the ui thread”, “build UI more responsiveness” and so on.&lt;/p&gt;  &lt;h2&gt;What you should know&lt;/h2&gt;  &lt;p&gt;NHibernate Sessions are not thread safe, so don’t use a single session in multiples threads. Conversation-per-Business-Transaction use the same session for a conversation. The end of the conversation flush the changes and close the session, the abort of the conversation discard changes and close the session.&lt;/p&gt;  &lt;p&gt;You can’t update UI controls from a non-ui thread. Some people read this like “don’t set a ViewModel property from a non UI thread”. But this is not true, because it depends where do you raise the property changed notification thank to my friend &lt;a href="http://schuager.com/"&gt;German Schuager&lt;/a&gt; for reminding me &lt;a href="http://devlicio.us/blogs/rob_eisenberg/archive/2009/09/08/dispelling-a-common-wpf-silverlight-myth.aspx"&gt;this post&lt;/a&gt; from &lt;a href="http://devlicio.us/blogs/rob_eisenberg"&gt;Rob Eisenberg&lt;/a&gt;. However, I’m not using this trick for now.&lt;/p&gt;  &lt;p&gt;Asynchronous code is &lt;u&gt;&lt;strong&gt;HARD&lt;/strong&gt;&lt;/u&gt; to unit test. I will like to separate the asynchronous code in few units more testable and test “in-sync”.&lt;/p&gt;  &lt;h1&gt;The problem&lt;/h1&gt;  &lt;p&gt;The load of the artist list is very slow and this causes the user interface to freeze. This is very irritating for the end user.&lt;/p&gt;  &lt;p&gt;I will break the async problem in the following three steps:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Preview: Before start the operation we want to let the user know that the operation is in-process with some message in the user interface or maybe an hourglass. &lt;/li&gt;    &lt;li&gt;Process: The heavy operation. &lt;/li&gt;    &lt;li&gt;Completed: The operation has ended and we want to show the result to the UI. &lt;/li&gt; &lt;/ol&gt;  &lt;h1&gt;Show me the code&lt;/h1&gt;  &lt;p&gt;This my generic implementation of ICommand for make async calls.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;AsyncCommandWithResult&lt;/span&gt;&amp;lt;TParameter, TResult&amp;gt;
        : IAsyncCommandWithResult&amp;lt;TParameter, TResult&amp;gt;
{
    &lt;span style="color:blue;"&gt;private readonly &lt;/span&gt;Func&amp;lt;TParameter, &lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;gt; _canAction;
    &lt;span style="color:blue;"&gt;private readonly &lt;/span&gt;Func&amp;lt;TParameter, TResult&amp;gt; _action;

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;AsyncCommandWithResult(Func&amp;lt;TParameter, TResult&amp;gt; action)
    {
        _action = action;
    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;AsyncCommandWithResult(
            Func&amp;lt;TParameter, TResult&amp;gt; action,
            Func&amp;lt;TParameter, &lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;gt; canAction)
    {
        _action = action;
        _canAction = canAction;
    }


    &lt;span style="color:blue;"&gt;public &lt;/span&gt;Action&amp;lt;TParameter, TResult&amp;gt; Completed { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;set&lt;/span&gt;; }
    &lt;span style="color:blue;"&gt;public &lt;/span&gt;Action&amp;lt;TParameter&amp;gt; Preview { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;set&lt;/span&gt;; }
    &lt;span style="color:blue;"&gt;public bool &lt;/span&gt;BlockInteraction { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;set&lt;/span&gt;; }

    &lt;span style="color:blue;"&gt;public void &lt;/span&gt;Execute(&lt;span style="color:blue;"&gt;object &lt;/span&gt;parameter)
    {
        &lt;span style="color:green;"&gt;//Execute Preview
        &lt;/span&gt;Preview((TParameter)parameter);

        &lt;span style="color:green;"&gt;//This is the async actions to take... 
        &lt;/span&gt;worker.DoWork += (sender, args) =&amp;gt;
        {
            args.Result = _action((TParameter)parameter);

        };

        &lt;span style="color:green;"&gt;//When the work is complete, execute the postaction.
        &lt;/span&gt;worker.RunWorkerCompleted += (sender, args) =&amp;gt;
        {
            Completed((TParameter)parameter, (TResult)args.Result);
            CommandManager.InvalidateRequerySuggested();
        };

        &lt;span style="color:green;"&gt;//Run the async work.
        &lt;/span&gt;worker.RunWorkerAsync();
    }

    [DebuggerStepThrough]
    &lt;span style="color:blue;"&gt;public bool &lt;/span&gt;CanExecute(&lt;span style="color:blue;"&gt;object &lt;/span&gt;parameter)
    {
        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(BlockInteraction &amp;amp;&amp;amp; worker.IsBusy)
            &lt;span style="color:blue;"&gt;return false&lt;/span&gt;;

        &lt;span style="color:blue;"&gt;return &lt;/span&gt;_canAction == &lt;span style="color:blue;"&gt;null &lt;/span&gt;? &lt;span style="color:blue;"&gt;true &lt;/span&gt;:
                _canAction((TParameter)parameter);
    }

    &lt;span style="color:blue;"&gt;public event &lt;/span&gt;EventHandler CanExecuteChanged
    {
        &lt;span style="color:blue;"&gt;add &lt;/span&gt;{ CommandManager.RequerySuggested += &lt;span style="color:blue;"&gt;value&lt;/span&gt;; }
        &lt;span style="color:blue;"&gt;remove &lt;/span&gt;{ CommandManager.RequerySuggested -= &lt;span style="color:blue;"&gt;value&lt;/span&gt;; }
    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;TResult ExecuteSync(TParameter obj)
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;_action(obj);
    }

    &lt;span style="color:blue;"&gt;private static readonly &lt;/span&gt;BackgroundWorker worker
            = &lt;span style="color:blue;"&gt;new &lt;/span&gt;BackgroundWorker();
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;h1&gt;Testing the ViewModel&lt;/h1&gt;

&lt;p&gt;Here you can see the test of the three steps. None of these test involves asynchronous calls.&lt;/p&gt;

&lt;pre class="code"&gt;[Test]
&lt;span style="color:blue;"&gt;public void &lt;/span&gt;preview_of_load_list_should_show_status_info()
{
    var browseArtistVm = &lt;span style="color:blue;"&gt;new &lt;/span&gt;BrowseArtistViewModel(
                &lt;span style="color:blue;"&gt;new &lt;/span&gt;Mock&amp;lt;IBrowseArtistModel&amp;gt;().Object,
                &lt;span style="color:blue;"&gt;new &lt;/span&gt;Mock&amp;lt;IViewFactory&amp;gt;().Object);
    
    browseArtistVm.LoadListCommand.Preview(&lt;span style="color:blue;"&gt;null&lt;/span&gt;);
    browseArtistVm.Status.Should().Be.EqualTo(&lt;span style="color:#a31515;"&gt;&amp;quot;Loading artists...&amp;quot;&lt;/span&gt;);
}

[Test(Description = &lt;span style="color:#a31515;"&gt;&amp;quot;Check if the process call the model&amp;quot;&lt;/span&gt;)]
&lt;span style="color:blue;"&gt;public void &lt;/span&gt;load_list_command_should_load_artists_coll()
{
    var artistModel = &lt;span style="color:blue;"&gt;new &lt;/span&gt;Mock&amp;lt;IBrowseArtistModel&amp;gt;();

    var artists = &lt;span style="color:blue;"&gt;new &lt;/span&gt;List&amp;lt;Artist&amp;gt; {&lt;span style="color:blue;"&gt;new &lt;/span&gt;Artist {Name = &lt;span style="color:#a31515;"&gt;&amp;quot;Jose&amp;quot;&lt;/span&gt;}};

    artistModel.Setup(am =&amp;gt; am.GetAllArtists()).Returns(artists);

    var browseArtistVm = &lt;span style="color:blue;"&gt;new &lt;/span&gt;BrowseArtistViewModel(
                            artistModel.Object, 
                            &lt;span style="color:blue;"&gt;new &lt;/span&gt;Mock&amp;lt;IViewFactory&amp;gt;().Object);

    browseArtistVm.LoadListCommand.ExecuteSync(&lt;span style="color:blue;"&gt;null&lt;/span&gt;);

    artistModel.VerifyAll();
}

[Test]
&lt;span style="color:blue;"&gt;public void &lt;/span&gt;completed_of_load_l_should_load_the_list_and_change_status()
{
    var browseArtistVm = &lt;span style="color:blue;"&gt;new &lt;/span&gt;BrowseArtistViewModel(
                &lt;span style="color:blue;"&gt;new &lt;/span&gt;Mock&amp;lt;IBrowseArtistModel&amp;gt;().Object,
                &lt;span style="color:blue;"&gt;new &lt;/span&gt;Mock&amp;lt;IViewFactory&amp;gt;().Object);

    var artists = &lt;span style="color:blue;"&gt;new &lt;/span&gt;List&amp;lt;Artist&amp;gt;();

    browseArtistVm.LoadListCommand.Completed(&lt;span style="color:blue;"&gt;null&lt;/span&gt;, artists);

    browseArtistVm.Artists.Should().Be.SameInstanceAs(artists);
    browseArtistVm.Status.Should().Be.EqualTo(&lt;span style="color:#a31515;"&gt;&amp;quot;Finished&amp;quot;&lt;/span&gt;);
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;h1&gt;Implementing the ViewModel&lt;/h1&gt;

&lt;p&gt;The LoadListCommand of the ViewModel is:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public virtual &lt;/span&gt;IAsyncCommandWithResult&amp;lt;&lt;span style="color:blue;"&gt;object&lt;/span&gt;, IList&amp;lt;Artist&amp;gt;&amp;gt; LoadListCommand
{
    &lt;span style="color:blue;"&gt;get
    &lt;/span&gt;{
        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(_loadListCommand == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
        {
            _loadListCommand = 
                &lt;span style="color:blue;"&gt;new &lt;/span&gt;AsyncCommandWithResult&amp;lt;&lt;span style="color:blue;"&gt;object&lt;/span&gt;, IList&amp;lt;Artist&amp;gt;&amp;gt;
                        (o =&amp;gt; _browseArtistModel.GetAllArtists())
                        {
                            BlockInteraction = &lt;span style="color:blue;"&gt;true&lt;/span&gt;,
                            Preview = o =&amp;gt; Status = &lt;span style="color:#a31515;"&gt;&amp;quot;Loading artists...&amp;quot;&lt;/span&gt;,
                            Completed = (o, artists) =&amp;gt;
                                {
                                    Artists = artists;
                                    Status = &lt;span style="color:#a31515;"&gt;&amp;quot;Finished&amp;quot;&lt;/span&gt;;
                                }
                        };
        }
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;_loadListCommand;
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;h1&gt;Final conclusion&lt;/h1&gt;

&lt;p&gt;You must to remember that an NHibernate Session should be used in only one thread. This model for Browsing Artists has only one method with EndMode = End. This means session-per-call, so each time I click the LoadCommand the model start a new conversation and session. If you have a ViewModel with multiples operations within the same Conversation better you use something else, or use AsyncCommand everywhere within the VM.&lt;/p&gt;

&lt;p&gt;There are a lot of alternatives to this approach, here are some;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/wewwczdw.aspx"&gt;Event-based asynchronous pattern&lt;/a&gt;. &lt;/li&gt;

  &lt;li&gt;Use background thread directly in your ViewModel. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Use this only when you need it. You don’t have to do this everywhere. Some operations are very fast and inexpensive.&lt;/p&gt;

&lt;p&gt;Divide and conquer; I really like this way of testing. Don’t bring asynchronous things to your unit tests.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://nhforge.org/aggbug.aspx?PostID=548" width="1" height="1"&gt;</description><category domain="http://nhforge.org/blogs/nhibernate/archive/tags/WPF/default.aspx">WPF</category></item><item><title>NHibernate and WPF: Test Databinding with Caliburn</title><link>http://nhforge.org/blogs/nhibernate/archive/2009/11/15/nhibernate-and-wpf-test-databinding-with-caliburn.aspx</link><pubDate>Sun, 15 Nov 2009 16:42:25 GMT</pubDate><guid isPermaLink="false">45f813f2-f1c4-4eda-a619-288e3cadc793:542</guid><dc:creator>Jose Romaniello</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://nhforge.org/blogs/nhibernate/rsscomments.aspx?PostID=542</wfw:commentRss><comments>http://nhforge.org/blogs/nhibernate/archive/2009/11/15/nhibernate-and-wpf-test-databinding-with-caliburn.aspx#comments</comments><description>&lt;p&gt;As I said before, for the Chinook Media Manager I’m not using neither &lt;a href="http://www.codeplex.com/caliburn"&gt;Caliburn&lt;/a&gt; nor &lt;a&gt;Prism&lt;/a&gt;.     &lt;br /&gt;But, whenever I found a limitation on the current tools, I start looking a solution elsewhere. This is how I meet Caliburn.Testability, a great tool.&lt;/p&gt;  &lt;h1&gt;The problem&lt;/h1&gt;  &lt;p&gt;We don’t know what would be the ViewModel for the View at design time. This is the reason why we don’t have intelliscence in XAML, and in general our databinding are not strongly typed in XAML. So, we can write “naem” instead of “Name”.&lt;/p&gt;  &lt;h1&gt;The solution&lt;/h1&gt;  &lt;p&gt;Caliburn has a great tool named “Caliburn Testability”, you can read the full &lt;a href="http://devlicio.us/blogs/rob_eisenberg/archive/2009/10/30/nhprof-and-caliburn-testability.aspx"&gt;post here&lt;/a&gt;. As &lt;a href="http://devlicio.us/blogs/rob_eisenberg/"&gt;Rob Eisenberg&lt;/a&gt; said, I take this one step farther to build an automatic test.&lt;/p&gt;  &lt;p&gt;This is the code:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DataBindingValidator
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;private static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;BindingValidator &lt;/span&gt;ValidatorFor(
            &lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;guiElement, &lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;presenterType)
    {
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;boundType = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;BoundType&lt;/span&gt;(presenterType);
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;instance = (&lt;span style="color:#2b91af;"&gt;DependencyObject&lt;/span&gt;)&lt;span style="color:#2b91af;"&gt;Activator&lt;/span&gt;.CreateInstance(guiElement);
        &lt;span style="color:#2b91af;"&gt;IElement &lt;/span&gt;element = &lt;span style="color:#2b91af;"&gt;Bound&lt;/span&gt;.DependencyObject(instance, boundType);
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;BindingValidator&lt;/span&gt;(element);
    }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Validate the bindings of a keyvalue pair 
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &lt;/span&gt;&lt;span style="color:green;"&gt;where the key is the View type and the 
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &lt;/span&gt;&lt;span style="color:green;"&gt;value is the ViewModel type.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ValidationResult&lt;/span&gt;&amp;gt;
            Validate(&lt;span style="color:#2b91af;"&gt;IDictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt;&amp;gt; viewViewModelDictionary)
    {
        &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;viewViewModel &lt;span style="color:blue;"&gt;in &lt;/span&gt;viewViewModelDictionary)
        {
            &lt;span style="color:#2b91af;"&gt;BindingValidator &lt;/span&gt;validator
                = ValidatorFor(viewViewModel.Key, viewViewModel.Value);
            &lt;span style="color:#2b91af;"&gt;ValidationResult &lt;/span&gt;validatorResult = validator.Validate();
            &lt;span style="color:blue;"&gt;yield return &lt;/span&gt;validatorResult;
        }
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This class validate a IDictionary&amp;lt;Type, Type&amp;gt;, the key is the “View” type, and the value is the ViewModel type. The View need to have a public constructor without args, this test will create an instance of the View. The ViewModel type could be a class, could be abstract and even an interface!&lt;/p&gt;

&lt;p&gt;The test is really easy, if you are using Caliburn, you already have a IViewStrategy. The Chinook Media Manager use a convention based approach and I don’t have an special artifact for this purpose. So my test looks as follows:&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;pre class="code"&gt;[&lt;span style="color:#2b91af;"&gt;TestFixture&lt;/span&gt;]
&lt;span style="color:blue;"&gt;public class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;TestDataBindings
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;private static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;GetViewForViewModel(&lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;viewModelType)
    {
        &lt;span style="color:blue;"&gt;string &lt;/span&gt;viewName = viewModelType.Name.Replace(&lt;span style="color:#a31515;"&gt;&amp;quot;ViewModel&amp;quot;&lt;/span&gt;, &lt;span style="color:#a31515;"&gt;&amp;quot;View&amp;quot;&lt;/span&gt;);
        &lt;span style="color:blue;"&gt;string &lt;/span&gt;viewFullName = &lt;span style="color:blue;"&gt;string&lt;/span&gt;.Format(&lt;span style="color:#a31515;"&gt;&amp;quot;ChinookMediaManager.GUI.Views.{0}, ChinookMediaManager.GUI&amp;quot;&lt;/span&gt;, viewName);
        &lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;viewType = &lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt;.GetType(viewFullName, &lt;span style="color:blue;"&gt;true&lt;/span&gt;);
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;viewType;
    }

    [&lt;span style="color:#2b91af;"&gt;Test&lt;/span&gt;]
    &lt;span style="color:blue;"&gt;public void &lt;/span&gt;AllDatabindingsAreOkay()
    {
        &lt;span style="color:blue;"&gt;bool &lt;/span&gt;fail = &lt;span style="color:blue;"&gt;false&lt;/span&gt;;
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;databindingValidator = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DataBindingValidator&lt;/span&gt;();

        &lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;examplePresenterType = &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;AlbumManagerViewModel&lt;/span&gt;);

        &lt;span style="color:blue;"&gt;var &lt;/span&gt;dictionary = examplePresenterType.Assembly.GetTypes()
                                            .Where(type =&amp;gt; type.Namespace.EndsWith(&lt;span style="color:#a31515;"&gt;&amp;quot;ViewModels&amp;quot;&lt;/span&gt;))
                                            .ToDictionary(vmType =&amp;gt; GetViewForViewModel(vmType), vmType =&amp;gt; vmType);

        

        &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;validationResult &lt;span style="color:blue;"&gt;in &lt;/span&gt;databindingValidator.Validate(dictionary))
        {
            &lt;span style="color:blue;"&gt;if&lt;/span&gt;(validationResult.HasErrors)
            {
                &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(validationResult.ErrorSummary);
                fail = &lt;span style="color:blue;"&gt;true&lt;/span&gt;;
            }
        }

        fail.Should().Be.False();
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;If you have any error in your databinding this test will fail. This test also show you a list of the DataBinding errors in the console, and for each error the full path inside the View:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/nhibernate/image_5F00_6D1D2B0A.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/nhibernate/image_5F00_thumb_5F00_40968BD5.png" width="885" height="115" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;You can see here the “nesting level”, Album is a property of the EditAlbumViewModel, Title is a property in the Album type. Titl&lt;u&gt;o&lt;/u&gt; doesn’t exist. EditAlbumView.Grid.TextBox is the full xaml path to the control holding the databinding. It show Grid and TextBox because these elements doesn’t have a name in xaml.&lt;/p&gt;

&lt;p&gt;This is why I use Caliburn.Testability in Chinook Media Manager. &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://nhforge.org/aggbug.aspx?PostID=542" width="1" height="1"&gt;</description><category domain="http://nhforge.org/blogs/nhibernate/archive/tags/NHibernate/default.aspx">NHibernate</category><category domain="http://nhforge.org/blogs/nhibernate/archive/tags/WPF/default.aspx">WPF</category></item><item><title>NHibernate and WPF: The GuyWire</title><link>http://nhforge.org/blogs/nhibernate/archive/2009/11/07/nhibernate-and-wpf-the-guywire.aspx</link><pubDate>Sat, 07 Nov 2009 19:12:52 GMT</pubDate><guid isPermaLink="false">45f813f2-f1c4-4eda-a619-288e3cadc793:539</guid><dc:creator>Jose Romaniello</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://nhforge.org/blogs/nhibernate/rsscomments.aspx?PostID=539</wfw:commentRss><comments>http://nhforge.org/blogs/nhibernate/archive/2009/11/07/nhibernate-and-wpf-the-guywire.aspx#comments</comments><description>&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note: I owe this knowledge to my friend &lt;a href="http://fabiomaulo.blogspot.com/"&gt;Fabio Maulo&lt;/a&gt;, so I would like to thank him for teaching me and letting me share.&lt;/em&gt;&lt;/strong&gt; &lt;/p&gt;  &lt;h1&gt;Introduction&lt;/h1&gt;  &lt;p&gt;I will show you in this post a nice way to configure your IoC container and some other aspects of your applications. I assume for this article that you have good knowledge of dependency injection and inversion of control.&lt;/p&gt;  &lt;h1&gt;The problem&lt;/h1&gt;  &lt;p&gt;There was a time when we used to configure our containers with xml, and all was fine. Then we started to use fluent and strongly typed interfaces and a problem became more frequent and acute. Basically, when we use a fluent interface, we do something like this:&lt;/p&gt;  &lt;pre class="brush: csharp;"&gt;container.Register(Component.For&amp;lt;IAlbumRepository&amp;gt;()
                       .ImplementedBy&amp;lt;AlbumRepository&amp;gt;()
                       .LifeStyle.Transient);&lt;/pre&gt;

&lt;p&gt;IAlbumRepository is in Chinook.Data and AlbumRepository is in Chinook.Data.Impl.&amp;#160; &lt;br /&gt;The problem is not *how* but &lt;strong&gt;&lt;u&gt;*where*&lt;/u&gt;&lt;/strong&gt;. Where do you do this? &lt;/p&gt;

&lt;p&gt;Most people will say “The startup project”. One of the goal that we look when using IoC is:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;..decoupling of the execution of a certain task from implementation.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Pay attention to the “Decoupling” part. If you want “decoupling”: Why do you add all those references in your startup project?&lt;/p&gt;

&lt;p&gt;This is a &lt;a href="http://www.ndepend.com/"&gt;NDepend&lt;/a&gt; extracted graph of the Northwind example that comes with &lt;a href="http://www.sharparchitecture.net/"&gt;Sharp Architecture&lt;/a&gt;:&lt;/p&gt;

&lt;p&gt;&lt;img border="0" src="http://content.screencast.com/users/JoseFR/folders/Jing/media/82a585f2-6ae5-4f3b-ba29-fc3f283be6ad/2009-10-26_1333.png" width="585" height="336" alt="" /&gt;&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;If you look at the Northwind.Web assembly you will see that it has a reference even to NHibernate. It has a reference to Northwind.Data (repositories that use NHibernate). The contract interface of repositories is in Northwind.Core. Also you can see that the start up project need a reference to Castle Container. If I want a loosely coupled solution, I don’t want some of those references.&lt;/p&gt;

&lt;p&gt;Pay atention; the northwind example of Sharp Architecture is a very good example, is a good architecture, and this is neither a complain nor a criticism. I’m pretty sure that it defines interfaces and implementations separately, as I’m pretty sure that controllers depends upon IRepositories. But, I think it has a problem at reference level. The main problem is because the initialization of the container is in a wrong place. You could see the initialization script &lt;a href="http://github.com/codai/Sharp-Architecture/blob/master/src/NorthwindSample/app/Northwind.Web/CastleWindsor/ComponentRegistrar.cs"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;So, what I’m looking for is:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;I don’t want references to concrete implementations in my startup project. &lt;/li&gt;

  &lt;li&gt;I don’t want to depend upon a specific IoC container technology. &lt;/li&gt;

  &lt;li&gt;And finally I don’t want to configure my container in the startup project, its is another “aspect” of my application like the repositories! &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;/p&gt;

&lt;h1&gt;The Solution&lt;/h1&gt;

&lt;p&gt;The solution is very simple. Take the container initialization to another place. &lt;/p&gt;

&lt;p&gt;We used to call this place “The GuyWire”, in italian “Cavo Portante”, in spanish “Cable Maestro”:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;A &lt;b&gt;guy-wire&lt;/b&gt; or &lt;b&gt;guy-rope&lt;/b&gt; is a tensioned cable designed to add stability to structures&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Two simple rules to remember:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;In order to configure service and implementers fluently, the GuyWire will reference everything. &lt;/li&gt;

  &lt;li&gt;Because the guy-wire reference everything, the GuyWire can not be referenced. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The guywire is an excellent place to “configure” the whole application. I used to separate the configuration in different aspects. Here some examples:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;ORM configuration &lt;/li&gt;

  &lt;li&gt;Constraint Validator configuration &lt;/li&gt;

  &lt;li&gt;Repositories configuration &lt;/li&gt;

  &lt;li&gt;Entities configuration &lt;/li&gt;

  &lt;li&gt;ViewModel configuration &lt;/li&gt;

  &lt;li&gt;Controllers configuration &lt;/li&gt;

  &lt;li&gt;Views configuration &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can explore the configurators of ChinookMediaManager &lt;a href="http://code.google.com/p/unhaddins/source/browse/#svn/trunk/Examples/uNHAddIns.Examples.WPF/ChinookMediaManager.GuyWire/Configurators"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;How does it works?&lt;/h2&gt;

&lt;p&gt;The guywire project has an special “Output Path”:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/nhibernate/image_5F00_53062B8B.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/nhibernate/image_5F00_thumb_5F00_6AC28453.png" width="552" height="255" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;So, the path is the “Startup” project.&lt;/p&gt;

&lt;p&gt;Secondly, in the App.Config, I have a config like this:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:#a31515;"&gt;appSettings&lt;/span&gt;&lt;span style="color:blue;"&gt;&amp;gt;
  &amp;lt;&lt;/span&gt;&lt;span style="color:#a31515;"&gt;add &lt;/span&gt;&lt;span style="color:red;"&gt;key&lt;/span&gt;&lt;span style="color:blue;"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color:blue;"&gt;GuyWire&lt;/span&gt;&amp;quot; &lt;span style="color:red;"&gt;value&lt;/span&gt;&lt;span style="color:blue;"&gt;=&lt;/span&gt;&amp;quot;&lt;span style="color:blue;"&gt;ChinookMediaManager.GuyWire.GeneralGuyWire, ChinookMediaManager.GuyWire&lt;/span&gt;&amp;quot; &lt;span style="color:blue;"&gt;/&amp;gt;
&amp;lt;/&lt;/span&gt;&lt;span style="color:#a31515;"&gt;appSettings&lt;/span&gt;&lt;span style="color:blue;"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;And finally, in my App.Xaml.cs:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public partial class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;App &lt;/span&gt;: Application
{
    &lt;span style="color:blue;"&gt;private readonly &lt;/span&gt;IGuyWire guyWire = ApplicationConfiguration.GetGuyWire();

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;App()
    {
        guyWire.Wire();
    }

    &lt;span style="color:blue;"&gt;protected override void &lt;/span&gt;OnStartup(StartupEventArgs e)
    {
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;viewFactory = ServiceLocator.Current.GetInstance&amp;lt;IViewFactory&amp;gt;();
        viewFactory.ShowView&amp;lt;BrowseArtistViewModel&amp;gt;();
    }

    &lt;span style="color:blue;"&gt;protected override void &lt;/span&gt;OnExit(ExitEventArgs e)
    {
        guyWire.Dewire();
        &lt;span style="color:blue;"&gt;base&lt;/span&gt;.OnExit(e);
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The interface IGuyWire and other classes needed for doing this, are in unhaddins.&lt;/p&gt;

&lt;p&gt;The reference graph of the Chinook Media Manager, is as follows:&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/nhibernate/image_5F00_4961041A.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/nhibernate/image_5F00_thumb_5F00_4FAA6B59.png" width="578" height="593" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h2&gt;A last word about the Configurators&lt;/h2&gt;

&lt;p&gt;I really like the idea of have different parts of the application configuration in separated classes. I used to reuse this configurators alone in my Tests. But, as a I said before, the guywire should not be referenced by any project. So, my trick is add the configurator as a “linked file” to the test project:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/nhibernate/image_5F00_6BBD04E1.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/nhibernate/image_5F00_thumb_5F00_400C3AE5.png" width="243" height="117" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;And this is a sample:&lt;/p&gt;

&lt;pre class="code"&gt;[&lt;span style="color:#2b91af;"&gt;TestFixture&lt;/span&gt;]
&lt;span style="color:blue;"&gt;public class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;AlbumValidationFixture
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;private &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IWindsorContainer &lt;/span&gt;container;

    [&lt;span style="color:#2b91af;"&gt;TestFixtureSetUp&lt;/span&gt;]
    &lt;span style="color:blue;"&gt;public void &lt;/span&gt;FixtureSetUp()
    {
        container = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;WindsorContainer&lt;/span&gt;();
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;configurator = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NHVConfigurator&lt;/span&gt;();
        configurator.Configure(container);
    }

    [&lt;span style="color:#2b91af;"&gt;Test&lt;/span&gt;]
    &lt;span style="color:blue;"&gt;public void &lt;/span&gt;title_constraints()
    {
        GetConstraint&amp;lt;&lt;span style="color:#2b91af;"&gt;Album&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;NotEmptyAttribute&lt;/span&gt;&amp;gt;(a =&amp;gt; a.Title)
            .Message
            .Should().Be.EqualTo(&lt;span style="color:#a31515;"&gt;&amp;quot;Title should not be null.&amp;quot;&lt;/span&gt;);

        GetConstraint&amp;lt;&lt;span style="color:#2b91af;"&gt;Album&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;LengthAttribute&lt;/span&gt;&amp;gt;(a =&amp;gt; a.Title)
            .Should().Be.OfType&amp;lt;&lt;span style="color:#2b91af;"&gt;LengthAttribute&lt;/span&gt;&amp;gt;()
            .And.ValueOf.Message.Should().Be.EqualTo(&lt;span style="color:#a31515;"&gt;&amp;quot;Title should not exceed 200 chars.&amp;quot;&lt;/span&gt;);
            
        
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;I will not talk about this long break in the series. If you are interested in Wpf and Nhibernate, you should be happy because; &lt;strong&gt;&lt;u&gt;I&amp;#39;M BACK&lt;/u&gt;!&lt;/strong&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://nhforge.org/aggbug.aspx?PostID=539" width="1" height="1"&gt;</description><category domain="http://nhforge.org/blogs/nhibernate/archive/tags/NHibernate/default.aspx">NHibernate</category><category domain="http://nhforge.org/blogs/nhibernate/archive/tags/WPF/default.aspx">WPF</category></item><item><title>Nhibernate and WPF: Validations</title><link>http://nhforge.org/blogs/nhibernate/archive/2009/08/27/nhibernate-and-wpf-validations.aspx</link><pubDate>Fri, 28 Aug 2009 01:06:36 GMT</pubDate><guid isPermaLink="false">45f813f2-f1c4-4eda-a619-288e3cadc793:493</guid><dc:creator>Jose Romaniello</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://nhforge.org/blogs/nhibernate/rsscomments.aspx?PostID=493</wfw:commentRss><comments>http://nhforge.org/blogs/nhibernate/archive/2009/08/27/nhibernate-and-wpf-validations.aspx#comments</comments><description>&lt;p&gt;Part I: &lt;a href="http://jfromaniello.blogspot.com/2009/08/introducing-nhiberate-and-wpf.html"&gt;Introducing NHiberate and WPF: The ChinookMediaManager&lt;/a&gt;     &lt;br /&gt;Part II: &lt;a href="http://jfromaniello.blogspot.com/2009/08/chinook-media-manager-core.html"&gt;Nhibernate and WPF: The core&lt;/a&gt;     &lt;br /&gt;Part III: &lt;a href="http://nhforge.org/blogs/nhibernate/archive/2009/08/15/nhibernate-and-wpf-models-concept.aspx"&gt;Nhibernate and WPF: Models concept&lt;/a&gt;     &lt;br /&gt;Part IV :&lt;a href="http://jfromaniello.blogspot.com/2009/08/nhibernate-and-wpf-viewmodels-and-views.html"&gt;Nhibernate and WPF: ViewModels and Views&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;In this post I will show you an easy way to handle validations in WPF.&lt;/p&gt;  &lt;p&gt;In System.ComponentModel we have an interesting interface named &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.idataerrorinfo.aspx"&gt;IDataErrorInfo&lt;/a&gt;.     &lt;br /&gt;This interface has two members:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;IDataErrorInfo.Item: Gets the error message for the property with the given name. &lt;/li&gt;    &lt;li&gt;IDataErrorInfo.Error: Gets an error message indicating what is wrong with this object. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The interesting side of this interface is that if we implement this in our domain classes, the presentation layer will automatically resolved certain things.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Side note: This interface was made with DataTables in mind. &lt;/p&gt; &lt;/blockquote&gt;  &lt;h4&gt;Validation Framework&lt;/h4&gt;  &lt;p&gt;I really like NHibernateValidator, in the same way that I like NHibernate. But, in uNhAddIns we have a main principle: “those two are just options”, so you can change whenever you want to use anything else (&lt;a href="http://msdn.microsoft.com/en-us/library/cc309509.aspx"&gt;Validation Application Block&lt;/a&gt;, &lt;a href="http://www.codeplex.com/ValidationFramework"&gt;Validation Framework&lt;/a&gt;, &lt;a href="http://www.castleproject.org/ActiveRecord/documentation/v1rc1/manual/validators.html"&gt;Castle Validators&lt;/a&gt;, &lt;a href="http://www.codeplex.com/xval"&gt;xVal&lt;/a&gt;).&lt;/p&gt;  &lt;p&gt;For that matter, &lt;a href="http://fabiomaulo.blogspot.com/"&gt;Fabio Maulo&lt;/a&gt; developed a simple interface named &lt;a href="http://code.google.com/p/unhaddins/source/browse/trunk/uNhAddIns/uNhAddIns.Adapters/IEntityValidator.cs"&gt;IEntityValidator&lt;/a&gt;, this is part now of the uNhAddIns.Adapters project. If you want to use Nhibernate Validator the EntityValidator is already implemented &lt;a href="http://code.google.com/p/unhaddins/source/browse/#svn/trunk/uNhAddIns/uNhAddIns.NHibernateValidator"&gt;here&lt;/a&gt;. If you want to use another validator framework please implement the interface and send us the patch ;-).&lt;/p&gt;  &lt;h4&gt;How To &lt;/h4&gt;  &lt;p&gt;Implementing IDataErrorInfo directly in domain classes is a waste of time and also is too much invasive, because will end with a dependency in the IEntityValidator. Since we already know how to build injectable behavior we can address this problem in the same way.&lt;/p&gt;  &lt;p&gt;I build a new DynamicProxy IInterceptor you could see the implementation &lt;a href="http://code.google.com/p/unhaddins/source/browse/trunk/uNhAddIns/uNhAddIns.ComponentBehaviors.Castle/DataErrorInfoInterceptor.cs"&gt;here&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;The configuration of the Album entity, now looks as follows:&lt;/p&gt;  &lt;pre class="code"&gt;container.Register(&lt;span style="color:#2b91af;"&gt;Component&lt;/span&gt;.For&amp;lt;&lt;span style="color:#2b91af;"&gt;Album&lt;/span&gt;&amp;gt;()
                                    .NhibernateEntity()
                                    .AddDataErrorInfoBehavior()
                                    .AddNotificableBehavior()
                                    .LifeStyle.Transient);&lt;/pre&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;The configuration of Nhibernate.Validator is very easy and &lt;a href="http://nhforge.org/wikis/howtonh/setup-nhv-fluently-with-your-ioc-container.aspx"&gt;I don’t want to repeat myself&lt;/a&gt;. 

  &lt;br /&gt;Then you need to register an IEntityValidator as follows:&lt;/p&gt;

&lt;pre class="code"&gt;container.Register(&lt;span style="color:#2b91af;"&gt;Component&lt;/span&gt;.For&amp;lt;&lt;span style="color:#2b91af;"&gt;IEntityValidator&lt;/span&gt;&amp;gt;()
                            .ImplementedBy&amp;lt;&lt;span style="color:#2b91af;"&gt;EntityValidator&lt;/span&gt;&amp;gt;());&lt;/pre&gt;

&lt;p&gt;You have three way to write validations with NHibernate Validator: Xml, Fluent and Attributes. This is aleady very well explained in this &lt;a href="http://fabiomaulo.blogspot.com/2009/02/diving-in-nhibernatevalidator.html"&gt;post&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In the VIEW the only thing that we need to enable is the ValidateOnDataErrors attribute, this is an example textbox:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:#a31515;"&gt;TextBox &lt;/span&gt;&lt;span style="color:red;"&gt;Text&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Binding &lt;/span&gt;&lt;span style="color:red;"&gt;Path&lt;/span&gt;&lt;span style="color:blue;"&gt;=Album.Title, &lt;/span&gt;&lt;span style="color:red;"&gt;ValidatesOnDataErrors&lt;/span&gt;&lt;span style="color:blue;"&gt;=true}&amp;quot; /&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;I’ve a shared a resource for views, as follows:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Style &lt;/span&gt;&lt;span style="color:red;"&gt;TargetType&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color:#a31515;"&gt;x&lt;/span&gt;&lt;span style="color:blue;"&gt;:&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Type &lt;/span&gt;&lt;span style="color:red;"&gt;TextBox&lt;/span&gt;&lt;span style="color:blue;"&gt;}&amp;quot;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Style.Triggers&lt;/span&gt;&lt;span style="color:blue;"&gt;&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Trigger &lt;/span&gt;&lt;span style="color:red;"&gt;Property&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;Validation.HasError&amp;quot; &lt;/span&gt;&lt;span style="color:red;"&gt;Value&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;true&amp;quot;&amp;gt;
            &amp;lt;&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Setter &lt;/span&gt;&lt;span style="color:red;"&gt;Property&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;ToolTip&amp;quot;
            &lt;/span&gt;&lt;span style="color:red;"&gt;Value&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Binding &lt;/span&gt;&lt;span style="color:red;"&gt;RelativeSource&lt;/span&gt;&lt;span style="color:blue;"&gt;={&lt;/span&gt;&lt;span style="color:#a31515;"&gt;RelativeSource &lt;/span&gt;&lt;span style="color:red;"&gt;Self&lt;/span&gt;&lt;span style="color:blue;"&gt;}, 
                   &lt;/span&gt;&lt;span style="color:red;"&gt;Path&lt;/span&gt;&lt;span style="color:blue;"&gt;=(Validation.Errors)[&lt;/span&gt;0&lt;span style="color:blue;"&gt;].ErrorContent}&amp;quot;/&amp;gt;
        &amp;lt;/&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Trigger&lt;/span&gt;&lt;span style="color:blue;"&gt;&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Style.Triggers&lt;/span&gt;&lt;span style="color:blue;"&gt;&amp;gt;
&amp;lt;/&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Style&lt;/span&gt;&lt;span style="color:blue;"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;This means: “textbox should display validation errors in tooltip”. 

&lt;br /&gt;

&lt;br /&gt;This is all. What?, you don’t believe me. 

&lt;br /&gt;

&lt;br /&gt;

&lt;h3&gt;See the behavior in action&lt;/h3&gt;
See the screencast &lt;a href="http://www.screencast.com/t/wSG2lhGbiJ6F"&gt;here&lt;/a&gt;. 

&lt;p&gt;Oh, and I almost forgot, this behavior &lt;a href="http://www.asp.net/Learn/mvc/tutorial-37-cs.aspx"&gt;should also work in ASP.NET Mvc&lt;/a&gt;.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://nhforge.org/aggbug.aspx?PostID=493" width="1" height="1"&gt;</description><category domain="http://nhforge.org/blogs/nhibernate/archive/tags/validation/default.aspx">validation</category><category domain="http://nhforge.org/blogs/nhibernate/archive/tags/Castle/default.aspx">Castle</category><category domain="http://nhforge.org/blogs/nhibernate/archive/tags/uNHAddins/default.aspx">uNHAddins</category><category domain="http://nhforge.org/blogs/nhibernate/archive/tags/Validator/default.aspx">Validator</category><category domain="http://nhforge.org/blogs/nhibernate/archive/tags/WPF/default.aspx">WPF</category></item><item><title>Nhibernate and WPF: ViewModels and Views</title><link>http://nhforge.org/blogs/nhibernate/archive/2009/08/19/nhibernate-and-wpf-viewmodels-and-views.aspx</link><pubDate>Wed, 19 Aug 2009 16:23:46 GMT</pubDate><guid isPermaLink="false">45f813f2-f1c4-4eda-a619-288e3cadc793:483</guid><dc:creator>Jose Romaniello</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://nhforge.org/blogs/nhibernate/rsscomments.aspx?PostID=483</wfw:commentRss><comments>http://nhforge.org/blogs/nhibernate/archive/2009/08/19/nhibernate-and-wpf-viewmodels-and-views.aspx#comments</comments><description>&lt;p&gt;Part I: &lt;a href="http://jfromaniello.blogspot.com/2009/08/introducing-nhiberate-and-wpf.html"&gt;Introducing NHiberate and WPF: The ChinookMediaManager&lt;/a&gt;     &lt;br /&gt;Part II: &lt;a href="http://jfromaniello.blogspot.com/2009/08/chinook-media-manager-core.html"&gt;Nhibernate and WPF: The core&lt;/a&gt;     &lt;br /&gt;Part III: &lt;a href="http://nhforge.org/blogs/nhibernate/archive/2009/08/15/nhibernate-and-wpf-models-concept.aspx"&gt;Nhibernate and WPF: Models concept&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;In this post I will introduce some concepts about the presentation layer of the Chinook Media Manager example.&lt;/p&gt;  &lt;h3&gt;Prerequisites&lt;/h3&gt;  &lt;p&gt;If you are new to the MVVM pattern I will strongly recommend you these blogs post:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://blogs.msdn.com/johngossman/archive/2005/10/08/478683.aspx"&gt;Tales from the smart client – John Grossman.&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx"&gt;WPF apps with the MVVM design pattern – By John Smith.&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/erwinvandervalk/archive/2009/08/14/the-difference-between-model-view-viewmodel-and-other-separated-presentation-patterns.aspx"&gt;The difference between Model-View-ViewModel and other separated presentation pattern – By Erwin van der Valk.&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt;  &lt;h3&gt;Introduction&lt;/h3&gt;  &lt;p&gt;I will quote John Smith:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;The single most important aspect of WPF that makes MVVM a great pattern to use is the data binding infrastructure. By binding properties of a view to a ViewModel, you get loose coupling between the two and entirely remove the need for writing code in a ViewModel that directly updates a view.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This is the more important thing that you need to remember. Unlike the MVP pattern the viewmodel never updates the UI, the ui is automatically updated by the databinding infrastructure. Also you has to keep in mind that all in the MVVM is about databinding, even &lt;strong&gt;events&lt;/strong&gt;. &lt;/p&gt;  &lt;p&gt;I chose to separate Views and ViewModels in differents assembly, although I saw these two together in a bunch of samples. For the other hand the interfaces of the ViewModels are defined in the Views assembly.&lt;/p&gt;  &lt;h3&gt;The “Album Manager” use case&lt;/h3&gt;  &lt;p&gt;If we recall my first post the UI was this:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/nhibernate/albums_5F00_4848FF1C.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="albums" border="0" alt="albums" src="http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/nhibernate/albums_5F00_thumb_5F00_1C533E31.png" width="476" height="384" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;I will separate this use case in two views and viewmodels:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/nhibernate/albumsred_5F00_28E60CAF.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="albumsred" border="0" alt="albumsred" src="http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/nhibernate/albumsred_5F00_thumb_5F00_16C1F142.png" width="476" height="384" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;The main View is called AlbumManagerView and the view inside the red border is called “EditAlbumView”. The reason for why I’m doing this is clear: “I need somehow to separate the problem into smaller parts”. And as I say in the “&lt;a href="http://nhforge.org/blogs/nhibernate/archive/2009/08/15/nhibernate-and-wpf-models-concept.aspx"&gt;Models concept&lt;/a&gt;” post a use-case can expand multiples views.&lt;/p&gt;  &lt;p&gt;To complicate things a bit, the user told us that would like to be able to simultaneously edit multiple albums. So, I will use the workspace sample of John Smith.&lt;/p&gt;  &lt;h3&gt;The AlbumManager&lt;/h3&gt;  &lt;p&gt;When I start to define a View, the first thing is the ViewModel interface, in this case:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public interface &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IAlbumManagerViewModel &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;INotifyPropertyChanged
&lt;/span&gt;{
    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Setup the view, load the albums collection.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&amp;quot;artist&amp;quot;&amp;gt;&amp;lt;/param&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;void &lt;/span&gt;SetUp(&lt;span style="color:#2b91af;"&gt;Artist &lt;/span&gt;artist);

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Expose a bindable collection of albums.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Album&lt;/span&gt;&amp;gt; Albums { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Get or Set the selected album.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Album &lt;/span&gt;SelectedAlbum { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;set&lt;/span&gt;; }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Open an edition workspace for editing the selected album.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ICommand &lt;/span&gt;EditSelectedAlbumCommand { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Commit all the changes.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ICommand &lt;/span&gt;SaveAllCommand { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Discard all the changes.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ICommand &lt;/span&gt;CancelAllCommand { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;WorkSpace open.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ObservableCollection&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;IEditAlbumViewModel&lt;/span&gt;&amp;gt; AlbumEditWorkspaces { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; }
}&lt;/pre&gt;

&lt;p&gt;In the introduction I said that MVVM use databinding even for events . 
  &lt;br /&gt;So, what is an ICommand?&amp;#160; ICommand interface has three members: CanExecuteChanged, CanExecute and Execute. The object that is bound to this command (aka command source), disable itself if the command cann’t be executed. You can bind KeyGestures, MouseActions, buttons and so on. More on this topic &lt;a href="http://msdn.microsoft.com/en-us/library/ms752308.aspx"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The second step is to start writing a test for the concrete implementation of the viewmodel.&amp;#160; &lt;br /&gt;&lt;/p&gt;

&lt;pre class="code"&gt;[&lt;span style="color:#2b91af;"&gt;TestFixture&lt;/span&gt;]
&lt;span style="color:blue;"&gt;public class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;AlbumManagerViewModelTest
&lt;/span&gt;{
    [&lt;span style="color:#2b91af;"&gt;Test&lt;/span&gt;]
    &lt;span style="color:blue;"&gt;public void &lt;/span&gt;setup_viewmodel_should_work()
    {
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;albumManagerModel = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Mock&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;IAlbumManagerModel&lt;/span&gt;&amp;gt;();

        &lt;span style="color:blue;"&gt;var &lt;/span&gt;artist = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Artist &lt;/span&gt;{ Name = &lt;span style="color:#a31515;"&gt;&amp;quot;John&amp;quot; &lt;/span&gt;};
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;albumList = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Album&lt;/span&gt;&amp;gt; { &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Album&lt;/span&gt;() { Artist = artist } };

        albumManagerModel.Setup(am =&amp;gt; am.GetAlbumsByArtist(artist))
                         .Returns(albumList)
                         .AtMostOnce();


        &lt;span style="color:blue;"&gt;var &lt;/span&gt;albumManagerVm = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;AlbumManagerViewModel&lt;/span&gt;(albumManagerModel.Object, 
                                                       viewInsantiator.Object);

        &lt;span style="color:blue;"&gt;var &lt;/span&gt;eventWasRaised = &lt;span style="color:blue;"&gt;false&lt;/span&gt;;

        albumManagerVm.PropertyChanged +=
            (sender, args) =&amp;gt;
            {
                &lt;span style="color:green;"&gt;//property changed should be raised AFTER the property change.
                &lt;/span&gt;&lt;span style="color:blue;"&gt;if &lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Albums&amp;quot;&lt;/span&gt;.Equals(args.PropertyName))
                {
                    albumManagerVm.Albums.Should().Be.SameInstanceAs(albumList);
                    eventWasRaised = &lt;span style="color:blue;"&gt;true&lt;/span&gt;;    
                }
            };

        albumManagerVm.SetUp(artist);
        eventWasRaised.Should().Be.True();
        albumManagerModel.VerifyAll();

    }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;When I setup an “AlbumManagerViewModel”, it should call GetAlbumByArtist of my model, and put the result in the “Albums” property. Also the viewmodel should raise the PropertyChanged for the album property, AFTER the change in the property.&lt;/p&gt;

&lt;p&gt;The implementation is very simple: 
  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public void &lt;/span&gt;SetUp(&lt;span style="color:#2b91af;"&gt;Artist &lt;/span&gt;artist)
{
    Albums = _albumManagerModel.GetAlbumsByArtist(artist);
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;private &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Album&lt;/span&gt;&amp;gt; _albums;
&lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Album&lt;/span&gt;&amp;gt; Albums
{
    &lt;span style="color:blue;"&gt;get &lt;/span&gt;{ &lt;span style="color:blue;"&gt;return &lt;/span&gt;_albums; }
    &lt;span style="color:blue;"&gt;private set
    &lt;/span&gt;{
        _albums = &lt;span style="color:blue;"&gt;value&lt;/span&gt;;
        OnPropertyChanged(&lt;span style="color:#a31515;"&gt;&amp;quot;Albums&amp;quot;&lt;/span&gt;);
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;To not getting bored with the code, the full implementation of the EditSelectedAlbumCommand is &lt;a href="http://code.google.com/p/unhaddins/source/browse/trunk/Examples/uNHAddIns.Examples.WPF/ChinookMediaManager.ViewModels/AlbumManagerViewModel.cs"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I will highlight interesting parts of this code:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ICommand &lt;/span&gt;EditSelectedAlbumCommand
{
    &lt;span style="color:blue;"&gt;get
    &lt;/span&gt;{
        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(_editSelectedAlbumCommand == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
            _editSelectedAlbumCommand = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;RelayCommand&lt;/span&gt;(
                o =&amp;gt; EditSelectedAlbum(),
                o =&amp;gt; SelectedAlbum != &lt;span style="color:blue;"&gt;null &lt;/span&gt;&amp;amp;&amp;amp;!AlbumEditWorkspaces.Any(ae =&amp;gt; ae.Album == SelectedAlbum));
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;_editSelectedAlbumCommand;
    }
}&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;This is the EditSelectedAlbumCommand. In the instantiation of the command you see two lambdas. The first function is the code that should be called when the commandsource call Execute. The second is the CanExecute function, as you can see it returns false when:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;There isn’t a selected album. &lt;/li&gt;

  &lt;li&gt;There is another workspace editing the album. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can find the RelayCommand in the source.&lt;/p&gt;

&lt;p&gt;The EditSelectedAlbum method looks as follows:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;private void &lt;/span&gt;EditSelectedAlbum()
{
    &lt;span style="color:green;"&gt;//Resolve a new instance of EditAlbumViewModel
    &lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;newWp = _viewFactory.ResolveViewModel&amp;lt;&lt;span style="color:#2b91af;"&gt;IEditAlbumViewModel&lt;/span&gt;&amp;gt;();
    &lt;span style="color:green;"&gt;//Setup the new viewmodel.
    &lt;/span&gt;newWp.SetUp(SelectedAlbum, _albumManagerModel);
    &lt;span style="color:green;"&gt;//subscribe to close request.
    &lt;/span&gt;newWp.RequestClose += EditAlbumRequestClose;
    &lt;span style="color:green;"&gt;//add the new viewmodel to the workspace collection.
    &lt;/span&gt;AlbumEditWorkspaces.Add(newWp);
    &lt;span style="color:green;"&gt;//set the new viewmodel as the active wp.
    &lt;/span&gt;SetActiveWorkspace(newWp);
}&lt;/pre&gt;

&lt;pre class="code"&gt;Now, the view for this viewmodel is very easy:&lt;/pre&gt;

&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:#a31515;"&gt;StackPanel&lt;/span&gt;&lt;span style="color:blue;"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color:#a31515;"&gt;StackPanel &lt;/span&gt;&lt;span style="color:red;"&gt;Orientation&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;Horizontal&amp;quot; &lt;/span&gt;&lt;span style="color:red;"&gt;DockPanel.Dock&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;Top&amp;quot; &amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Button &lt;/span&gt;&lt;span style="color:red;"&gt;Command&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Binding &lt;/span&gt;&lt;span style="color:red;"&gt;EditSelectedAlbumCommand&lt;/span&gt;&lt;span style="color:blue;"&gt;}&amp;quot; &amp;gt;&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Edit&lt;/span&gt;&lt;span style="color:blue;"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Button&lt;/span&gt;&lt;span style="color:blue;"&gt;&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Button&lt;/span&gt;&lt;span style="color:blue;"&gt;&amp;gt;&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Close&lt;/span&gt;&lt;span style="color:blue;"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Button&lt;/span&gt;&lt;span style="color:blue;"&gt;&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color:#a31515;"&gt;StackPanel&lt;/span&gt;&lt;span style="color:blue;"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color:#a31515;"&gt;ListBox &lt;/span&gt;&lt;span style="color:red;"&gt;Name&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;AlbumsList&amp;quot; 
         &lt;/span&gt;&lt;span style="color:red;"&gt;ItemsSource&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Binding &lt;/span&gt;&lt;span style="color:red;"&gt;Albums&lt;/span&gt;&lt;span style="color:blue;"&gt;}&amp;quot; 
         &lt;/span&gt;&lt;span style="color:red;"&gt;DisplayMemberPath&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;Title&amp;quot;
         &lt;/span&gt;&lt;span style="color:red;"&gt;SelectedItem&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Binding &lt;/span&gt;&lt;span style="color:red;"&gt;SelectedAlbum&lt;/span&gt;&lt;span style="color:blue;"&gt;}&amp;quot;
         &lt;/span&gt;&lt;span style="color:red;"&gt;DockPanel.Dock&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;Top&amp;quot; &lt;/span&gt;&lt;span style="color:red;"&gt;Height&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;302&amp;quot;&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color:#a31515;"&gt;ListBox&lt;/span&gt;&lt;span style="color:blue;"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Button &lt;/span&gt;&lt;span style="color:red;"&gt;Command&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Binding &lt;/span&gt;&lt;span style="color:red;"&gt;SaveAllCommand&lt;/span&gt;&lt;span style="color:blue;"&gt;}&amp;quot; &amp;gt;&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Save All&lt;/span&gt;&lt;span style="color:blue;"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Button&lt;/span&gt;&lt;span style="color:blue;"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Button &lt;/span&gt;&lt;span style="color:red;"&gt;Command&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Binding &lt;/span&gt;&lt;span style="color:red;"&gt;CancelAllCommand&lt;/span&gt;&lt;span style="color:blue;"&gt;}&amp;quot; &amp;gt;&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Cancel All&lt;/span&gt;&lt;span style="color:blue;"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Button&lt;/span&gt;&lt;span style="color:blue;"&gt;&amp;gt;
&amp;lt;/&lt;/span&gt;&lt;span style="color:#a31515;"&gt;StackPanel&lt;/span&gt;&lt;span style="color:blue;"&gt;&amp;gt;
&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The “tabs” container is described in this peace of code:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Border &lt;/span&gt;&lt;span style="color:red;"&gt;Style&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color:#a31515;"&gt;StaticResource &lt;/span&gt;&lt;span style="color:red;"&gt;MainBorderStyle&lt;/span&gt;&lt;span style="color:blue;"&gt;}&amp;quot;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color:#a31515;"&gt;HeaderedContentControl 
      &lt;/span&gt;&lt;span style="color:red;"&gt;Content&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Binding &lt;/span&gt;&lt;span style="color:red;"&gt;Path&lt;/span&gt;&lt;span style="color:blue;"&gt;=AlbumEditWorkspaces}&amp;quot;
      &lt;/span&gt;&lt;span style="color:red;"&gt;ContentTemplate&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color:#a31515;"&gt;StaticResource &lt;/span&gt;&lt;span style="color:red;"&gt;WorkspacesTemplate&lt;/span&gt;&lt;span style="color:blue;"&gt;}&amp;quot;
      &lt;/span&gt;&lt;span style="color:red;"&gt;Header&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;Workspaces&amp;quot;
      &lt;/span&gt;&lt;span style="color:red;"&gt;Style&lt;/span&gt;&lt;span style="color:blue;"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color:#a31515;"&gt;StaticResource &lt;/span&gt;&lt;span style="color:red;"&gt;MainHCCStyle&lt;/span&gt;&lt;span style="color:blue;"&gt;}&amp;quot;
      /&amp;gt;
&amp;lt;/&lt;/span&gt;&lt;span style="color:#a31515;"&gt;Border&lt;/span&gt;&lt;span style="color:blue;"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;h3&gt;The EditAlbum &lt;/h3&gt;

&lt;p&gt;I define the interface for the IEditAlbumViewModel as follows: 
  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public interface &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEditAlbumViewModel &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;INotifyPropertyChanged
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;void &lt;/span&gt;SetUp(&lt;span style="color:#2b91af;"&gt;Album &lt;/span&gt;album, &lt;span style="color:#2b91af;"&gt;IAlbumManagerModel &lt;/span&gt;albumManagerModel);

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;The album being edited.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Album &lt;/span&gt;Album { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; }
   
    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;The title of the tab.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;string &lt;/span&gt;DisplayName { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;The command to close the tab.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ICommand &lt;/span&gt;CloseCommand { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;The command to save the album.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ICommand &lt;/span&gt;SaveCommand { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;The command to add a new track to the album.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ICommand &lt;/span&gt;AddNewTrackCommand { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;The command to delete the selected track.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ICommand &lt;/span&gt;DeleteSelectedTrackCommand { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; }

    &lt;span style="color:#2b91af;"&gt;Track &lt;/span&gt;SelectedTrack { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;set&lt;/span&gt;; }

    &lt;span style="color:blue;"&gt;event &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;EventHandler &lt;/span&gt;RequestClose;
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The implementation is very straightforward, you can see &lt;a href="http://code.google.com/p/unhaddins/source/browse/trunk/Examples/uNHAddIns.Examples.WPF/ChinookMediaManager.ViewModels/EditAlbumViewModel.cs"&gt;here&lt;/a&gt;. One thing to mention is that I configure nhibernate to resolve all my collections with INotifyCollectionChanged, so I can add a new Track in my viewmodel and the datagrid bound to the tracks collection will be notified about that change.&lt;/p&gt;

&lt;h3&gt;What’s next?&lt;/h3&gt;

&lt;p&gt;We have several troubles with this application:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Error handling. Is simple, this is what the user see. We MUST handle unexpected exceptions, just think what would happen if we shutdown the database server. &lt;/li&gt;

  &lt;li&gt;Asynchronous calls. For now we are freezing the UI thread with database and business layer operations. We need to build responsive UI’s &lt;/li&gt;

  &lt;li&gt;Validation. I will add support to the NHibernate Validator. &lt;/li&gt;

  &lt;li&gt;Conflict resolution for concurrency problems. &lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;Do you want to see the app working?&lt;/h3&gt;

&lt;p&gt;&lt;a href="http://www.screencast.com/t/dCrs2VJB"&gt;Here&lt;/a&gt; you can see the full concept of &amp;quot;Conversation per Business Transaction&amp;quot; of &lt;a href="http://fabiomaulo.blogspot.com/"&gt;Fabio Maulo&lt;/a&gt; working.&lt;/p&gt;


&lt;p&gt;The full source code project is &lt;a href="http://code.google.com/p/unhaddins/"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Special thanks to all the people mentioned in this post.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://nhforge.org/aggbug.aspx?PostID=483" width="1" height="1"&gt;</description><category domain="http://nhforge.org/blogs/nhibernate/archive/tags/Session/default.aspx">Session</category><category domain="http://nhforge.org/blogs/nhibernate/archive/tags/WPF/default.aspx">WPF</category></item><item><title>Nhibernate and WPF: Models concept</title><link>http://nhforge.org/blogs/nhibernate/archive/2009/08/15/nhibernate-and-wpf-models-concept.aspx</link><pubDate>Sun, 16 Aug 2009 00:33:46 GMT</pubDate><guid isPermaLink="false">45f813f2-f1c4-4eda-a619-288e3cadc793:470</guid><dc:creator>Jose Romaniello</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://nhforge.org/blogs/nhibernate/rsscomments.aspx?PostID=470</wfw:commentRss><comments>http://nhforge.org/blogs/nhibernate/archive/2009/08/15/nhibernate-and-wpf-models-concept.aspx#comments</comments><description>&lt;p&gt;&lt;a href="http://jfromaniello.blogspot.com/2009/08/introducing-nhiberate-and-wpf.html"&gt;Part I: Introducing Nhibernate and WPF&lt;/a&gt;     &lt;br /&gt;&lt;a href="http://jfromaniello.blogspot.com/2009/08/chinook-media-manager-core.html"&gt;Part II: Chinook Media Manager: The Core&lt;/a&gt;&lt;/p&gt;  &lt;h3&gt;Introduction&lt;/h3&gt;  &lt;p&gt;For this post I will use the concept of &lt;a href="http://fabiomaulo.blogspot.com/"&gt;Fabio Maulo&lt;/a&gt; called “Conversation-per-BussinesTransaction”. If you have not read, what are you waiting for?     &lt;br /&gt;&lt;/p&gt;  &lt;h3&gt;Definition&lt;/h3&gt;  &lt;p&gt;This definition is extracted from Fabio’s &lt;a href="http://fabiomaulo.blogspot.com/2008/12/conversation-per-business-transaction.html"&gt;post&lt;/a&gt; and is very important that you understood it:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;When you read something about NHibernate-session-management is because we want abstract/”aspect” NH-session’s stuff from the code are using it. In general, or I hope so, you are using the session in something like a DAO/Repository and, in a use-case, you are calling more than one DAO/Repository. Open a new session in each DAO/Repository is an anti-pattern called session-per-call (or very closer to it). What we are searching is something to manage the session in an high-layer but without wire that layer with NHibernate. In a WEB environment it is pretty easy because we can manage the session using an implementation of a IHttpModule, or in the HttpApplication, “intercepting” the request (two patterns mentioned here). In a winForm, or WPF, aplication it is not so clear where the abstraction have place. In this post I will use an “artifact” named Model to represent the “abstraction-point” (in my mind the Model is the business-object that are using DAOs/Repository and domain-entities); in an MVC based application, probably, the abstraction have place in the Controller.&lt;/p&gt; &lt;/blockquote&gt;  &lt;h3&gt;Implementation&lt;/h3&gt;  &lt;p&gt;We start defining an interface for our Use-case Model class as follows: &lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public interface &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IAlbumManagerModel
    &lt;/span&gt;{

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Search all albums from a given artist.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        /// &amp;lt;param name=&amp;quot;artist&amp;quot;&amp;gt;&amp;lt;/param&amp;gt;
        /// &amp;lt;returns&amp;gt;&amp;lt;/returns&amp;gt;
        &lt;/span&gt;IEnumerable&amp;lt;Album&amp;gt; GetAlbumsByArtist(Artist artist);

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Persist an album.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        /// &amp;lt;param name=&amp;quot;album&amp;quot;&amp;gt;&amp;lt;/param&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;void &lt;/span&gt;SaveAlbum(Album album);

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Revert changes of a given album to his current persisted state.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        /// &amp;lt;param name=&amp;quot;album&amp;quot;&amp;gt;&amp;lt;/param&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;void &lt;/span&gt;CancelAlbum(Album album);

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Flush all changes to the database.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;void &lt;/span&gt;SaveAll();

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Cancel all changes.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;void &lt;/span&gt;CancelAll();
    }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;As I say in my previous post this interface is defined in the “ChinookMediaManager.Domain”. 
  &lt;br /&gt;The concrete implementation is defined in ChinookMediaManager.DomainImpl as follows: 

  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="code"&gt;[PersistenceConversational(MethodsIncludeMode = MethodsIncludeMode.Implicit)]
    &lt;span style="color:blue;"&gt;public class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;AlbumManagerModel &lt;/span&gt;: IAlbumManagerModel
    {

        &lt;span style="color:blue;"&gt;private readonly &lt;/span&gt;IAlbumRepository albumRepository;

        &lt;span style="color:blue;"&gt;public &lt;/span&gt;AlbumManagerModel(IAlbumRepository albumRepository)
        {
            &lt;span style="color:blue;"&gt;this&lt;/span&gt;.albumRepository = albumRepository;
        }

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Search all the albums from a given artist.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        /// &amp;lt;param name=&amp;quot;artist&amp;quot;&amp;gt;&amp;lt;/param&amp;gt;
        /// &amp;lt;returns&amp;gt;&amp;lt;/returns&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;public &lt;/span&gt;IEnumerable&amp;lt;Album&amp;gt; GetAlbumsByArtist(Artist artist)
        {
            &lt;span style="color:blue;"&gt;return &lt;/span&gt;albumRepository.GetByArtist(artist);
        }

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Persist an album.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        /// &amp;lt;param name=&amp;quot;album&amp;quot;&amp;gt;&amp;lt;/param&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;public void &lt;/span&gt;SaveAlbum(Album album)
        {
            albumRepository.MakePersistent(album);
        }

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Revert changes of a given album to his original state.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        /// &amp;lt;param name=&amp;quot;album&amp;quot;&amp;gt;&amp;lt;/param&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;public void &lt;/span&gt;CancelAlbum(Album album)
        {
            albumRepository.Refresh(album);
        }

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Flush all changes to the database.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        &lt;/span&gt;[PersistenceConversation(ConversationEndMode = EndMode.End)]
        &lt;span style="color:blue;"&gt;public void &lt;/span&gt;SaveAll()
        { }

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Cancel all changes.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        &lt;/span&gt;[PersistenceConversation(ConversationEndMode = EndMode.Abort)]
        &lt;span style="color:blue;"&gt;public void &lt;/span&gt;CancelAll()
        {
        }
    }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;pre class="brush: csharp;"&gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;

&lt;p&gt;Well, this is the non-invasive AOP way of doing with CpBT from unhaddins. 
  &lt;br /&gt;The PersistenceCovnersational attribute tell us two things: 

  &lt;br /&gt;- All methods are involved in the conversation if not explicitly excluded. 

  &lt;br /&gt;– All methods ends with “Continue” if not explicitly changed. 

  &lt;br /&gt;SaveAll end the conversation with EndMode.End, this means that the UoW will be flushed. 

  &lt;br /&gt;For the other hand CancelAll end with Abort, this means that all changes are evicted and the conversation is not flushed.&lt;/p&gt;

&lt;h3&gt;Testing the model&lt;/h3&gt;

&lt;p&gt;Testing is very simple, all you need to do is to mock your repositories as follows: 
  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="code"&gt;[Test]
&lt;span style="color:blue;"&gt;public void &lt;/span&gt;can_cancel_album()
{
    var repository = &lt;span style="color:blue;"&gt;new &lt;/span&gt;Mock&amp;lt;IAlbumRepository&amp;gt;();
    var album = &lt;span style="color:blue;"&gt;new &lt;/span&gt;Album();
    repository.Setup(rep =&amp;gt; rep.Refresh(It.IsAny&amp;lt;Album&amp;gt;()))
              .AtMostOnce();

    var albumManagerModel = &lt;span style="color:blue;"&gt;new &lt;/span&gt;AlbumManagerModel(repository.Object);

    albumManagerModel.CancelAlbum(album);

    repository.Verify(rep =&amp;gt; rep.Refresh(album));
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;In this test I’m using the &lt;a href="http://code.google.com/p/moq/"&gt;Moq&lt;/a&gt; library. 

  &lt;br /&gt;The other thing that we need to test is the conversation configuration, my first approach was to test the attributes, but owned by the fact that we can configure the CpBT in many ways (such as XML), this is my test:&lt;/p&gt;

&lt;pre class="code"&gt;[TestFixtureSetUp]
&lt;span style="color:blue;"&gt;public void &lt;/span&gt;FixtureSetUp()
{
    conversationalMetaInfoStore.Add(&lt;span style="color:blue;"&gt;typeof &lt;/span&gt;(AlbumManagerModel));
    metaInfo = conversationalMetaInfoStore.GetMetadataFor(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(AlbumManagerModel));
}

[Test]
&lt;span style="color:blue;"&gt;public void &lt;/span&gt;model_represents_conversation()
{
    metaInfo.Should().Not.Be.Null();
    metaInfo.Setting.DefaultEndMode.Should().Be.EqualTo(EndMode.Continue);
    metaInfo.Setting.MethodsIncludeMode.Should().Be.EqualTo(MethodsIncludeMode.Implicit);
}

[Test]
&lt;span style="color:blue;"&gt;public void &lt;/span&gt;cancel_all_abort_the_conversation()
{
    var method = Strong.Instance&amp;lt;AlbumManagerModel&amp;gt;
        .Method(am =&amp;gt; am.CancelAll());

    var conversationInfo = metaInfo.GetConversationInfoFor(method);

    conversationInfo.ConversationEndMode
                    .Should().Be.EqualTo(EndMode.Abort);
}

[Test]
&lt;span style="color:blue;"&gt;public void &lt;/span&gt;save_all_end_the_conversation()
{
    var method = Strong.Instance&amp;lt;AlbumManagerModel&amp;gt;
        .Method(am =&amp;gt; am.SaveAll());

    var conversationInfo = metaInfo.GetConversationInfoFor(method);

    conversationInfo.ConversationEndMode
                    .Should().Be.EqualTo(EndMode.End);
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;I&amp;#39;m using a strongly typed way to get the MethodInfo extracted from this &lt;a href="http://www.codeproject.com/KB/cs/Strong.aspx"&gt;example&lt;/a&gt;.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://nhforge.org/aggbug.aspx?PostID=470" width="1" height="1"&gt;</description><category domain="http://nhforge.org/blogs/nhibernate/archive/tags/AOP/default.aspx">AOP</category><category domain="http://nhforge.org/blogs/nhibernate/archive/tags/Session/default.aspx">Session</category><category domain="http://nhforge.org/blogs/nhibernate/archive/tags/WPF/default.aspx">WPF</category></item><item><title>Nhibernate and WPF: The core</title><link>http://nhforge.org/blogs/nhibernate/archive/2009/08/15/nhibernate-and-wpf-the-core.aspx</link><pubDate>Sun, 16 Aug 2009 00:30:52 GMT</pubDate><guid isPermaLink="false">45f813f2-f1c4-4eda-a619-288e3cadc793:469</guid><dc:creator>Jose Romaniello</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://nhforge.org/blogs/nhibernate/rsscomments.aspx?PostID=469</wfw:commentRss><comments>http://nhforge.org/blogs/nhibernate/archive/2009/08/15/nhibernate-and-wpf-the-core.aspx#comments</comments><description>&lt;p&gt;   &lt;br /&gt;Part I: &lt;a href="http://jfromaniello.blogspot.com/2009/08/introducing-nhiberate-and-wpf.html"&gt;Introducing NHiberate and WPF: The ChinookMediaManager&lt;/a&gt;&lt;/p&gt;  &lt;h3&gt;Introduction&lt;/h3&gt;  &lt;p&gt;   &lt;br /&gt;This is my second post about the Chinook Media Manager, an example application for NHibernate and WPF. In this post I will outline some concepts behind the architecture that I’ve chosen.&lt;/p&gt;  &lt;h3&gt;Note&lt;/h3&gt;  &lt;p&gt;Probably at some points you will feel that this is over-architected, YAGNI and so on. Yes, you are right I’m not trying to bind a grid to a collection of objects there are tons of samples on the net about that subject.    &lt;br /&gt;&lt;/p&gt;  &lt;h3&gt;The four musketeers&lt;/h3&gt;  &lt;p&gt;The core of the application is composed of four components:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;ChinookMediaManager.Data: Contains the definition of repositories interfaces. &lt;/li&gt;    &lt;li&gt;ChinookMediaManager.DataImpl: Contains the implementation of these repositories plus other nhibernate things that we will need to make work the implementation of repositories (like mappings). &lt;/li&gt;    &lt;li&gt;ChinookMediaManager.Domain: Contains the domain classes plus model interfaces (we will focus on this concept latter) &lt;/li&gt;    &lt;li&gt;ChinookMediaManager.DomainImpl: Contains the implementation of the models. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;My base repository definition is as follows: &lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public interface &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IRepository&lt;/span&gt;&amp;lt;T&amp;gt; : IQueryable&amp;lt;T&amp;gt;
    {
        T Get(&lt;span style="color:blue;"&gt;object &lt;/span&gt;id);
        T Load(&lt;span style="color:blue;"&gt;object &lt;/span&gt;id);
        T MakePersistent(T entity);
        &lt;span style="color:blue;"&gt;void &lt;/span&gt;Refresh(T entity);
        &lt;span style="color:blue;"&gt;void &lt;/span&gt;MakeTransient(T entity);
    }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This means that a repository is a IQueryable&amp;lt;T&amp;gt; by itself and we can build queries in a more natural way. 
  &lt;br /&gt;I have seen a lot of repositories implementations with methods Save, Update and Delete, there is nothing wrong with it, just that I think that MakePersistent (Save) and MakeTransient (Delete) better represents that functionality (I have stolen this terminology from a &lt;a href="http://gustavoringel.blogspot.com/"&gt;Gustavo Ringel&lt;/a&gt;’s example). 

  &lt;br /&gt;You could find the implementation &lt;a href="http://code.google.com/p/unhaddins/source/browse/trunk/Examples/uNHAddIns.Examples.WPF/ChinookMediaManager.Data.Impl/Repositories/Repository.cs"&gt;here&lt;/a&gt;. 

  &lt;br /&gt;&lt;/p&gt;

&lt;h3&gt;Don’t touch “the domain”&lt;/h3&gt;

&lt;p&gt;Working with WPF sometimes you will need that your entities implement INotifyPropertyChanged or IEditableObject for data binding. Although the implementation of those interfaces is simple, if you implement directly in your domain you will tie your domain to a presentation concern and also will end writing a lot of code. 
  &lt;br /&gt;

  &lt;br /&gt;So, I wrote an addin for nhibernate (unhaddins.wpf) that will help you to inject those behaviors without touching anything in your domain model.&amp;#160; &lt;br /&gt;

  &lt;br /&gt;We only have to add the entity to the container as follows:&lt;/p&gt;

&lt;pre class="code"&gt;container.Register(Component.For&amp;lt;Album&amp;gt;()
    .NhibernateEntity()
    .AddNotificableBehavior()
    .LifeStyle.Transient);&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;If you need to add editable object behavior (read &lt;a href="http://jfromaniello.blogspot.com/2009/07/ieditableobject-useful-interface.html"&gt;this&lt;/a&gt; and &lt;a href="http://jfromaniello.blogspot.com/2009/07/ieditableobject-another-behaviour-for.html"&gt;this&lt;/a&gt;) you simple put “.AddEditableBehavior()”. 

  &lt;br /&gt;If we want a transient instance we will request it to the container (or an object factory). In unhaddins we have got an artifact that allows nhibernate to instantiate entities from the container, read &lt;a href="http://fabiomaulo.blogspot.com/2008/11/entities-behavior-injection.html"&gt;this&lt;/a&gt; post from Fabio Maulo. 

  &lt;br /&gt;

  &lt;br /&gt;For INotifyCollectionChanged, unhaddins.wpf has a Collection Type Factory, we need to configure NHibernate as follows:&lt;/p&gt;

&lt;pre class="code"&gt;nhConfiguration.Properties[Environment.CollectionTypeFactoryClass] =
  &lt;span style="color:blue;"&gt;typeof &lt;/span&gt;(WpfCollectionTypeFactory).AssemblyQualifiedName;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;With this simple step all bag, sets and list (more coming up) of objects retrieved from NHibernate will implement INotifyCollectionChanged.&lt;/p&gt;

&lt;p&gt;It goes without saying that this configuration is not in the domain. 
  &lt;br /&gt;

  &lt;br /&gt;As you can see, I don’t have to put presentations concerns inside &lt;em&gt;“the four musketeers”&lt;/em&gt;. &lt;/p&gt;

&lt;p&gt;In the next post I will talk about models and CpBT.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://nhforge.org/aggbug.aspx?PostID=469" width="1" height="1"&gt;</description><category domain="http://nhforge.org/blogs/nhibernate/archive/tags/AOP/default.aspx">AOP</category><category domain="http://nhforge.org/blogs/nhibernate/archive/tags/Session/default.aspx">Session</category><category domain="http://nhforge.org/blogs/nhibernate/archive/tags/WPF/default.aspx">WPF</category></item><item><title>Introducing NHiberate and WPF: The ChinookMediaManager</title><link>http://nhforge.org/blogs/nhibernate/archive/2009/08/15/introducing-nhiberate-and-wpf-the-chinookmediamanager.aspx</link><pubDate>Sun, 16 Aug 2009 00:26:25 GMT</pubDate><guid isPermaLink="false">45f813f2-f1c4-4eda-a619-288e3cadc793:468</guid><dc:creator>Jose Romaniello</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://nhforge.org/blogs/nhibernate/rsscomments.aspx?PostID=468</wfw:commentRss><comments>http://nhforge.org/blogs/nhibernate/archive/2009/08/15/introducing-nhiberate-and-wpf-the-chinookmediamanager.aspx#comments</comments><description>&lt;p&gt;As you can note in my previous posts I’ve talked a lot about NHibernate and WPF. So I&amp;#39;ve decided to write an ongoing series of blog posts about the integration of these two technologies. &lt;/p&gt;  &lt;h3&gt;Motivation&lt;/h3&gt;  &lt;p&gt;The motivation behind this series of posts is very simple most of the articles that you can read about NHibernate are for web technologies such as ASP.Net or ASP.NET MVC. Despite the fact that NHibernate is an ORM and has nothing to do with the presentation layer there are certain consideration that you have to take into account to build a good architecture. &lt;/p&gt;  &lt;h3&gt;Sample Domain&lt;/h3&gt;  &lt;p&gt;For this series of post I have chosen to use a small subset of the &lt;a href="http://www.codeplex.com/ChinookDatabase"&gt;Chinook&lt;/a&gt; database with few modifications. I have changed all the Identities primary keys to HiLo. You can find both the original and the slightly modified version &lt;a href="http://code.google.com/p/unhaddins/source/browse/#svn/trunk/SampleDomain"&gt;here&lt;/a&gt; (with class, mappings and read only tests).&lt;/p&gt;  &lt;p&gt;This is the full database schema:&lt;/p&gt;  &lt;p&gt;&lt;img src="http://lh4.ggpht.com/_oKo6zFhdD98/SWFPtyfHJFI/AAAAAAAAAMc/GdrlzeBNsZM/s800/ChinookDatabaseSchema1.1.png" width="609" height="492" alt="" /&gt; &lt;/p&gt;  &lt;p&gt;However we will focus in this subset of the domain:    &lt;br /&gt;    &lt;br /&gt;&lt;a href="http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/nhibernate/ClassDiagram1_5F00_055516A1.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="ClassDiagram1" border="0" alt="ClassDiagram1" src="http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/nhibernate/ClassDiagram1_5F00_thumb_5F00_4FDEE52C.png" width="331" height="477" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h3&gt;A word about session management&lt;/h3&gt;  &lt;p&gt;Most of the examples of NHibernate for web applications uses a pattern called “Session-per-Request”, this means that the session and the transaction has the same lifetime that the web request. This pattern is very easy to work with and very easy to understood but is not suitable for desktop applications.    &lt;br /&gt;There are two antipatterns called “session-per-application” and “session-per-call” that you need to avoid.     &lt;br /&gt;The pattern that I will use for this series is called “conversation per bussines transactions” and is very well described by his inventor &lt;a href="http://fabiomaulo.blogspot.com/"&gt;Fabio Maulo&lt;/a&gt;. I’ve learned a lot with Fabio and &lt;a href="http://gustavoringel.blogspot.com/"&gt;Gustavo Ringel&lt;/a&gt;&amp;#160; about CpBT. &lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;h3&gt;A word about data binding&lt;/h3&gt;  &lt;p&gt;In this series of post we will make intensive use of WPF data binding capabilities. Is for that reason that I’ve written &lt;a href="http://code.google.com/p/unhaddins/source/browse/#svn/trunk/uNhAddIns/uNhAddIns.WPF"&gt;uNHAddIns.WPF&lt;/a&gt; that uses NHibernate extensions points to bring us few behaviors that we need for data binding.&lt;/p&gt;  &lt;h4&gt;The interface that we have to solve&lt;/h4&gt;  &lt;p&gt;&lt;a href="http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/nhibernate/albums_5F00_37E02626.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="albums" border="0" alt="albums" src="http://nhforge.org/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/nhibernate/albums_5F00_thumb_5F00_03647540.png" width="482" height="388" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;The user need this very complex GUI. The user-story is as follows:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;The user can have multiple instances of this window open for editing albums of different artists. &lt;/li&gt;    &lt;li&gt;The user can add albums. &lt;/li&gt;    &lt;li&gt;The user can add tracks to the new albums and preexistent albums. &lt;/li&gt;    &lt;li&gt;None of the information is persisted until the user press “Save All”. &lt;/li&gt;    &lt;li&gt;If the user press close the application will ask to the user if he really want to discard all changes. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;   &lt;br /&gt;This is all for now, in the next post I will talk about the architecture that I will use.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://nhforge.org/aggbug.aspx?PostID=468" width="1" height="1"&gt;</description><category domain="http://nhforge.org/blogs/nhibernate/archive/tags/Session/default.aspx">Session</category><category domain="http://nhforge.org/blogs/nhibernate/archive/tags/WPF/default.aspx">WPF</category></item></channel></rss>