<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Random Ramblings</title>
	<atom:link href="http://leomburke.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://leomburke.wordpress.com</link>
	<description>Random (mostly) .net related rambles</description>
	<lastBuildDate>Sun, 31 Mar 2013 17:17:12 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='leomburke.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Random Ramblings</title>
		<link>http://leomburke.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://leomburke.wordpress.com/osd.xml" title="Random Ramblings" />
	<atom:link rel='hub' href='http://leomburke.wordpress.com/?pushpress=hub'/>
		<item>
		<title>EF Code First and WPF with the Chinook database. Part 3 &#8211; Styles and DataTemplates 101</title>
		<link>http://leomburke.wordpress.com/2011/02/22/ef-code-first-and-wpf-with-the-chinook-database-part-3-styles-and-datatemplates-101/</link>
		<comments>http://leomburke.wordpress.com/2011/02/22/ef-code-first-and-wpf-with-the-chinook-database-part-3-styles-and-datatemplates-101/#comments</comments>
		<pubDate>Tue, 22 Feb 2011 13:48:53 +0000</pubDate>
		<dc:creator>Leom Burke</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Skins]]></category>
		<category><![CDATA[Styles]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">https://leomburke.wordpress.com/?p=158</guid>
		<description><![CDATA[I have decided to split out the styling work into 2 posts as it would be a huge post to restyle even something so simple.  so this post is going to change the controls to be more style-conscious and introduce basic style and the next post will introduce some more advance concepts such as using [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leomburke.wordpress.com&#038;blog=7579884&#038;post=158&#038;subd=leomburke&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I have decided to split out the styling work into 2 posts as it would be a huge post to restyle even something so simple.  so this post is going to change the controls to be more style-conscious and introduce basic style and the next post will introduce some more advance concepts such as using adorners to display additional details.</p>
<p>Going back to <a href="http://leomburke.wordpress.com/2011/02/08/ef-code-first-and-wpf-with-the-chinook-database-part-2-the-client/">the previous post</a> we had a basic app as follows:</p>
<p><img src="http://leomburke.files.wordpress.com/2011/02/image.png?w=630" alt="" /></p>
<p>This is slightly ugly and needs a little work so the first thing I want to add is  a style that will tidy up the artist list.</p>
<p>I want the artist list to have a nice look and feel with rounded button type items and also contain a count of the number of albums – I want each item in the list to look something like this:</p>
<p><a href="http://leomburke.files.wordpress.com/2011/02/image1.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="image" src="http://leomburke.files.wordpress.com/2011/02/image_thumb1.png?w=364&#038;h=37" border="0" alt="image" width="364" height="37" /></a></p>
<p>The first step to getting this design in place is adding the <a href="http://msdn.microsoft.com/en-us/library/ms742521.aspx">DataTemplate</a> so that it is picked up by the item.  A DataTemplate is a template that gets applied to an object that has no default way of showing itself and manifests itself as its type name.</p>
<p><em>NOTE – this can also be be done by overriding Object.ToString() but this is a client side post so I don’t want to have to change model code to do something.</em></p>
<p>I have added a simple DataTemplate to the Application.Resources section in App.xaml as follows:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;DataTemplate DataType=&quot;{x:Type business:Artist}&quot;&gt;
    &lt;TextBlock x:Name=&quot;contentHolder&quot;&gt;
        &lt;TextBlock.Text&gt;
            &lt;MultiBinding StringFormat=&quot;{}{0} - {1} albums&quot;&gt;
                &lt;Binding Path=&quot;Name&quot;/&gt;
                &lt;Binding Path=&quot;Albums.Count&quot; /&gt;
            &lt;/MultiBinding&gt;
        &lt;/TextBlock.Text&gt;                
    &lt;/TextBlock&gt;
    &lt;DataTemplate.Triggers&gt;
        &lt;DataTrigger Binding=&quot;{Binding Albums.Count}&quot; Value=&quot;1&quot;&gt;
            &lt;DataTrigger.Setters&gt;
                &lt;Setter Property=&quot;TextBlock.Text&quot; TargetName=&quot;contentHolder&quot;&gt;
                    &lt;Setter.Value&gt;
                        &lt;MultiBinding StringFormat=&quot;{}{0} - {1} album&quot;&gt;
                            &lt;Binding Path=&quot;Name&quot;/&gt;
                            &lt;Binding Path=&quot;Albums.Count&quot; /&gt;
                        &lt;/MultiBinding&gt;
                    &lt;/Setter.Value&gt;
                &lt;/Setter&gt;
            &lt;/DataTrigger.Setters&gt;
        &lt;/DataTrigger&gt;
    &lt;/DataTemplate.Triggers&gt;
&lt;/DataTemplate&gt;
</pre>
<p>There are several things going on here:</p>
<ol>
<li>the first line declares the type that this template is associated with – you have to add the namespace to this file first in order to make this work:
<pre class="brush: xml; title: ; notranslate">
xmlns:business=&quot;clr-namespace:MusicApp.Model;assembly=MusicApp.Model&quot;
</pre>
</li>
<li>The MultiBinding has an associated StringFormat – this is the same as a normal format string except for the “{}” after the equals sign – this simply escapes the format string.</li>
<li>The binding to Albums.Count – yes you can bind to “built-in” properties as well.</li>
<li>The DataTrigger is a simple way of saying that if we have only one album then the trailing text shouldn’t have an ‘s’ on the end.</li>
</ol>
<p>It is possible to do the whole string in a converter but I like the declarative way as you can see everything going on in one place.  For those that like using converters you would bind the TextBlock’s Text property to the whole Artist ({Binding}) and then use a converter like the following:</p>
<pre class="brush: csharp; title: ; notranslate">
public class ArtistStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string retVal = string.Empty;
        var artist = value as Artist;
        if (artist != null)
        {
            retVal += string.Format(&quot;{0} - {1} {2}&quot;, artist.Name, artist.Albums.Count, artist.Albums.Count == 1 ? &quot;artist&quot; : &quot;artists&quot;);
        }

        return retVal;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</pre>
<p>this is then used from the xaml as follows:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;local:ArtistStringConverter x:Key=&quot;artistConverter&quot;/&gt;
&lt;DataTemplate DataType=&quot;{x:Type business:Artist}&quot;&gt;
    &lt;TextBlock x:Name=&quot;contentHolder&quot; Text=&quot;{Binding Converter={StaticResource artistConverter}}&quot; /&gt;
&lt;/DataTemplate&gt;
</pre>
<p>Once this is added (either option) you need to remove the DisplayMemberPath property from the ArtistList.xaml view so that the template is used instead.</p>
<p>I now have a list of Artists that show the name and the total albums they have so I can work on the actual style to make the list items look like the above image.</p>
<p>I want all three lists to look the same so I am adding a style with no key to the app.xaml file.  If you want specific styles for your controls then you can add ‘x:Key=”YourKeyName”’ and reference it using ‘{StaticResource YourKeyName}’ (in this instance the reference would be in the ItemContainerStyle property of the ListBox).</p>
<pre class="brush: xml; title: ; notranslate">
&lt;Style TargetType=&quot;ListBoxItem&quot;&gt;
    &lt;Style.Setters&gt;
        &lt;Setter Property=&quot;Margin&quot; Value=&quot;5,2&quot; /&gt;
        &lt;Setter Property=&quot;Template&quot;&gt;
            &lt;Setter.Value&gt;
                &lt;ControlTemplate TargetType=&quot;ListBoxItem&quot;&gt;
                    &lt;Grid&gt;
                        &lt;Rectangle Opacity=&quot;0.5&quot; Height=&quot;30&quot; StrokeThickness=&quot;1&quot; x:Name=&quot;backBox&quot;
                                        Stroke=&quot;Silver&quot; RadiusX=&quot;5&quot; RadiusY=&quot;5&quot; Fill=&quot;Azure&quot;/&gt;
                        &lt;ContentPresenter HorizontalAlignment=&quot;Center&quot; VerticalAlignment=&quot;Center&quot;/&gt;
                    &lt;/Grid&gt;
                    &lt;ControlTemplate.Triggers&gt;
                        &lt;Trigger Property=&quot;Selector.IsSelected&quot; Value=&quot;True&quot;&gt;
                            &lt;Setter TargetName=&quot;backBox&quot; Property=&quot;Fill&quot; Value=&quot;Silver&quot;/&gt;
                        &lt;/Trigger&gt;
                    &lt;/ControlTemplate.Triggers&gt;
                &lt;/ControlTemplate&gt;
            &lt;/Setter.Value&gt;
        &lt;/Setter&gt;
    &lt;/Style.Setters&gt;
&lt;/Style&gt;
</pre>
<p>Again I have a couple of things going on inside this style:</p>
<ol>
<li>It targets ListBoxItem as this is what we want to style (not the ListBox itself).</li>
<li>The margin separates the items nicely.</li>
<li>The actual style part is contained inside a ControlTemplate which is then assigned  the Template property of the ListBoxItem.</li>
<li>The ContentPresenter will present whatever content it is given, in this case it is presenting the passed in DataTemplate.</li>
<li>The trigger here indicates that when the ListBoxItem is selected we want to change the fill colour of the rectangle to indicate we have selected an item.</li>
</ol>
<p>To finish I have added a new DataTemplate for the albums – this looks the same with the type and property names changed to display the correct things and I have also rearranged the view as follows:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;Grid&gt;
    &lt;Grid.ColumnDefinitions&gt;
        &lt;ColumnDefinition Width=&quot;0.5*&quot; /&gt;
        &lt;ColumnDefinition Width=&quot;0.5*&quot; /&gt;
    &lt;/Grid.ColumnDefinitions&gt;
    &lt;Grid.RowDefinitions&gt;
        &lt;RowDefinition Height=&quot;0.5*&quot;/&gt;
        &lt;RowDefinition Height=&quot;0.5*&quot;/&gt;
    &lt;/Grid.RowDefinitions&gt;

    &lt;ListBox ItemsSource=&quot;{Binding Path=Artists}&quot; Margin=&quot;5&quot; 
                Grid.Column=&quot;0&quot; Grid.Row=&quot;0&quot;
                Grid.RowSpan=&quot;2&quot;
                SelectedItem=&quot;{Binding SelectedArtist}&quot; /&gt;
        
    &lt;ListBox ItemsSource=&quot;{Binding Path=SelectedArtist.Albums}&quot; Margin=&quot;5&quot; 
                Grid.Column=&quot;1&quot; Grid.Row=&quot;0&quot; 
                SelectedItem=&quot;{Binding SelectedAlbum}&quot; /&gt;
        
    &lt;ListBox ItemsSource=&quot;{Binding Path=SelectedAlbum.Tracks}&quot; Margin=&quot;5&quot; 
                DisplayMemberPath=&quot;Name&quot; 
                Grid.Column=&quot;1&quot; Grid.Row=&quot;1&quot; /&gt;
&lt;/Grid&gt;
</pre>
<p>This now gives me the following view which I am sure you will agree looks a lot better and is easily achievable by simply using XAML – we could have done this in blend as well but for the simple changes we have made I prefer to edit the XAML directly.</p>
<p><a href="http://leomburke.files.wordpress.com/2011/02/image2.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="image" src="http://leomburke.files.wordpress.com/2011/02/image_thumb2.png?w=575&#038;h=349" border="0" alt="image" width="575" height="349" /></a></p>
<p>In the next post I will be adding some adorner goodness to the screen for displaying album and track details (which also covers changes to the model).</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/leomburke.wordpress.com/158/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/leomburke.wordpress.com/158/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leomburke.wordpress.com&#038;blog=7579884&#038;post=158&#038;subd=leomburke&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://leomburke.wordpress.com/2011/02/22/ef-code-first-and-wpf-with-the-chinook-database-part-3-styles-and-datatemplates-101/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/67f0caee10a2adc1664f26eda21facb9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">leomburke</media:title>
		</media:content>

		<media:content url="http://leomburke.files.wordpress.com/2011/02/image.png" medium="image" />

		<media:content url="http://leomburke.files.wordpress.com/2011/02/image_thumb1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://leomburke.files.wordpress.com/2011/02/image_thumb2.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>EF Code First and WPF with the Chinook database. Part 2 &#8211; The client</title>
		<link>http://leomburke.wordpress.com/2011/02/08/ef-code-first-and-wpf-with-the-chinook-database-part-2-the-client/</link>
		<comments>http://leomburke.wordpress.com/2011/02/08/ef-code-first-and-wpf-with-the-chinook-database-part-2-the-client/#comments</comments>
		<pubDate>Tue, 08 Feb 2011 14:27:07 +0000</pubDate>
		<dc:creator>Leom Burke</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">https://leomburke.wordpress.com/?p=146</guid>
		<description><![CDATA[Now we have the data fetching work sorted out we can turn our attentions to the front-end. I am going to make a very simple view in this post listing the artists and associated albums with their tracks.  It is going to look like this: Now, this is very basic but it serves its purpose [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leomburke.wordpress.com&#038;blog=7579884&#038;post=146&#038;subd=leomburke&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Now we have the data fetching work sorted out we can turn our attentions to the front-end.</p>
<p>I am going to make a very simple view in this post listing the artists and associated albums with their tracks.  It is going to look like this:</p>
<p><a href="http://leomburke.files.wordpress.com/2011/02/image.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;" title="image" src="http://leomburke.files.wordpress.com/2011/02/image_thumb.png?w=268&#038;h=299" border="0" alt="image" width="268" height="299" /></a></p>
<p>Now, this is very basic but it serves its purpose to show the tools we are going to be using – a later post will use the power of WPF to style and transform the screen into something more palatable.</p>
<p>The first thing to do is add a WPF project(I have named mine MusicApp.WPF.Client).  If you rename the the MainWindow.xaml file then don’t forget to change the startup uri in app.xaml</p>
<pre class="brush: xml; title: ; notranslate">
&lt;Application x:Class=&quot;MusicApp.WPF.Client.App&quot;
             xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
             xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
             StartupUri=&quot;Main.xaml&quot;&gt;
</pre>
<p>In terms of the structure for the project I have separate folders for views, view models and common files.</p>
<p><strong>The View</strong></p>
<p>Once the basic structure is in place we can add our view to the Views folder.  The view in this case is a user control that we will add to the main window.</p>
<p>The view itself is very simplistic – 1 grid containing 3 ListBoxes and is created as follows</p>
<pre class="brush: xml; title: ; notranslate">
&lt;UserControl x:Class=&quot;MusicApp.WPF.Client.Views.ArtistList&quot;
              xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
              xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
              Height=&quot;Auto&quot; Width=&quot;Auto&quot;&gt;
    &lt;Grid&gt;
        &lt;Grid.ColumnDefinitions&gt;
            &lt;ColumnDefinition Width=&quot;0.5*&quot; /&gt;
            &lt;ColumnDefinition Width=&quot;0.5*&quot; /&gt;
        &lt;/Grid.ColumnDefinitions&gt;
        &lt;Grid.RowDefinitions&gt;
            &lt;RowDefinition Height=&quot;0.7*&quot;/&gt;
            &lt;RowDefinition Height=&quot;0.3*&quot;/&gt;
        &lt;/Grid.RowDefinitions&gt;
        &lt;ListBox ItemsSource=&quot;{Binding Path=Artists}&quot; Margin=&quot;5&quot; 
                 DisplayMemberPath=&quot;Name&quot; Grid.Column=&quot;0&quot; 
                 Grid.ColumnSpan=&quot;2&quot; Grid.Row=&quot;0&quot; 
                 SelectedItem=&quot;{Binding SelectedArtist}&quot; /&gt;
        
        &lt;ListBox ItemsSource=&quot;{Binding Path=SelectedArtist.Albums}&quot; Margin=&quot;5&quot; 
                 DisplayMemberPath=&quot;Title&quot; Grid.Column=&quot;0&quot; Grid.Row=&quot;1&quot; 
                 SelectedItem=&quot;{Binding SelectedAlbum}&quot; /&gt;
        
        &lt;ListBox ItemsSource=&quot;{Binding Path=SelectedAlbum.Tracks}&quot; Margin=&quot;5&quot; 
                 DisplayMemberPath=&quot;Name&quot; Grid.Column=&quot;1&quot; Grid.Row=&quot;1&quot; /&gt;
    &lt;/Grid&gt;
&lt;/UserControl&gt;
</pre>
<p>This is a view with a 2 x 2 grid with columns of equal width (1/2 of the grid each) and one row at 70% width and one at 30%.  Inside the grid there is a ListBox that takes up the whole top row (ColumnSpan=2) and one ListBox in each of the columns in the lower row.</p>
<p>I have included all of the bindings so that I know what is required on the view model when I write it.  I will need a collection property called ‘Artists’ and 2 properties for the selected artist and selected album.</p>
<p>The DisplayMemberPath details which property of the object will be displayed as text in the ListBoxItem.</p>
<p>Once the control has been written then we can add it to the main window xaml.  There are 2 things to do to add a usercontrol to another xaml file</p>
<ol>
<li>add the correct namespace.</li>
<li>add the control</li>
</ol>
<p>Adding the namespace requires that we add an xmlns to the top of the main window file</p>
<pre class="brush: xml; title: ; notranslate">
xmlns:views=&quot;clr-namespace:MusicApp.WPF.Client.Views&quot;
</pre>
<p>Once we have this then we can simply add the control as a new object on the window</p>
<pre class="brush: xml; title: ; notranslate">
&lt;views:ArtistList/&gt;
</pre>
<p>which gives us a Main window with the following xaml</p>
<pre class="brush: xml; title: ; notranslate">
&lt;Window x:Class=&quot;MusicApp.WPF.Client.Main&quot;
        xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
        xmlns:views=&quot;clr-namespace:MusicApp.WPF.Client.Views&quot;
        Title=&quot;Main&quot; Height=&quot;475&quot; Width=&quot;425&quot;&gt;
    &lt;Grid&gt;
        &lt;views:ArtistList/&gt;
    &lt;/Grid&gt;
&lt;/Window&gt;
</pre>
<p><strong>The ViewModel</strong></p>
<p>Now the view is done I can create a ViewModel to support it.  The ViewModel will need to implement INotifyPropertyChanged and I have the following snippet method that will fire the event implemented by it</p>
<pre class="brush: csharp; title: ; notranslate">
private void Notify(string propertyName)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
</pre>
<p><strong>Unity</strong></p>
<p>I want to be able to use a different data provider here if I want to so I am going to introduce the Unity IoC container to the application at this point.  Unity can be installed into the current project directly from NuGet (<em>install-package unity</em>) or you can download directly. It needs a little configuration before we can use it.</p>
<p>I am going to use it to resolve a reference to the IDataProvider interface we created previously so I add a new app.config file to the client project and add the following configuration</p>
<pre class="brush: xml; title: ; notranslate">
&lt;configuration&gt;
    &lt;configSections&gt;
        &lt;section name=&quot;unity&quot;
                             type=&quot;Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration&quot; /&gt;
    &lt;/configSections&gt;
    &lt;unity&gt;
        &lt;containers&gt;
            &lt;container&gt;
                &lt;type type=&quot;MusicApp.Model.IDataProvider, MusicApp.Model&quot; mapTo=&quot;MusicApp.Model.EFCodeFirstDataProvider, MusicApp.Model&quot; /&gt;
            &lt;/container&gt;
        &lt;/containers&gt;
    &lt;/unity&gt;
&lt;/configuration&gt;
</pre>
<p>This is simply adding a mapping between IDataProvider and EFCodeFirstDataProvider which allows me to resolve the former to the latter.</p>
<p>We need a way of referencing this container in our application so I use a factory class with a static member to hold the actual UnityContainer</p>
<pre class="brush: csharp; title: ; notranslate">
class ContainerFactory
{
    private static UnityContainer container;

    public ContainerFactory()
    {
        if (container == null)
        {
            container = new UnityContainer();
            UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection(&quot;unity&quot;);
            section.Containers.Default.Configure(container);
        }
    }

    public UnityContainer Container
    {
        get
        {
            return container;
        }
    }
}
</pre>
<p>I can then have a reference to an IDataProvider in the ViewModel and resolve it from the constructor as follows</p>
<pre class="brush: csharp; title: ; notranslate">
ContainerFactory factory = new ContainerFactory();
provider = factory.Container.Resolve&lt;IDataProvider&gt;();
</pre>
<p>The whole ViewModel including properties now looks like this.</p>
<pre class="brush: csharp; title: ; notranslate">
public class ArtistListViewModel : INotifyPropertyChanged
{
    private IDataProvider provider;
    private ObservableCollection&lt;Artist&gt; artists;
    private Artist selectedArtist;
    private Album selectedAlbum;

    public ArtistListViewModel()
    {
        ContainerFactory factory = new ContainerFactory();
        provider = factory.Container.Resolve&lt;IDataProvider&gt;();
        GetArtists();
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public ObservableCollection&lt;Artist&gt; Artists
    {
        get
        {
            return artists;
        }
        private set
        {
            artists = value;
            Notify(&quot;Artists&quot;);
        }
    }

    public Artist SelectedArtist
    {
        get
        {
            return selectedArtist;
        }
        set
        {
            selectedArtist = value;
            Notify(&quot;SelectedArtist&quot;);
        }
    }

    public Album SelectedAlbum
    {
        get
        {
            return selectedAlbum;
        }
        set
        {
            selectedAlbum = value;
            Notify(&quot;SelectedAlbum&quot;);
        }
    }

    private void GetArtists()
    {
        Artists = new ObservableCollection&lt;Artist&gt;(provider.GetArtists());
    }

    private void Notify(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
</pre>
<p><strong>Wire it up</strong></p>
<p>Now we have the ViewModel and view in place we need to wire them together this is just a case of setting the views DataContext from its constructor</p>
<pre class="brush: csharp; title: ; notranslate">
public ArtistList()
{
    InitializeComponent();
    this.DataContext = new ArtistListViewModel();
}
</pre>
<p><strong>Wrapping up</strong></p>
<p>Now we have these wired we simply need to add the ConnectionStrings to the config file (that we added the unity config to earlier), change the startup project to the new WPF app and run it.  This will now display the window shown at the start and I can change the artist to update the albums/tracks at the bottom.</p>
<p>Next time – making the view look good.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/leomburke.wordpress.com/146/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/leomburke.wordpress.com/146/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leomburke.wordpress.com&#038;blog=7579884&#038;post=146&#038;subd=leomburke&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://leomburke.wordpress.com/2011/02/08/ef-code-first-and-wpf-with-the-chinook-database-part-2-the-client/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/67f0caee10a2adc1664f26eda21facb9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">leomburke</media:title>
		</media:content>

		<media:content url="http://leomburke.files.wordpress.com/2011/02/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>EF Code First and WPF with the Chinook database. Part 1c &#8211; the unit tests</title>
		<link>http://leomburke.wordpress.com/2011/01/25/ef-code-first-and-wpf-with-the-chinook-database-part-1c-ndash-the-unit-tests/</link>
		<comments>http://leomburke.wordpress.com/2011/01/25/ef-code-first-and-wpf-with-the-chinook-database-part-1c-ndash-the-unit-tests/#comments</comments>
		<pubDate>Tue, 25 Jan 2011 12:04:48 +0000</pubDate>
		<dc:creator>Leom Burke</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Mocking]]></category>

		<guid isPermaLink="false">https://leomburke.wordpress.com/?p=139</guid>
		<description><![CDATA[In the final part of the server side code (we have already written a Code First provider and data provider) I am going to implement some unit tests for the two methods I currently have on the data provider. My unit tests will need to have no access to the database as that would break [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leomburke.wordpress.com&#038;blog=7579884&#038;post=139&#038;subd=leomburke&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In the final part of the server side code (we have already written a <a href="http://leomburke.wordpress.com/2011/01/13/ef-code-first-and-wpf-with-the-chinook-database-part-1-the-model/">Code First provider</a> and <a href="http://leomburke.wordpress.com/2011/01/20/ef-code-first-and-wpf-with-the-chinook-database-part-1b-the-provider/">data provider</a>) I am going to implement some unit tests for the two methods I currently have on the data provider.</p>
<p>My unit tests will need to have no access to the database as that would break the encapsulation of the test so we need to mock out the raw data access layer while still providing the functionality that we would expect from the Entity Framework context.</p>
<p>To do this we need to make several changes to the current project to allow us to inject a mocked up context into the data provider.</p>
<p>The first thing we need to do is to abstract the context used by the data provider out into an interface, being as we currently have a small set of classes then the interface is simply:</p>
<pre class="brush: csharp; title: ; notranslate">
public interface IContext
{
    IDbSet&lt;Artist&gt; Artist { get; set; }

    IDbSet&lt;Album&gt; Album { get; set; }

    IDbSet&lt;Track&gt; Track { get; set; }
}
</pre>
<p>Notice the IDbSet&lt;T&gt; – this is to allow us to mock up the DbSet’s using the same interface.</p>
<p>Next up we need to edit our Chinook class so that it uses this new interface (note, again, the IDbSet&lt;T&gt;’s)</p>
<pre class="brush: csharp; title: ; notranslate">
public class Chinook : DbContext, IContext
{
    protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove&lt;PluralizingTableNameConvention&gt;();
    }

    public IDbSet&lt;Artist&gt; Artist { get; set; }

    public IDbSet&lt;Album&gt; Album { get; set; }

    public IDbSet&lt;Track&gt; Track { get; set; }
}
</pre>
<p>Now we have this we can use the interface in the data provider and set it to a Chinook instance by default (for the time being).</p>
<pre class="brush: csharp; title: ; notranslate">
private IContext db = new Chinook();
</pre>
<p>Right we now have a good basis to start working on the test so add a new test project to the solution and create a new class called MockDbSet.  This allows us to simulate the actions of a real DbSet in the database for a given set of objects.  Huge thanks to <a href="http://thedatafarm.com/blog/data-access/agile-entity-framework-4-repository-part-6-mocks-amp-unit-tests/">Julie Lerman</a> for showing the starting point for this work with her series on EF4 repositories (A great read!).</p>
<p>The MockDbSet implements the IDbSet&lt;T&gt; Interface supplied by the Entity Framework and allows us to replicate the functionality as follows (note I have not implemented the create or find methods as I don’t need them right now.)</p>
<pre class="brush: csharp; title: ; notranslate">
public class MockDbSet&lt;T&gt; : IDbSet&lt;T&gt; where T : class
{
    readonly IList&lt;T&gt; _container = new List&lt;T&gt;();

    public T Add(T entity)
    {
        _container.Add(entity);
        return entity;
    }

    public T Attach(T entity)
    {
        _container.Add(entity);
        return entity;
    }

    public TDerivedEntity Create&lt;TDerivedEntity&gt;() where TDerivedEntity : class, T
    {
        throw new NotImplementedException();
    }

    public T Create()
    {
        throw new NotImplementedException();
    }

    public T Find(params object[] keyValues)
    {
        throw new NotImplementedException();
    }

    public System.Collections.ObjectModel.ObservableCollection&lt;T&gt; Local
    {
        get
        {
            return new ObservableCollection&lt;T&gt;(_container);
        }
    }

    public T Remove(T entity)
    {
        _container.Remove(entity);
        return entity;
    }

    public IEnumerator&lt;T&gt; GetEnumerator()
    {
        return _container.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return _container.GetEnumerator();
    }

    public Type ElementType
    {
        get
        {
            return typeof(T);
        }
    }

    public System.Linq.Expressions.Expression Expression
    {
        get
        {
            return _container.AsQueryable&lt;T&gt;().Expression;
        }
    }

    public IQueryProvider Provider
    {
        get
        {
            return _container.AsQueryable&lt;T&gt;().Provider;
        }
    }
 }
</pre>
<p>This is a simple implementation that stores the set in a local List.</p>
<p>Now we have a mock set we can mock up the context which is something that implements IContext and allows us to access the DbSets we want to work with outside of a database environment.  I have added some methods to add test data into the sets as well.</p>
<pre class="brush: csharp; title: ; notranslate">
class MockContext : IContext
{
    private IDbSet&lt;Artist&gt; artist;
    private IDbSet&lt;Album&gt; album;
    private IDbSet&lt;Track&gt; track;

    public IDbSet&lt;Artist&gt; Artist
    {
        get
        {
            this.CreateArtists();
            return this.artist;
        }

        set
        {
            throw new NotImplementedException();
        }
    }

    public IDbSet&lt;Album&gt; Album
    {
        get
        {
            this.CreateAlbums();
            return this.album;
        }
        
        set
        {
            throw new NotImplementedException();
        }
    }

    public IDbSet&lt;Track&gt; Track
    {
        get
        {
            this.CreateTracks();
            return this.track;
        }
        
        set
        {
            throw new NotImplementedException();
        }
    }

    private void CreateArtists()
    {
        if (artist == null)
        {
            artist = new MockDbSet&lt;Artist&gt;();
            artist.Add(new Artist { ArtistId = 1, Name = &quot;Test Artist 1&quot; });
            artist.Add(new Artist { ArtistId = 2, Name = &quot;Test Artist 2&quot; });
            artist.Add(new Artist { ArtistId = 3, Name = &quot;Test Artist 3&quot; });
        }
    }

    private void CreateAlbums()
    {
        if (album == null)
        {
            album = new MockDbSet&lt;Album&gt;();
            album.Add(new Album { AlbumId = 1, Title = &quot;Test Album 1&quot;, ArtistId = 1 });
            album.Add(new Album { AlbumId = 2, Title = &quot;Test Album 2&quot;, ArtistId = 2 });
            album.Add(new Album { AlbumId = 3, Title = &quot;Test Album 3&quot;, ArtistId = 3 });
            album.Add(new Album { AlbumId = 4, Title = &quot;Test Album 4&quot;, ArtistId = 3 });
        }
    }

    private void CreateTracks()
    {
        if (track == null)
        {
            track = new MockDbSet&lt;Track&gt;();
            track.Add(new Track { TrackId = 1, Name = &quot;Test Track 1&quot;, AlbumId = 1 });
            track.Add(new Track { TrackId = 2, Name = &quot;Test Track 2&quot;, AlbumId = 1 });
            track.Add(new Track { TrackId = 3, Name = &quot;Test Track 3&quot;, AlbumId = 1 });
            track.Add(new Track { TrackId = 4, Name = &quot;Test Track 4&quot;, AlbumId = 2 });
            track.Add(new Track { TrackId = 5, Name = &quot;Test Track 5&quot;, AlbumId = 2 });
            track.Add(new Track { TrackId = 6, Name = &quot;Test Track 6&quot;, AlbumId = 2 });
            track.Add(new Track { TrackId = 7, Name = &quot;Test Track 7&quot;, AlbumId = 3 });
            track.Add(new Track { TrackId = 8, Name = &quot;Test Track 8&quot;, AlbumId = 3 });
            track.Add(new Track { TrackId = 9, Name = &quot;Test Track 9&quot;, AlbumId = 4 });
            track.Add(new Track { TrackId = 10, Name = &quot;Test Track 10&quot;, AlbumId = 4 });
        }
    }
}
</pre>
<p>Now we have a context and sets mocked up we can almost write our tests but at the moment we have no way of getting the new mock context into the data provider.  This is where we can use an often overlooked assembly attribute, <a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx">InternalsVisibleTo</a>, which allows the given project access to internal members of the a project.  So all we need to do is apply the following to the AssemblyInfo.cs class of the model project.</p>
<pre class="brush: csharp; title: ; notranslate">
[assembly: InternalsVisibleTo(&quot;MusicApp.Model.Tests&quot;)]
</pre>
<p>and change the context member in the data provider (db) from private to internal and we can access it from the our test project.</p>
<p>I have two tests – one for each method in the data provider and have implemented them as follows:</p>
<pre class="brush: csharp; title: ; notranslate">
public class EFCodeFirstDataProviderTest
{
    [TestMethod()]
    public void GetArtistsTest()
    {
        EFCodeFirstDataProvider target = new EFCodeFirstDataProvider() { db = new MockContext() };

        List&lt;Artist&gt; expected = new List&lt;Artist&gt;();
        expected.Add(new Artist { ArtistId = 1, Name = &quot;Test Artist 1&quot; });
        expected.Add(new Artist { ArtistId = 2, Name = &quot;Test Artist 2&quot; });
        expected.Add(new Artist { ArtistId = 3, Name = &quot;Test Artist 3&quot; });

        List&lt;Artist&gt; actual = target.GetArtists();
        CollectionAssert.AreEquivalent(expected, actual);
    }

    [TestMethod()]
    public void SearchArtistsTest()
    {
        EFCodeFirstDataProvider target = new EFCodeFirstDataProvider() { db = new MockContext() };

        string searchTerm = &quot;Artist 1&quot;;
        List&lt;Artist&gt; expected = new List&lt;Artist&gt;();
        expected.Add(new Artist { ArtistId = 1, Name = &quot;Test Artist 1&quot; });

        List&lt;Artist&gt; actual = target.SearchArtists(searchTerm);

        CollectionAssert.AreEquivalent(expected, actual);
    }
}
</pre>
<p>As you can see they are simple tests to determine that the methods return the objects that I wanted.  As they stand these methods will fail as the CollectionAssert.AreEquivalent method checks for equality and we have no override for equality (or hash code) in our Artist class so we just need to add them in:</p>
<pre class="brush: csharp; title: ; notranslate">
public override int GetHashCode()
{
    return ArtistId;
}

public override bool Equals(object obj)
{
    return ArtistId == (obj as Artist).ArtistId;
}
</pre>
<p>and the tests will now pass.</p>
<p>In the next post I will create a simple WPF front-end to display the information and then I will build the interface from that point on.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/leomburke.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/leomburke.wordpress.com/139/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leomburke.wordpress.com&#038;blog=7579884&#038;post=139&#038;subd=leomburke&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://leomburke.wordpress.com/2011/01/25/ef-code-first-and-wpf-with-the-chinook-database-part-1c-ndash-the-unit-tests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/67f0caee10a2adc1664f26eda21facb9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">leomburke</media:title>
		</media:content>
	</item>
		<item>
		<title>EF Code First and WPF with the Chinook database. Part 1b &#8211; the provider</title>
		<link>http://leomburke.wordpress.com/2011/01/20/ef-code-first-and-wpf-with-the-chinook-database-part-1b-the-provider/</link>
		<comments>http://leomburke.wordpress.com/2011/01/20/ef-code-first-and-wpf-with-the-chinook-database-part-1b-the-provider/#comments</comments>
		<pubDate>Thu, 20 Jan 2011 14:40:25 +0000</pubDate>
		<dc:creator>Leom Burke</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">https://leomburke.wordpress.com/?p=135</guid>
		<description><![CDATA[I like to isolate my data access code to a single point so that my client does not have to worry about creating contexts or anything of the sort.  This makes it simpler to change the way the data is delivered to the client as it is abstracted away. In thinking about what methods I [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leomburke.wordpress.com&#038;blog=7579884&#038;post=135&#038;subd=leomburke&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I like to isolate my data access code to a single point so that my client does not have to worry about creating contexts or anything of the sort.  This makes it simpler to change the way the data is delivered to the client as it is abstracted away.</p>
<p>In thinking about what methods I would need for this I discovered that for the first phase I would only need two:</p>
<ul>
<li><span style="color:#555555;">GetArtists() – Returns all artists.</span></li>
<li><span style="color:#555555;">SearchArtists(string searchTerm) – Searches for artists and returns any matches.</span></li>
</ul>
<p>I don’t need any methods at the moment to fetch albums or tracks because I have virtual lazy loading properties set up to deal with them.  I will be adding more methods to this provider as the series grows (such as adding, deleting…etc).</p>
<p>Lets go ahead and test those lazy properties:</p>
<pre class="brush: csharp; title: ; notranslate">
class Program
{
    static Chinook db = new Chinook();

    static void Main(string[] args)
    {
        // Using ToList() executes the command so the datareader is closed.
        var artists = db.Artist.ToList();
        foreach (var a in artists)
        {
            Console.WriteLine(a.Name);
            PrintAlbums(a.Albums);
        }

        Console.ReadLine();
    }

    static void PrintAlbums(ICollection&lt;Album&gt; albums)
    {
        foreach (var a in albums)
        {
            Console.WriteLine(&quot;\t&quot; + a.Title);
            PrintTracks(a.Tracks);
        }
    }

    static void PrintTracks(ICollection&lt;Track&gt; tracks)
    {
        foreach (var t in tracks)
        {
            Console.WriteLine(&quot;\t\t&quot; + t.Name);
        }
    }
}
</pre>
<p><a href="http://leomburke.files.wordpress.com/2011/01/image1.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="image" src="http://leomburke.files.wordpress.com/2011/01/image_thumb1.png?w=560&#038;h=362" border="0" alt="image" width="560" height="362" /></a></p>
<p>Whoops – seems we have an invalid column name “ArtistArtistId”.</p>
<p>This is due to the way Code First decides on what the foreign key columns are called if we don’t explicitly include them – the default is “{TypeName}{TypeName}Id” which we obviously don’t have in the database.</p>
<p>We need to add the foreign key properties to our objects so EF picks up the correct names (this needs to be done for both Album and Track – note the new ArtistId and AlbumId respectively):</p>
<pre class="brush: csharp; title: ; notranslate">
public class Album
{
    public int AlbumId { get; set; }

    public string Title { get; set; }

    public int ArtistId { get; set; }

    public virtual Artist Artist { get; set; }

    public virtual ICollection&lt;Track&gt; Tracks { get; set; }
}

public class Track
{
    public int TrackId { get; set; }

    public string Name { get; set; }

    public int AlbumId { get; set; }

    public virtual Album Album { get; set; }

    public string Composer { get; set; }
}
</pre>
<p>We can now run our demo and get a correct output:</p>
<p><a href="http://leomburke.files.wordpress.com/2011/01/image2.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="image" src="http://leomburke.files.wordpress.com/2011/01/image_thumb2.png?w=521&#038;h=356" border="0" alt="image" width="521" height="356" /></a></p>
<p>We are now in a position to implement our simple data provider.</p>
<p>I am going to put the data provider behind an interface to allow for easy extension and dependency injection should we want to go that way.</p>
<pre class="brush: csharp; title: ; notranslate">
public interface IDataProvider
{
    List&lt;Artist&gt; GetArtists();

    List&lt;Artist&gt; SearchArtists(string searchTerm);
}
</pre>
<p>This is then implemented as follows for the code first model:</p>
<pre class="brush: csharp; title: ; notranslate">
public class EFCodeFirstDataProvider : IDataProvider
{
    private Chinook db = new Chinook();

    public List&lt;Artist&gt; GetArtists()
    {
        return this.db.Artist.ToList();
    }

    public List&lt;Artist&gt; SearchArtists(string searchTerm)
    {
        return this.db.Artist.Where(a =&gt; a.Name.Contains(searchTerm)).ToList();
    }
}
</pre>
<p>We have a private instance of the Chinook data context that controls all of the fetching of data.  When the Artist requests its albums then this context is used.  This is the same with the tracks.</p>
<p>The intention here is to allow the client to call simple methods to interact with the data and we are able to swap out for another provider if we so wish easily.</p>
<p>The only thing we now need to change is the little test app so that it uses the new data provider (we will hard code the type here but will be using dependency injection in our WPF app).</p>
<pre class="brush: csharp; title: ; notranslate">
static IDataProvider dp = new EFCodeFirstDataProvider();

static void Main(string[] args)
{
    var artists = dp.GetArtists();
    foreach (var a in artists)
    {
        Console.WriteLine(a.Name);
        PrintAlbums(a.Albums);
    }

    Console.ReadLine();
}
</pre>
<p>And that’s all there is to it – we now have a separate data provider to work with our entity framework objects.</p>
<p>The next part of this series (1c) is going to involve writing unit tests for the data provider.  This is easier said than done and involves much mocking of the EF classes.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/leomburke.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/leomburke.wordpress.com/135/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leomburke.wordpress.com&#038;blog=7579884&#038;post=135&#038;subd=leomburke&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://leomburke.wordpress.com/2011/01/20/ef-code-first-and-wpf-with-the-chinook-database-part-1b-the-provider/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/67f0caee10a2adc1664f26eda21facb9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">leomburke</media:title>
		</media:content>

		<media:content url="http://leomburke.files.wordpress.com/2011/01/image_thumb1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://leomburke.files.wordpress.com/2011/01/image_thumb2.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>EF Code First and WPF with the Chinook database. Part 1 &#8211; the model</title>
		<link>http://leomburke.wordpress.com/2011/01/13/ef-code-first-and-wpf-with-the-chinook-database-part-1-the-model/</link>
		<comments>http://leomburke.wordpress.com/2011/01/13/ef-code-first-and-wpf-with-the-chinook-database-part-1-the-model/#comments</comments>
		<pubDate>Thu, 13 Jan 2011 14:26:30 +0000</pubDate>
		<dc:creator>Leom Burke</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">https://leomburke.wordpress.com/?p=119</guid>
		<description><![CDATA[Introduction I am going to start a series of posts building a simple app using the Chinook database as a back-end and putting a WPF client on the front-end.  I am going to keep it loose as I don’t want to commit to blog posts that I may not get chance to complete so I [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leomburke.wordpress.com&#038;blog=7579884&#038;post=119&#038;subd=leomburke&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><span style="color:#666666;"><strong>Introduction</strong></span></p>
<p><span style="color:#666666;">I am going to start a series of posts building a simple app using the <a href="http://chinookdatabase.codeplex.com/">Chinook</a> database as a back-end and putting a WPF client on the front-end.  I am going to keep it loose as I don’t want to commit to blog posts that I may not get chance to complete so I will keep every post self-contained covering 1 detail of the implementation. </span></p>
<p><span style="color:#666666;">The technologies and tools I plan on using for this series are as follows:</span></p>
<ul>
<li><span style="color:#666666;"><a href="http://blogs.msdn.com/b/adonet/archive/2010/12/14/ef-feature-ctp5-released.aspx">Entity Framework Code First CTP5.</a></span></li>
<li><span style="color:#666666;">WPF 4. </span></li>
<li><span style="color:#666666;"><a href="http://mvvmlight.codeplex.com/">MVVM Light</a>. </span></li>
<li><span style="color:#666666;"><a href="http://nuget.codeplex.com/">NuGet</a>. </span></li>
</ul>
<p><span style="color:#666666;">As you can see the idea is to use the latest technologies available to build a simple app to display the music details from the Chinook database.  As I am not committing to a large series I will say that my intentions for the series include:</span></p>
<ul>
<li><span style="color:#666666;">Setting up the model using EF4 Code First (this post).</span></li>
<li><span style="color:#666666;">creating a basic screen listing the artists and associated albums.</span></li>
<li><span style="color:#666666;">Creating an album details adorner to show the tracks of individual albums.</span></li>
</ul>
<p><span style="color:#666666;">Possible future posts will include:</span></p>
<ul>
<li><span style="color:#666666;">Adding the ability for customers to place an order (creating invoices).</span></li>
<li><span style="color:#666666;">Adding employees to manage the customer invoices (this is a WPF app so the employee will be doing all of the work as this is not a customer facing app).</span></li>
<li><span style="color:#666666;">Adding the ability to create custom playlists that can reviewed.</span></li>
</ul>
<p><span style="color:#666666;">Note that all of these items already exist in the Chinook database and I will be focusing on the data access and UI layers.</span></p>
<p><span style="color:#666666;"> </span></p>
<p><span style="color:#666666;"><strong>Building the model using EF Code First</strong></span></p>
<p><span style="color:#666666;">The first thing we need to do is create a new solution for our app.  Being as we are creating the model first I am going to create a class library.</span></p>
<p><span style="color:#666666;">Once the solution and project are in place we need to get the Code First bits into the project.  I am going to use NuGet so you need to have this installed.</span></p>
<p><span style="color:#666666;">In the NuGet package manager window we can find the required package by firing the command:</span></p>
<p><span style="color:#666666;"><em>Get-Package –remote –filter CodeFirst</em></span></p>
<p><span style="color:#666666;">This will give us the following output:</span></p>
<p><a href="http://leomburke.files.wordpress.com/2011/01/image.png"><span style="color:#666666;"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="image" src="http://leomburke.files.wordpress.com/2011/01/image_thumb.png?w=575&#038;h=213" border="0" alt="image" width="575" height="213" /></span></a></p>
<p><span style="color:#666666;">This shows us the package that we need to install is EFCodeFirst so we issue</span></p>
<p><span style="color:#666666;"><em>Install-Package EFCodeFirst</em></span></p>
<p><span style="color:#666666;">this should add the EntityFramework reference to your project but it didn’t do that on my class library so I had to add the reference manually ({SolutionFolder}\packages\EFCodeFirst.0.8\lib\EntityFramework.dll).</span></p>
<p><span style="color:#666666;">Now we have the reference we can start to create our POCO objects.  I am going to create a model that initially uses the Artist, Album and Track tables as they are going to be used in the first part of this app – I will add more as I go along.</span></p>
<p><span style="color:#666666;">EF Code First allows us to create standard POCOs to represent our model so for my initial model I have:</span></p>
<p><span style="color:#666666;">
<pre class="brush: csharp; title: ; notranslate">
public class Artist
{
    public int ArtistId { get; set; }
    public string Name { get; set; }
    public virtual ICollection&lt;Album&gt; Albums { get; set; }
}

public class Album
{
    public int AlbumId { get; set; }
    public string Title { get; set; }
    public virtual Artist Artist { get; set; }
    public virtual ICollection&lt;Track&gt; Tracks { get; set; }
}

public class Track
{
    public int TrackId { get; set; }
    public string Name { get; set; }
    public virtual Album Album { get; set; }
    public string Composer { get; set; }
}
</pre>
<p> </span></p>
<p><span style="color:#666666;">Note the virtual association properties – this is to allow these properties to be lazy-loaded.</span></p>
<p><span style="color:#666666;">The next thing we need is the actual dbContext which is defined as follows:</span></p>
<p><span style="color:#666666;">
<pre class="brush: csharp; title: ; notranslate">
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions.Edm.Db;
.
.
.
public class Chinook : DbContext
{
    protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove&lt;PluralizingTableNameConvention&gt;();
    }

    public DbSet&lt;Artist&gt; Artist { get; set; }
    public DbSet&lt;Album&gt; Album { get; set; }
    public DbSet&lt;Track&gt; Track { get; set; }
}
</pre>
<p></span></p>
<p><span style="color:#808080;">This is a class that includes one property per table in the database and handles the mapping to our objects.  This is using default conventions with the exception of the one removed in the overridden OnModelCreating method.  This says that the database we have doesn’t have pluralised names as Code First expects and instead the names match the entities.</span></p>
<p><span style="color:#666666;">Next we need to add an app.config file to the project and add the ConnectionString for the database.  I use SQLServer so adjust accordingly.</span></p>
<p><span style="color:#666666;">
<pre class="brush: xml; title: ; notranslate">
&lt;connectionStrings&gt;
    &lt;add name=&quot;Chinook&quot; providerName=&quot;System.Data.SqlClient&quot;
        connectionString=&quot;Data Source=.;Initial Catalog=chinook;Integrated Security=true&quot; /&gt;
&lt;/connectionStrings&gt;
</pre>
<p></span></p>
<p><span style="color:#666666;">Notice that the name of the connectionString must be the same as the class name when using the default conventions.</span></p>
<p><span style="color:#666666;"><strong>Testing that it works</strong></span></p>
<p><span style="color:#666666;">OK, we have the model built now and can run a crude test to see if it works.  Add a console app to your solution and set it as the startup project.  Add references to the Model assembly and the Code First assembly and move the app.config to the new project. Now add the following code to the main method.</span></p>
<p><span style="color:#666666;">
<pre class="brush: csharp; title: ; notranslate">
static void Main(string[] args)
{
    using (Chinook db = new Chinook())
    {
        foreach (var artist in db.Artist)
        {
            Console.WriteLine(artist.Name);
        }

        Console.ReadLine();
    }
}
</pre>
<p></span></p>
<p><span style="color:#666666;">This will loop through all of the artists and print their name to the screen.</span></p>
<p><span style="color:#666666;">That’s all there is to creating a simple model with Entity Framework Code First CTP5.  In the next instalment I plan on writing a simple data provider class that will abstract the actual DbContext calls away from the user and allow the user to simply call methods like provider.GetArtists().</span></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/leomburke.wordpress.com/119/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/leomburke.wordpress.com/119/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leomburke.wordpress.com&#038;blog=7579884&#038;post=119&#038;subd=leomburke&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://leomburke.wordpress.com/2011/01/13/ef-code-first-and-wpf-with-the-chinook-database-part-1-the-model/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/67f0caee10a2adc1664f26eda21facb9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">leomburke</media:title>
		</media:content>

		<media:content url="http://leomburke.files.wordpress.com/2011/01/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>WPF/Silverlight ListBox and equality checking</title>
		<link>http://leomburke.wordpress.com/2010/12/16/wpf-listbox-and-equality-checking/</link>
		<comments>http://leomburke.wordpress.com/2010/12/16/wpf-listbox-and-equality-checking/#comments</comments>
		<pubDate>Thu, 16 Dec 2010 11:03:39 +0000</pubDate>
		<dc:creator>Leom Burke</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">https://leomburke.wordpress.com/?p=108</guid>
		<description><![CDATA[In WPF we bind collections of objects to ListBoxes and the like all the time – its part and parcel of the WPF development cycle but this is something that stung me recently. I bound a collection of objects to the ItemsSource property as usual but the selection was odd.  Every time I selected an [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leomburke.wordpress.com&#038;blog=7579884&#038;post=108&#038;subd=leomburke&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In WPF we bind collections of objects to ListBoxes and the like all the time – its part and parcel of the WPF development cycle but this is something that stung me recently.</p>
<p>I bound a collection of objects to the ItemsSource property as usual but the selection was odd.  Every time I selected an item the ListBox assumed that the first item was also selected and subsequent selections marked all previous selections as selected, also the SelectedIndex was always 0.  It took some time but I tracked it down to the way that ListBoxes use equality.</p>
<p>Something I didn’t know was that the objects that I was using had an overridden Equals method which was simply comparing a single string on the objects to determine if they were equal.  Because I only wanted a small subset of of the object I only populated those properties I needed along with the id of the object and not the string being compared.</p>
<p>The below shows an example of what I was doing.</p>
<pre class="brush: csharp; title: ; notranslate">
public class MainViewModel : INotifyPropertyChanged
{
    private ObservableCollection foos;

    public ObservableCollection Foos
    {
        get
        {
            return foos;
        }
        set
        {
            foos = value;
        }
    }

    public MainViewModel()
    {
        this.Foos = new ObservableCollection();
        this.Foos.Add(new Foo { id = 1, Display = &quot;First&quot; });
        this.Foos.Add(new Foo { id = 2, Display = &quot;Second&quot; });
        this.Foos.Add(new Foo { id = 3, Display = &quot;Third&quot; });
        this.Foos.Add(new Foo { id = 4, Display = &quot;Fourth&quot; });
        this.Foos.Add(new Foo { id = 5, Display = &quot;Fifth&quot; });
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

public class Foo
{
    public int id { get; set; }

    public string Display { get; set; }

    public string FooCode { get; set; }

    public override bool Equals(object obj)
    {
        return FooCode == (obj as Foo).FooCode;
    }
}
</pre>
<p>As we can see I have no interest in the FooCode property and as a result don’t use it in my ViewModel.</p>
<p>The problem with this is that now the ListBox has no way of knowing if the objects are different as we have an overriding Equals method that implements value equality rather than reference equality and because the value is always going to be the same (as I don’t set it) then the ListBox will assume that every object is essentially the same object.</p>
<p>A simple change to include the FooCode property in each object in the collection solves this problem and gives us different values for equality testing.</p>
<p>A sample project with 2 lists displaying this different behaviour can be found <a href="http://bit.ly/eNVw5D">here</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/leomburke.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/leomburke.wordpress.com/108/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leomburke.wordpress.com&#038;blog=7579884&#038;post=108&#038;subd=leomburke&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://leomburke.wordpress.com/2010/12/16/wpf-listbox-and-equality-checking/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/67f0caee10a2adc1664f26eda21facb9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">leomburke</media:title>
		</media:content>
	</item>
		<item>
		<title>Skinning in WPF</title>
		<link>http://leomburke.wordpress.com/2010/12/07/wpf-skinning/</link>
		<comments>http://leomburke.wordpress.com/2010/12/07/wpf-skinning/#comments</comments>
		<pubDate>Tue, 07 Dec 2010 12:24:58 +0000</pubDate>
		<dc:creator>Leom Burke</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Skins]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">https://leomburke.wordpress.com/?p=79</guid>
		<description><![CDATA[I like writing XAML.  It gives me a sense of completion when I write a style of template by hand and it just works, I like using blend as well but raw is more fun . Lets say we have a requirement to change the front-end of a product for different brandings and “products” (that [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leomburke.wordpress.com&#038;blog=7579884&#038;post=79&#038;subd=leomburke&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I like writing XAML.  It gives me a sense of completion when I write a style of template by hand and it just works, I like using blend as well but raw is more fun <img class="wlEmoticon wlEmoticon-smile" style="border-style:none;" src="http://leomburke.files.wordpress.com/2010/12/wlemoticon-smile.png?w=630" alt="Smile" />.</p>
<p>Lets say we have a requirement to change the front-end of a product for different brandings and “products” (that is, the same product with a different ‘skin’).  One of the challenges we have is that we don’t want to write new user controls every time the client screen needs to change (especially for something simple such as switching to a different style for certain builds).  What follows is a way of using the power of WPF resources to skin an application with little work.</p>
<p>we start off with 2 ListBoxes on a window, for the purposes of this article the list boxes are simple with a list of colours, as follows (they are both the same).</p>
<pre class="brush: xml; title: ; notranslate">
&lt;ListBox Grid.Column=&quot;0&quot; Margin=&quot;5&quot;&gt; 
    &lt;ListBoxItem&gt;Red&lt;/ListBoxItem&gt; 
    &lt;ListBoxItem&gt;Yellow&lt;/ListBoxItem&gt; 
    &lt;ListBoxItem&gt;Pink&lt;/ListBoxItem&gt; 
    &lt;ListBoxItem&gt;Green&lt;/ListBoxItem&gt; 
    &lt;ListBoxItem&gt;Orange&lt;/ListBoxItem&gt; 
    &lt;ListBoxItem&gt;Purple&lt;/ListBoxItem&gt; 
    &lt;ListBoxItem&gt;Blue&lt;/ListBoxItem&gt; 
&lt;/ListBox&gt; 
</pre>
<p>Now, this will just display 2 boring list so lets add a nice style in the app.xaml file for the left hand list as follows:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;Style x:Key=&quot;RoundedList&quot; TargetType=&quot;{x:Type ListBoxItem}&quot;&gt;
    &lt;Setter Property=&quot;Width&quot; Value=&quot;150&quot; /&gt;
    &lt;Setter Property=&quot;Margin&quot; Value=&quot;5,2&quot; /&gt;
    &lt;Setter Property=&quot;Padding&quot; Value=&quot;2&quot; /&gt;
    &lt;Setter Property=&quot;Template&quot;&gt;
        &lt;Setter.Value&gt;
            &lt;ControlTemplate TargetType=&quot;{x:Type ListBoxItem}&quot;&gt;
                &lt;Border x:Name=&quot;border&quot; BorderThickness=&quot;1&quot; BorderBrush=&quot;Silver&quot; Background=&quot;AliceBlue&quot; CornerRadius=&quot;5&quot;&gt;
                    &lt;ContentPresenter x:Name=&quot;Content&quot; Margin=&quot;0&quot; HorizontalAlignment=&quot;Center&quot; TextBlock.Foreground=&quot;Black&quot; VerticalAlignment=&quot;Stretch&quot; /&gt;
                &lt;/Border&gt;
                &lt;ControlTemplate.Triggers&gt;
                    &lt;Trigger Property=&quot;Selector.IsSelected&quot; Value=&quot;True&quot;&gt;
                        &lt;Setter TargetName=&quot;border&quot; Property=&quot;Background&quot; Value=&quot;Silver&quot; /&gt;
                    &lt;/Trigger&gt;
                &lt;/ControlTemplate.Triggers&gt;
            &lt;/ControlTemplate&gt;
        &lt;/Setter.Value&gt;
    &lt;/Setter&gt;
&lt;/Style&gt;
</pre>
<p>Adding the ItemContainerStyle (<em>{StaticResource RoundedList}</em>) to the list box will now give us something like the following:</p>
<p><a href="http://leomburke.files.wordpress.com/2010/12/image.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="image" src="http://leomburke.files.wordpress.com/2010/12/image_thumb.png?w=1028&#038;h=300" border="0" alt="image" width="1028" height="300" /></a></p>
<p>As we can see we now have a nice styled list on the left which will change colour when we click on each item.  To demonstrate the skinning I am going to apply the same style to the right hand list but with a different name (so we now have 2 styles in the app.xaml file – RoundedList and RoundedList_skin).</p>
<p>So, for certain builds of this app we want the list buttons to shrink slightly when we click them but we only want it to do that for certain configurations.  We can add a new WPF resource dictionary to our project (Skin.xaml) and add the new style to it – it is important that the new style retains the name of the one it is replacing as we shall see shortly.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;Style x:Key=&quot;RoundedList_skin&quot; TargetType=&quot;{x:Type ListBoxItem}&quot;&gt;
    &lt;Setter Property=&quot;Width&quot; Value=&quot;150&quot; /&gt;
    &lt;Setter Property=&quot;Margin&quot; Value=&quot;5,2&quot; /&gt;
    &lt;Setter Property=&quot;Padding&quot; Value=&quot;2&quot; /&gt;
    &lt;Setter Property=&quot;Template&quot;&gt;
        &lt;Setter.Value&gt;
            &lt;ControlTemplate TargetType=&quot;{x:Type ListBoxItem}&quot;&gt;
                &lt;Border x:Name=&quot;border&quot; BorderThickness=&quot;1&quot; BorderBrush=&quot;Silver&quot; Background=&quot;AliceBlue&quot; CornerRadius=&quot;5&quot;&gt;
                    &lt;ContentPresenter x:Name=&quot;Content&quot; Margin=&quot;0&quot; HorizontalAlignment=&quot;Center&quot; VerticalAlignment=&quot;Stretch&quot; /&gt;
                &lt;/Border&gt;
                &lt;ControlTemplate.Triggers&gt;
                    &lt;Trigger Property=&quot;Selector.IsSelected&quot; Value=&quot;True&quot;&gt;
                        &lt;Setter Property=&quot;RenderTransform&quot;&gt;
                            &lt;Setter.Value&gt;
                                &lt;ScaleTransform ScaleX=&quot;0.85&quot; ScaleY=&quot;0.85&quot;/&gt;
                            &lt;/Setter.Value&gt;
                        &lt;/Setter&gt; 
                        &lt;Setter Property=&quot;RenderTransformOrigin&quot; Value=&quot;0.5, 0.5&quot;/&gt;
                    &lt;/Trigger&gt;
                &lt;/ControlTemplate.Triggers&gt;
            &lt;/ControlTemplate&gt;
       &lt;/Setter.Value&gt;
    &lt;/Setter&gt;
&lt;/Style&gt;
</pre>
<p>The transform in this style simply makes the item look as though it had been pressed.</p>
<p>And now for the actual trick of making the new skin available to the app thus replacing the defaults in App.xaml.  I need a new Application configuration file (App.config) with an appSetting (<em>skins</em>) to hold the required skins for this application build.  This is a comma-separated list of resource dictionaries that we are going to include in this build.  In order to allow the new skins to override the existing ones we are required to move the current resources that we have defined into a dictionary of their own (this is due to the scoping rules of merged dictionaries in WPF – the primary dictionary will always take precedence).  I am simply going to move them into a new dictionary called OriginalSkin.xaml and include this in my skins appSetting which now looks like this.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;add key=&quot;skins&quot; value=&quot;OriginalSkin.xaml,Skin.xaml&quot;/&gt;
</pre>
<p>We now have the two dictionaries ready to be loaded.  In App.xaml.cs we need a new method to load the skins from the config and this should be called from the OnStartup method of the app (its virtual so is available right there in app.xaml.cs to be overridden).</p>
<pre class="brush: csharp; title: ; notranslate">
private void LoadSkins()
{
    string skins = ConfigurationManager.AppSettings[&quot;skins&quot;];
    if (string.IsNullOrEmpty(skins))
    {
        return;
    }

    string[] resources = skins.Split(new string[] { &quot;,&quot; }, StringSplitOptions.RemoveEmptyEntries);
    foreach (string resource in resources)
    {
        ResourceDictionary dictionary = new ResourceDictionary();
        dictionary.Source = new Uri(resource, UriKind.Relative);
        this.Resources.MergedDictionaries.Add(dictionary);
    }
}
</pre>
<p>This code loops through the skins in the appSetting and adds them as merged dictionaries.  The beauty of this is that merged dictionaries are read in the order that they are added so the latter dictionaries will override the earlier ones resulting in our newly minted RoundedList_skin being called instead of the original one but the original version of RoundedList is still available for the other ListBox:</p>
<p><a href="http://leomburke.files.wordpress.com/2010/12/image1.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;" title="image" src="http://leomburke.files.wordpress.com/2010/12/image_thumb1.png?w=1028&#038;h=300" border="0" alt="image" width="1028" height="300" /></a></p>
<p>We can now add any number of skins to this configuration but we will only load the ones listed in the App.config file – this now makes the app very extensible and can be changed at the drop of a hat.</p>
<p>The sample application that I used for this post can be found <a href="http://bit.ly/h6yPmT">here</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/leomburke.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/leomburke.wordpress.com/79/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leomburke.wordpress.com&#038;blog=7579884&#038;post=79&#038;subd=leomburke&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://leomburke.wordpress.com/2010/12/07/wpf-skinning/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/67f0caee10a2adc1664f26eda21facb9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">leomburke</media:title>
		</media:content>

		<media:content url="http://leomburke.files.wordpress.com/2010/12/wlemoticon-smile.png" medium="image">
			<media:title type="html">Smile</media:title>
		</media:content>

		<media:content url="http://leomburke.files.wordpress.com/2010/12/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://leomburke.files.wordpress.com/2010/12/image_thumb1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>MVVM &#8211; The &#8216;Other&#8217; ViewModel</title>
		<link>http://leomburke.wordpress.com/2010/12/01/mvvmthe-other-viewmodel/</link>
		<comments>http://leomburke.wordpress.com/2010/12/01/mvvmthe-other-viewmodel/#comments</comments>
		<pubDate>Wed, 01 Dec 2010 11:29:07 +0000</pubDate>
		<dc:creator>Leom Burke</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">https://leomburke.wordpress.com/?p=67</guid>
		<description><![CDATA[Something that we regularly do at work is add additional properties to business objects that are only for use on the client (isDirty, HasChanged …etc).  We have always just added these to the business object directly and thought nothing of it, but after listening to a Hanselminutes interview with Laurent Bugnion I discovered the ‘other’ [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leomburke.wordpress.com&#038;blog=7579884&#038;post=67&#038;subd=leomburke&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Something that we regularly do at work is add additional properties to business objects that are only for use on the client (isDirty, HasChanged …etc).  We have always just added these to the business object directly and thought nothing of it, but after listening to a <a href="http://www.hanselminutes.com/default.aspx?showID=260">Hanselminutes interview</a> with <a href="http://blog.galasoft.ch/Default.aspx">Laurent Bugnion</a> I discovered the ‘other’ use for a ViewModel – wrapping client side business objects to expose new properties.  This is also useful in removing the overhead of viewing objects via a converter.</p>
<p>I have recently started looking at ASP.NET MVC as well and the way to pass things between controller and view is by using a ViewModel class.  This overload of the term had not translated into being useable in MVVM as well so what follows is a short, simple example of using a ViewModel to better model some data to fit a view.</p>
<p>Lets say we have a meeting object that we have extracted from a service and it is now ready to display on our client.  This business object has no real relation to them ORM version of the same object if we are correctly differentiating between them and client facing business objects so it has no in-built tracking to determine if it has changed and we don&#8217;t want to send it back to the service for updating if nothing has changed.  Our class looks like this.</p>
<pre class="brush: csharp; title: ; notranslate">
public class Meeting
{
    public Meeting()
    {

    }
    public string Subject { get; set; }
    public string Location { get; set; }
    public DateTime StartTime { get; set; }
    public List&lt;Person&gt; Attendees { get; set; }
}
</pre>
<p>This is a very simple class to define our meeting but it has no way of knowing if it has changed and also the StartTime property is stored on the server as UTC but the client could be anywhere.</p>
<p>&nbsp;</p>
<p>Taking the latter problem first you may be tempted to bind directly to the StartTime property of this object and use a converter to convert to the appropriate time zone based on the user culture (as I have done many times).  As for the problem with a meeting change, there has to be some way of telling an object that it has changed.  Both of these problems can be solved with a MeetingViewModel.  This is a VM that follows the <a href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a> and could be implemented as follows:</p>
<pre class="brush: csharp; title: ; notranslate">
public class MeetingViewModel
    {
        private Meeting inner;
        public MeetingViewModel(Meeting m)
        {
            inner = m;
        }

        public Meeting Inner
        {
            get
            {
                return inner;
            }
        }

        public string Location
        {
            get
            {
                return inner.Location;
            }
            set
            {
                inner.Location = value;
            }
        }
        public DateTime StartTime
        {
            get
            {
                return inner.StartTime;
            }
            set
            {
                inner.StartTime = value;
            }
        }
        public List&lt;Person&gt; Attendees
        {
            get
            {
                return inner.Attendees;
            }
            set
            {
                inner.Attendees = value;
            }
        }

        public DateTime LocalStartTime
        {
            get
            {
                return inner.StartTime.ToLocalTime();
            }
            set
            {
                inner.StartTime = value.ToUniversalTime();
            }
        }

        public bool IsDirty { get; set; }
    }
</pre>
<p>Here we now have a nice property that sorts out the StartTime into a local time for us and a property that determines if this object has changed.  In your VM that controls your view you now operate on an object of type MeetingViewModel and all bindings are to this object.  When it comes time to save the object you simply need to check if you have set the dirty flag and if so extract the internal Meeting object using the get-only property and send it back to the service.</p>
<p>&nbsp;</p>
<p>This is also a nice way of working with business objects that you have no control over such as from an external web service or third party library.  Once you start to understand the power of this approach over simply using converters you will find yourself writing VM’s for all of your business objects that you need to modify slightly on the client side when you need properties like the above or other bits of information like calculated properties.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/leomburke.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/leomburke.wordpress.com/67/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leomburke.wordpress.com&#038;blog=7579884&#038;post=67&#038;subd=leomburke&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://leomburke.wordpress.com/2010/12/01/mvvmthe-other-viewmodel/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/67f0caee10a2adc1664f26eda21facb9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">leomburke</media:title>
		</media:content>
	</item>
		<item>
		<title>Using JustMock and Dependency Injection to mock data providers</title>
		<link>http://leomburke.wordpress.com/2010/11/15/using-justmock-and-dependency-injection-to-mock-data-providers/</link>
		<comments>http://leomburke.wordpress.com/2010/11/15/using-justmock-and-dependency-injection-to-mock-data-providers/#comments</comments>
		<pubDate>Mon, 15 Nov 2010 13:56:41 +0000</pubDate>
		<dc:creator>Leom Burke</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Mocking]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">https://leomburke.wordpress.com/2010/11/15/using-justmock-and-dependency-injection-to-mock-data-providers/</guid>
		<description><![CDATA[Justmock is an excellent, fairly new, mocking framework from Telerik that I had the pleasure of getting a free licence for at the launch event.  The company I work for has now picked this up and is intending on rolling it out across the development department and I don’t think it can happen soon enough.  [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leomburke.wordpress.com&#038;blog=7579884&#038;post=20&#038;subd=leomburke&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://www.telerik.com/products/mocking.aspx">Justmock</a> is an excellent, fairly new, mocking framework from Telerik that I had the pleasure of getting a free licence for at the launch event.  The company I work for has now picked this up and is intending on rolling it out across the development department and I don’t think it can happen soon enough.  This is a conversation I have just had (edited and redacted for this blog) with a colleague about using it to mock up the fetching of data.</p>
<p>The current set up was similar to this much more contrived example but it serves to demonstrate the changes we made.</p>
<p>We had a class that depended on the data provider to access the database and return actual values to verify a method was working.  For this example I am using simple number checking but the actual problem was much larger.  The data provider fetches a list of numbers based on an initial value and then the checker returns the maximum value in the results set.  The data provider interface and checker are below.</p>
<pre class="brush: csharp; title: ; notranslate">
public interface IDataProvider
{
    List GetNumbers(int start);
}

public class DataProvider : IDataProvider
{
    public List GetNumbers(int start)
    {
        var list = new List();
        // Use EF to access db and return list based on parameter
        // return a new list for this example
        return list;
    }
}

public class NumberChecker
{
    public int Getmax()
    {
        IDataProvider dp = new DataProvider();
        return dp.GetNumbers(5).Max();
    }

    public List GetNumbers()
    {
        IDataProvider dp = new DataProvider();
        return dp.GetNumbers(5);
    }
}
</pre>
<p>This is very simple code and the associated test went something like this.</p>
<pre class="brush: csharp; title: ; notranslate">
[TestMethod()]
public void CheckCheckGeneratorReturnsMaximumValue()
{
    NumberChecker checker = new NumberChecker();
    int expected = checker.GetNumbers().Max();
    int actual = checker.Getmax();
    Assert.AreEqual(expected, actual);
}
</pre>
<p>This test passes but its not very nice.  It calls the generator methods twice and then continues to touch the database in order to get the data.</p>
<p>We really wanted to use JustMock so we broke it out and installed it on his machine.</p>
<p>To refactor this code into something testable we first had to remove that dependency on the data provider. The fact that it has an interface makes this much easier as we can simply inject an implementer of this interface into the method and act on that.  So without changing the implementation of the data provider and the interface the NumberChecker class became the following.</p>
<p><span style="font-family:Consolas, Monaco, 'Courier New', Courier, monospace;line-height:18px;font-size:12px;white-space:pre;"> </span></p>
<pre class="brush: csharp; title: ; notranslate">
public class NumberChecker
{
    public int Getmax(IDataProvider dp)
    {
        return dp.GetNumbers(5).Max();
    }

    public List GetNumbers(IDataProvider dp)
    {
        return dp.GetNumbers(5);
    }
}
</pre>
<p>Here we have moved the data provider up to a parameter and are now able to inject any implementer we choose into this method.</p>
<p>This now allows us to test these methods without accessing the data or the real data provider (as we are not testing that here).</p>
<p>JustMock has a method that allows you to return any value when calling a method on a mocked object (Returns).  Using this we can mock up our data provider to do something that we want it to do rather than access the database.  This then allows us to return a custom value so the test now becomes:</p>
<pre class="brush: csharp; title: ; notranslate">
[TestMethod()]
public void CheckCheckGeneratorReturnsMaximumValue()
{
    // ARRANGE
    // Create a new list of integers to use as the returns value
    var ints = new List { 1, 2, 3, 4, 5 };

    // Create the data provider object and set it up so that GetNumbers method
    // always returns the list we created above.
    var provider = Mock.Create();
    Mock.Arrange(() =&gt; provider.GetNumbers(Arg.IsAny&lt;int&gt;())).Returns(ints);

    // ACT
    // Run the NumberChecker method passing in our mocked data provider
    NumberChecker checker = new NumberChecker();
    int actual = checker.Getmax(provider);

    // ASSERT
    int expected = 5;
    Assert.AreEqual(expected, actual);
}
</pre>
<p>As we can now see passing in the data provider instance from here makes the test much easier to understand.  We have created a new list of integers and are simply returning this from the method on the data provider that we pass in to our NumberChecker.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/leomburke.wordpress.com/20/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/leomburke.wordpress.com/20/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leomburke.wordpress.com&#038;blog=7579884&#038;post=20&#038;subd=leomburke&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://leomburke.wordpress.com/2010/11/15/using-justmock-and-dependency-injection-to-mock-data-providers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/67f0caee10a2adc1664f26eda21facb9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">leomburke</media:title>
		</media:content>
	</item>
		<item>
		<title>Binding and styling text to a RichTextBox in WPF</title>
		<link>http://leomburke.wordpress.com/2010/04/09/binding-and-styling-text-to-a-richtextbox-in-wpf/</link>
		<comments>http://leomburke.wordpress.com/2010/04/09/binding-and-styling-text-to-a-richtextbox-in-wpf/#comments</comments>
		<pubDate>Fri, 09 Apr 2010 16:03:39 +0000</pubDate>
		<dc:creator>Leom Burke</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://leomburke.wordpress.com/2010/04/09/binding-and-styling-text-to-a-richtextbox-in-wpf/</guid>
		<description><![CDATA[The RichTextBox in WPF is a great tool for dealing with text that needs to be styled (such as syntax highlighting) but its not so great when it comes to allowing us to bind and edit text on the fly. I got a feature request from our product manager to change the colour of certain [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leomburke.wordpress.com&#038;blog=7579884&#038;post=8&#038;subd=leomburke&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>The RichTextBox in WPF is a great tool for dealing with text that needs to be styled (such as syntax highlighting) but its not so great when it comes to allowing us to bind and edit text on the fly.</p>
<p>I got a feature request from our product manager to change the colour of certain text within a TextBox to match a legacy application.  It turns out it is not as straight forward as you might expect.</p>
<p>We have text in an SQL database like this:</p>
<blockquote><p>this is a title:.\r\n\r\nThis is a normal line\r\n\r\nthis is another title:.\r\n</p></blockquote>
<p>You can see that the titles end with “:.” so all we need to do is pull out these lines and make them (in my case) blue.</p>
<p>The problem is that this text is on an object that my previous TextBox was able to bind its Text property to with ease, but the RichTextBox has no text property as it displays a flow document. OK, I thought, I will just bind the text to the document as follows:</p>
<blockquote><p>&lt;RichTextBox IsReadOnly=&#8221;True&#8221; Document=&#8221;{Binding ElementName=ViewType, Path=SelectedItem.Tag /&gt;</p></blockquote>
<p>This doesn’t work because the Document property is not a Dependency Property and therefore can not be bound to.  So BindableRichTextBox here I come.  I created a very simple control so that I could bind to the Document property.  In doing this I discovered that the Document property expects a FlowDocument as its content so I had to convert my text string to a flow document with the relevant parts highlighted.  I used a converter to spit out the FlowDocument with the correctly formatted text on a per line basis</p>
<pre class="brush: csharp; title: ; notranslate">

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    FlowDocument doc = new FlowDocument();

    string s = value as string;
    if (s != null)
    {
        using (StringReader reader = new StringReader(s))
        {
            string newLine;
            while ((newLine = reader.ReadLine()) != null)
            {
                Paragraph paragraph = null;
                if (newLine.EndsWith(&quot;:.&quot;))
                {
                    paragraph = new Paragraph(new Run(newLine.Replace(&quot;:.&quot;, string.Empty)));
                    paragraph.Foreground = new SolidColorBrush(Colors.Blue);
                    paragraph.FontWeight = FontWeights.Bold;
                }
                else
                {
                    paragraph = new Paragraph(new Run(newLine));
                }

                doc.Blocks.Add(paragraph);
            }
        }
    }

    return doc;
}

</pre>
<p>This simply takes the string and reads it line by line.  If we have the desired characters at the end of a line (“:.”) then we make the line blue and bold and remove the characters, otherwise we just add the text.  Each line is added as a paragraph so to reduce the space between each one I added the following to the control declaration in the XAML</p>
<blockquote><p>&lt;RichTextBox.Resources&gt;</p>
<p>&lt;Style TargetType=&#8221;{x:Type Paragraph}&#8221;&gt;</p>
<p>&lt;Setter Property=&#8221;Margin&#8221; Value=&#8221;0&#8243;/&gt;</p>
<p>&lt;/Style&gt;</p>
<p>&lt;/RichTextBox.Resources&gt;</p></blockquote>
<p>This simply removes the the margin from each paragraph.</p>
<p>The final part of the puzzle is the control that allows binding this is a simple case of adding a dependency property onto a new control that inherits from RichTextBox</p>
<pre class="brush: csharp; title: ; notranslate">
public class BindableRichTextBox : RichTextBox
{
    public static readonly DependencyProperty DocumentProperty = DependencyProperty.Register(&quot;Document&quot;, typeof(FlowDocument), typeof(BindableRichTextBox), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(OnDocumentChanged)));

    public new FlowDocument Document
    {
        get
        {
            return (FlowDocument)this.GetValue(DocumentProperty);
        }

        set
        {
            this.SetValue(DocumentProperty, value);
        }
    }

    public static void OnDocumentChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
    {
        RichTextBox rtb = (RichTextBox)obj;
        rtb.Document = (FlowDocument)args.NewValue;
    }
}
</pre>
<p>I hope you find a use for this – I simply need it written down somewhere so I don’t forget!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/leomburke.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/leomburke.wordpress.com/8/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leomburke.wordpress.com&#038;blog=7579884&#038;post=8&#038;subd=leomburke&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://leomburke.wordpress.com/2010/04/09/binding-and-styling-text-to-a-richtextbox-in-wpf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/67f0caee10a2adc1664f26eda21facb9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">leomburke</media:title>
		</media:content>
	</item>
	</channel>
</rss>
