<?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/"
	>

<channel>
	<title>xaml ninja &#187; MVVM</title>
	<atom:link href="http://blogs.xamlninja.com/category/mvvm/feed" rel="self" type="application/rss+xml" />
	<link>http://blogs.xamlninja.com</link>
	<description>xaml ninja moves</description>
	<lastBuildDate>Tue, 10 Jan 2012 19:46:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>WP7 Contrib &#8211; Bing Service Wrapper Part I &#8211; Location</title>
		<link>http://blogs.xamlninja.com/xaml/wp7-contrib-bing-service-wrapper-part-i-location</link>
		<comments>http://blogs.xamlninja.com/xaml/wp7-contrib-bing-service-wrapper-part-i-location#comments</comments>
		<pubDate>Fri, 24 Jun 2011 14:31:13 +0000</pubDate>
		<dc:creator>rich</dc:creator>
				<category><![CDATA[Bing Services]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WP7]]></category>
		<category><![CDATA[WP7Contrib]]></category>
		<category><![CDATA[Xaml]]></category>
		<category><![CDATA[WP7Dev]]></category>

		<guid isPermaLink="false">http://blogs.xamlninja.com/?p=499</guid>
		<description><![CDATA[This being the first post about the Wrappers I thought that we should break the ice with the most commonly used service. Location. Out of all of the services this is the simplest to call but also we would suspect the most widely used. When you combine this service with the device location based WP7C [...]]]></description>
			<content:encoded><![CDATA[<p>This being the first post about the Wrappers I thought that we should break the ice with the most commonly used service. Location. Out of all of the services this is the simplest to call but also we would suspect the most widely used. When you combine this service with the device location based WP7C bits then you can build your geo location aware app and have it plotting to a map and moving in real-time, or you could be helping your user to find the location of an address.</p>
<p>In the sample for using the location service we tackle both of these scenarios.</p>
<p>So, I am going to jump straight in here and assume that you have either looked at the sample in the Spikes folder of the <a href="http://wp7contrib.codeplex.com/" target="_blank">WP7 Contrib</a> (WP7C) or you have some experience of using the Rest API provided by the Bing Maps endpoint. If you have not done this then I would suggest opening up the sample and taking a quick look at the Location View Model, its pretty straight forwards so you should be back in 10.</p>
<p>First off if you have not already created a project then you need too. If you are using MVVM and some sort of DI library cool, if not no worries. There are two different options provided by the Location Service from the Bing REST API; you can either use the Geo Coordinate Location of the device and pass this to the service in order to give you back a current address; or you can enter a location to find out what Geo Coordinate Location is.</p>
<p>If you are not already using the WP7C components in you app (shame on you J) then you need to add a couple of references in order to get this up and running, these include:-</p>
<ul>
<li>WP7Contrib.Services
<ul>
<li>BingMaps</li>
<li>BingMaps.Model</li>
<li>Location</li>
</ul>
</li>
</ul>
<p>These are the basic bits that you need to get your geo location app up and running. Once we have included those assemblies then we need to define the interfaces we want to use and the data objects that correspond to the location service calls.</p>
<p>First up we need to declare the private fields so let’s go ahead and do that</p>
<pre class="brush: csharp">
private readonly IBingMapService bingMapService;
private readonly ILocationService locationService;
private LocationRect boundingRectangle;
private GeoCoordinate currentDeviceGeoCoordinate;
private IDisposable currentLocationObserver;
private RelayCommand selectFindMyCurrentLocationCommand;
private RelayCommand selectFindGeoLocationFromAddressCommand;
private Address address;
private LocationData locationDataByPoint;
</pre>
<p>&nbsp;</p>
<p>Next, we need to create a constructor for our VM. You will notice that not only am I using the ILocationService which is the WP7C’s Rx location component but we are also going to pass in a IBingMapService which is our wrapper that we will use to call the REST services. The other interfaces that I am using here are the navigation service and the logging component from WP7C.</p>
<pre class="brush: csharp">
public LocationViewModel(
INavigationService navigationService,
ILocationService locationService,
IBingMapService bingMapService,
ILog log)
: base(navigationService, log)
{
this.locationService = locationService;
this.bingMapService = bingMapService;
this.address = new Address {CountryRegion = &quot;UK&quot;, PostalCode = &quot;LE17 5ER&quot;};
}
</pre>
<p>&nbsp;</p>
<p>Currently, and this is consistent across all of our samples we are using Funq as our DI framework of choice, its light and simple which is why it’s great for WP7, we are not bound to Funq in anyway so if you want to use your Favourite DI then you can do so.</p>
<p>With our constructor defined we need to go ahead and do our register and resolve in the bootstrapper.</p>
<p>There is quite a bit of stuff happening in the bootstrapper, mainly because of the fact that we are taking advantage of the different components inside of the WP7C, now you don’t have to use these however if you need things like logging; want to store data; and if you have a design where you are not loading all the VM’s upfront take a look at the Last Message Replay. As this is the first in a series of posts we can deconstruct what is happening here in the future articles I will only reference this section.</p>
<p>The code below setups the Logging bits for us.</p>
<pre class="brush: csharp">
this.Container.Register&lt;ILogManager&gt;(c =&gt; new LoggingService(&quot;BingMaps&quot;));
this.Container.Register&lt;ILog&gt;(c =&gt; this.Container.Resolve&lt;ILogManager&gt;());
&lt;p&gt;var logManager = this.Container.Resolve&lt;ILogManager&gt;();
logManager.Enable();
</pre>
<p>&nbsp;</p>
<p>Here we setup the settings for the app and assign the key that we want to use for bing maps. The registered key in the code is registered to the WP7C so I would advise that you register, it does not take long and the key is generated instantly.</p>
<pre class="brush: csharp">
this.Container.Register&lt;IStoreSettings&gt;(c =&gt; new SettingsStore(this.Container.Resolve&lt;ILog&gt;()));
this.Container.Register&lt;ISettings&gt;(c =&gt; new Settings(&quot;Bing Key&quot;));
var serialisationAssemblies = new List&lt;Assembly&gt; { this.GetType().Assembly };
</pre>
<p>&nbsp;</p>
<p>Setup the cache provider and initialise it.</p>
<pre class="brush: csharp">
this.Container.Register&lt;ICacheProvider&gt;(c =&gt; new  IsolatedStorageCacheProvider(&quot;BingMaps&quot;, serialisationAssemblies,  c.Resolve&lt;ILog&gt;()));
var cache = this.Container.Resolve&lt;ICacheProvider&gt;();
System.Threading.ThreadPool.QueueUserWorkItem(state =&gt; cache.PreemptiveInitialise());
</pre>
<p>&nbsp;</p>
<p>Setup the last replay messenger.</p>
<pre class="brush: csharp">
this.Container.Register&lt;IMessenger&gt;(c =&gt; new LastMessageReplayMessenger());
</pre>
<p>&nbsp;</p>
<p>Setup the WP7C Navigation Service.</p>
<pre class="brush: csharp">
this.Container.Register&lt;INavigationService&gt;(

c =&gt; new ApplicationFrameNavigationService(((App)Application.Current).RootFrame));
</pre>
<p>&nbsp;</p>
<p>Setup the WP7C Network service</p>
<pre class="brush: csharp">
this.Container.Register&lt;INetworkService&gt;(c =&gt; new NetworkMonitor(5000));
</pre>
<p>&nbsp;</p>
<p>Setup the WP7C Storage service.</p>
<pre class="brush: csharp">
var assemblies = new List&lt;Assembly&gt; { this.GetType().Assembly, typeof(BaseModel).Assembly };
this.Container.Register&lt;IStorageService&gt;(c =&gt; new StorageService(assemblies, c.Resolve&lt;ILog&gt;()));
</pre>
<p>&nbsp;</p>
<p>As we are using the Resource Client from WP7C we also need to add this setup code into our bootstrapper.</p>
<pre class="brush: csharp">
this.Container.Register&lt;IEncodeProperties&gt;(c =&gt; new UrlEncoder());
this.Container.Register&lt;IHandleResourcesFactory&gt;(c =&gt; new ResourceClientFactory(c.Resolve&lt;ILog&gt;()));
</pre>
<p>&nbsp;</p>
<p>The final part is that we need to wire in the IBingMapService which needs to be resolved using some of the interfaces that we registered earlier.</p>
<pre class="brush: csharp">
this.Container.Register&lt;IBingMapService&gt;(c =&gt; new BingMapService(
c.Resolve&lt;IHandleResourcesFactory&gt;(),
c.Resolve&lt;IEncodeProperties&gt;(),
c.Resolve&lt;ICacheProvider&gt;(),
c.Resolve&lt;ISettings&gt;(),
c.Resolve&lt;ILog&gt;()));
</pre>
<p>&nbsp;</p>
<p>Ok, so we nearly have, all of the underlying plumbing done what we need to do next is to setup the VM locator. If you need more details on this please refer to the sample code. Once you have the VM locator updated we can go ahead and bind our Data Context up to the VM using the service locator pattern in Xaml.</p>
<p>As I mentioned at the start of this article, the UI’s are more about form and function, so our intentions are purely to visualise all the different types of data coming back from the service. So, for this we went with simple UI controls to make sure that the data being returned from our request is correct.</p>
<p>Now, that we have the plumbing in place, and some simple UI that displays the responses, our next step is to make our requests out to the Bing Services. This code is going to live in the VM.</p>
<p>The first thing on our list to implement is that we need to make our app location aware, everything you need to do this is already baked in the WP7C, it just requires a simple bit of Rx to get it wired in. In order to do this we need to leverage the ILocation Service that we injected into the VM as this will find out what our current location is.</p>
<pre class="brush: csharp">
private GeoCoordinate currentDeviceGeoCoordinate;
private IDisposable currentLocationObserver;
private void ExecuteSelectFindMyCurrentLocationCommand()
{
try
{
this.currentLocationObserver =
this.locationService.Location()
.ObserveOnDispatcher()
.Subscribe(geoCoordinate =&gt;
{
this.CurrentDeviceGeoCoordinate = geoCoordinate;
this.SearchForLocation(this.BuildLocationSearchForPoint());
});
}
catch (Exception exn)
{
MessageBox.Show(string.Format(&quot;Failed! Message - &#039;{0}&quot;, exn.Message), &quot;Location Search&quot;,                MessageBoxButton.OK);
}}
</pre>
<p>&nbsp;</p>
<p>Notice in the subscribe how we are assigning a value to the VM’s Current Device Geo Coordinate Property which is bound up in the view; also note that we are then doing a Search for a geo location and passing into this method the result from the Build Location Search For Point. We decided that in order for us to wrap up all the services and provide a common API from which users can use the services we would adopt a factory style pattern. So, what’s going on in the Build method? Well here we are calling out to the factory and asking it to create what we need in order to query the Bing services for dealing with the request.</p>
<pre class="brush: csharp">
private ILocationSearchPointCriterion BuildLocationSearchForPoint()
{
return CriterionFactory.CreateLocationSearchForPoint(this.CurrentDeviceGeoCoordinate);
}
</pre>
<p>&nbsp;</p>
<p>And that is all you need to add location awareness to your app, I hope that you agree with me that this is rather straight forwards. Next up we need to build out the search for location method, which is going to use the Bing wrapper service from the WP7C to search for a location. If you have looked over the code you will see that we have 2 overloaded methods, one which deals with Geo Location and the other which deals with addresses.</p>
<pre class="brush: csharp">
private void SearchForLocation(ILocationSearchPointCriterion criterion)
{
this.bingMapService.SearchForLocationUsingPoint(criterion)
.ObserveOnDispatcher()
.Subscribe(this.ProcessSearchLocationByPointResponse,
FailedSearch,
CompletedSearch);
}
</pre>
<p>&nbsp;</p>
<p>And for completeness I have included the code for the address mechanism below.</p>
<p>&nbsp;</p>
<pre class="brush: csharp">
private void SearchForLocation(ILocationSearchAddressCriterion criterion)
{
this.bingMapService.SearchForLocationUsingAddress(criterion)
.ObserveOnDispatcher()
.Subscribe(this.ProcessSearchLocationByAddressResponse,
FailedSearch,
CompletedSearch);
}
</pre>
<p>&nbsp;</p>
<p>Note that there are a couple of differences between the overloads; first the interface type that we are passing into our method for locations we always need to use the ILocationSearchPointCriterion and for addresses we need to use the ILocationSearchAddressCriterion; and the other difference is that we use a different method to deal with the response that we get sent from the Bing Services.</p>
<pre class="brush: csharp">
private void ProcessSearchLocationByPointResponse(LocationSearchResult result)
{
if (result == null)
{
return;
}
if (result.Locations.Count != 0)
this.LocationDataByPoint = result.Locations[0];
}
</pre>
<p>In order to successfully process the data and then work on this data the WP7C provides you with the data transformation classes that you need and does all the map and wrap code so that you don’t have to. In the code above this is illustrated by our use of the LocationDataByPoint property which uses the Location Data class from the WP7C, we are using databinding in the view and wiring up to this property from the VM .</p>
<p>So, just to recap what we have covered are a couple of things here; first we made our app Geo Location aware by using the WP7C Rx location service; which was then wired up to the Bing Services Wrapper and we used this to provide an address of the device&#8217;s current location; and for completeness we provide a way for the user to enter details of an address and the app responds with a Geo Location that corresponds to the address.</p>
<p>Admittedly we are doing some simple tasks here however its super important that we put in the ground work so that you can gain a deep understanding of how the wrappers work. We would really like to hear your feedback, if you have built an app using the Bing services we would also be interested in talking to you about your sceanrios.</p>
<p>In the next post I will dig into using the Route Service.</p>
<p><a href="http://awkwardcoder.blogspot.com/" target="_blank">Ollie</a> has some deep dive blog posts planned which are based around the patterns that he is using along with some gems of information around using Rx with these more traditional patterns so watch out for those.</p>
<p>Enjoy!</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.xamlninja.com/xaml/wp7-contrib-bing-service-wrapper-part-i-location/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>uk tech.days 2011</title>
		<link>http://blogs.xamlninja.com/silverlight/uk-tech-days-2011</link>
		<comments>http://blogs.xamlninja.com/silverlight/uk-tech-days-2011#comments</comments>
		<pubDate>Mon, 23 May 2011 12:31:12 +0000</pubDate>
		<dc:creator>rich</dc:creator>
				<category><![CDATA[Blend]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[uktechdays]]></category>
		<category><![CDATA[Xaml]]></category>

		<guid isPermaLink="false">http://blogs.xamlninja.com/?p=464</guid>
		<description><![CDATA[This week Ollie and I will presenting at the UK tech.days happening in the Fulham, London. Our first session will be all about building Data Data Intensive apps for WP7 and we are really looking forward to talking to you about what we have learnt building these types of applications. We are also going to [...]]]></description>
			<content:encoded><![CDATA[<p>This week <a href="http://awkwardcoder.blogspot.com/" target="_blank">Ollie </a>and I will presenting at the UK <a href="http://uktechdays.cloudapp.net/home.aspx">tech.days</a> happening in the Fulham, London.</p>
<p>Our first session will be all about building <a href="http://uktechdays.cloudapp.net/techdays-live/windows-phone-1-state-of-the-nation.aspx" target="_blank">Data Data Intensive apps for WP7</a> and we are really looking forward to talking to you about what we have learnt building these types of applications. We are also going to show off bits from the WP7 Contrib that help to make building these types of applications easier. It&#8217;s going to be a demo packed session so hold on for a rollercoaster ride. We are making avaliable all our demos before the session so if you are attending and interested you can download these from the skydrive link at the bottom of the post.</p>
<p>My other session obviously will be about using Blend =P  and the title of the session is aptly named <a href="http://uktechdays.cloudapp.net/techdays-live/building-rich-client-applications.aspx">&#8220;Expression Blend for Silverlight Developers&#8221;</a>.</p>
<p>The session is broken down into 3 sub sections; designer developer collaboration; Blend quick fire tips; and the main part, building out an app from a Adobe Photoshop/Illustrator visual design into a functional Silverlight app. This session is aimed particularly at developers who are just starting out with Blend, however even if you have been using Blend for a while there should be plenty of refreshers.</p>
<p>Now, I had thought about doing</p>
<p><em> “… this is how I create a button in Blend, and oh look I can make it into a circle and bounce across the screen…”</em></p>
<p>as much as I love attending these sessions and love the buzz afterwards sometimes it can be difficult to relate the content to a problem you may currently be working on.</p>
<p>Up on skydrive you will find; the .psd file I am going to use; an unstyled version; and a completed version that is styled. There is still plenty more to do so the scope is open and hopefully you will be able to use this as a reference point for future apps that you build. Therefore, I thought that it would be an interesting idea to see how attendees if they so wished can use the session as a hands-on Blend training hour, and if you want to participate then you can. Otherwise you can sit back and watch how we build a static vector graphic into a functioning app.</p>
<p>If you are planning on attending and would like me to cover off anything in particular I will do my best to make it happen, otherwise I would be more than happy to chat during the event, if you can bring code or have a scenario that would really help me understand the context of your questions.</p>
<p>You can find all of the goodies up on the sky drive folder.</p>
<p>See you there!</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.xamlninja.com/silverlight/uk-tech-days-2011/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>WP7 Contrib &#8211; When messaging becomes messy and services shine</title>
		<link>http://blogs.xamlninja.com/mvvm/wp7-contrib-when-messaging-becomes-messy-and-services-shine</link>
		<comments>http://blogs.xamlninja.com/mvvm/wp7-contrib-when-messaging-becomes-messy-and-services-shine#comments</comments>
		<pubDate>Tue, 08 Feb 2011 16:58:58 +0000</pubDate>
		<dc:creator>rich</dc:creator>
				<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WP7]]></category>
		<category><![CDATA[WP7Contrib]]></category>
		<category><![CDATA[Xaml]]></category>

		<guid isPermaLink="false">http://blogs.xamlninja.com/?p=358</guid>
		<description><![CDATA[In a previous post I introduced you to the Last Message Replay Messenger, in this post I wanted to dig into something that happened recently where I needed to provided the ability in the application for the user to add an item to a favourites list. Ok so fairly straight forwards, however there was a [...]]]></description>
			<content:encoded><![CDATA[<p>In a previous <a href="http://blogs.xamlninja.com/xaml/wp7-contrib-the-last-messenger" target="_blank">post </a>I introduced you to the Last Message Replay Messenger, in this post I wanted to dig into something that happened recently where I needed to provided the ability in the application for the user to add an item to a favourites list. Ok so fairly straight forwards, however there was a slight twist. Not only can the user add items to their favourites from a list but they can also add an item to their favourites list from a number  of different places in the application.  Each view has a different VM and we don’t want to chain the VM&#8217;s together as then they know about each other; we also don’t want to use the VM Locator from the Xaml and call the same relay command to perform the action; so on the surface this looks like a job for a messenger :-</p>
<ol>
<li>Define the Message which wraps up the data</li>
<li>Add the IMessenger interface as a parameter in the VM constructor</li>
<li>Register the IMessenger interface with the Last Message Replay Messenger</li>
<li>In the originator register the type of message data your interested in with the Notification Message Action</li>
<li>In the VM which is interested in the message register for the Message defined in step 1</li>
<li>Provide a method that deals with the received messages and sets up the data context of the View</li>
</ol>
<p>Now this works just fine when I want to pass data to disconnected lazy loading VM&#8217;s but I got into trouble when it came to stashing this content. The main reason is that it comes down to a level of responsibility which results in the question of who owns the data ? and who is responsible for storing the data ?</p>
<p>What I ended up with was a collection of favourites that were being managed by each VM that required their Views to have the ability; add to the favourites list and then fire a message broadcasting that here is the new favourite item which needs to be added into the favourites collection. Cool!</p>
<p>So all is cool now? Well sure until it comes to building out the persistence mechanism using the override Activate and DeActive methods that the VM Base provides us with in order to store the data. My next move was then to start changing the data inside of the Message to a collection of the same type, but this solution means that I now pass around a reference pointer to the collection in the message and each VM is then responsible for adding new items. The Favourites VM is then inherently responsible for persisting the collection. Ok so that gets us closer. Unfortunately, the Favourites Page and VM are not primaries in the user journey through the app therefore, there is a high potential that the user will not have viewed the Favourites Page resulting the Favourites VM not being instantiated and now things start to get sticky again….</p>
<p>At this point its time for a brew&#8230;. I could continue trying to bend the message pattern to fit our needs but its generating a large amount of friction when we try and push. This is where using a service makes far more sense. Now, if you chat to <a href="http://awkwardcoder.blogspot.com/" target="_blank">Ollie </a>he will say well this is all about &#8220;ask don’t tell, Rich&#8221;.  Therefore, moving to a more service style pattern similar to the one used in the service layer for our Apps results in those VM&#8217;s which need to use the favourites service have this injected during startup via the bootstrapper. Unlike our current situation where each VM has to register for the message. This gets us back into check with a single responsibility pattern. As the favourites service is now responsible for anything to do with favourites cleaning up the implementation code in the VM&#8217;s wanting to use the service. Sweet!<a href="http://blogs.xamlninja.com/wp-content/uploads/2011/02/servicestyleratherthanmessenger.png" rel="shadowbox[sbpost-358];player=img;" target="_blank"><img class="alignright size-full wp-image-374" style="margin: 5px;" title="servicestyleratherthanmessenger" src="http://blogs.xamlninja.com/wp-content/uploads/2011/02/servicestyleratherthanmessenger.png" alt="" width="354" height="629" /></a></p>
<p>Now I really like this pattern as its super simple to implement and by taking advantage of IStorage and IStorageService which can be found in the WP7C not only do we have a simple pattern for sharing data and operating on that data, we also get the ability to stash this content into Isolated Storage.</p>
<p>The best way for me to show this off is to do a sample, so I am going to build on the sample from the previous post, its also in the spikes directory on <a href="http://wp7contrib.codeplex.com/" target="_blank">Codeplex</a>. What we are going to add to this is a favourites page, wired up to a Favourites VM, and a favourites service that has the ability for our user to do an add to favourites from the list (Main VM)and an add to favourites from the details page (Child VM).</p>
<p>First, up we need to create an interface, in my case its called IFavouriteSearch and it going to provide a service to retrieve the current collection of favourites, add a new favourite, query to see if the service already contains a particular favourite and also remove a favourite from the collection.</p>
<pre class="brush: csharp">
using ServiceStyleRatherThanMessengerStyle.Model;

using WP7Contrib.Collections;

/// &lt;summary&gt;
/// The favourites service contract.
/// &lt;/summary&gt;
public interface IFavouritesService
{
        #region Properties

        /// &lt;summary&gt;
        /// Gets Favourites.
        /// &lt;/summary&gt;
        ReadOnlyObservableCollection&lt;Person&gt; Favourites { get; }

        #endregion

        #region Public Methods

        /// &lt;summary&gt;
        /// The add.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;person&quot;&gt;
        /// The currently selected person.
        /// &lt;/param&gt;
        void Add(Person person);

        /// &lt;summary&gt;
        /// The is a favourite.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;person&quot;&gt;
        /// The person.
        /// &lt;/param&gt;
        /// &lt;returns&gt;
        /// The is a favourite.
        /// &lt;/returns&gt;
        bool IsAFavourite(Person person);

        /// &lt;summary&gt;
        /// The remove favoutite.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;person&quot;&gt;
        /// The person.
        /// &lt;/param&gt;
        void RemoveFavourite(Person person);

        #endregion
}
</pre>
<p>That’s the service defined.</p>
<p>Next up we need to define a concrete class called the Favourite Service which implements the interface, the important part to remember here is that we want to stash the collection to isolated storage in order to persist the selected favourites between sessions. In order to do this we can simply pass into the constructor the IStorageService interface, if you wanted to use the logging parts of <a href="http://wp7contrib.codeplex.com/" target="_blank">WP7C</a> then you can added this into the constructor parameter list.</p>
<pre class="brush: csharp">
public FavouritesService(IStorageService storageService, ILog log)
{
   this.storageService = storageService;
   this.log = log;
}
</pre>
<p>So this is the cool part, when we expose the favourites collection all we need to do is work out if we are rehydrating the collection for the first time from Isolated Storage and load up the collection in ISO, otherwise we new up a collection of the required type. Each piece of content that is stored into ISO has its own key, in my case its called favourites and its used as the Unique ID to retrieve the specified content. The code to Load from Storage is boiler plate and done once it’s a rinse and repeat style pattern.</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// Gets Favourites.
/// &lt;/summary&gt;
public ReadOnlyObservableCollection&lt;Person&gt; Favourites
{
   get
   {
      if (!this.loaded)
      {
         this.LoadFromStorage();
      }

       return new ReadOnlyObservableCollection&lt;Person&gt;(this.favourites);
   }
}
</pre>
<p>The management methods that operate on the collection we build out as normal and then decorate this code with the storage calls. These are rather easy to remember; once the collection has been updated then we make a call to write the list into ISO associated with our Unique ID, then we flush the storage buffer.</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// Adds a person to the favourites.
/// &lt;/summary&gt;
/// &lt;param name=&quot;person&quot;&gt;
/// The currently selected person.
/// &lt;/param&gt;
public void Add(Person person)
{
   if (person == null)
   {
      return;
   }

   if (!this.loaded)
   {
      this.LoadFromStorage();
   }

   if (this.favourites.Contains(person))
   {
      return;
   }

   this.favourites.Add(person);
   this.storage.Write(StorageKey, this.favourites.ToList());
   this.storage.Flush();
}

/// &lt;summary&gt;
/// The is a favourite.
/// &lt;/summary&gt;
/// &lt;param name=&quot;person&quot;&gt;
/// The person.
/// &lt;/param&gt;
/// &lt;returns&gt;
/// Returns true if the person is a favourite.
/// &lt;/returns&gt;
public bool IsAFavourite(Person person)
{
   if (person == null)
   {
      return false;
   }

   if (!this.loaded)
   {
      this.LoadFromStorage();
   }

   return this.favourites.Contains(person);
}

/// &lt;summary&gt;
/// The remove favoutite.
/// &lt;/summary&gt;
/// &lt;param name=&quot;person&quot;&gt;
/// The persoh.
/// &lt;/param&gt;
public void RemoveFavourite(Person person)
{
   if (person == null)
   {
      return;
   }

   if (!this.loaded)
   {
      this.LoadFromStorage();
   }

   if (!this.favourites.Contains(person))
   {
      return;
   }

   this.favourites.Remove(persoh);
   this.storage.Write(StorageKey, this.favourites);
   this.storage.Flush();
}
</pre>
<p>Lets now take a look at the Load From Storage method.</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// The load from storage.
/// &lt;/summary&gt;
private void LoadFromStorage()
{
   if (this.loaded)
   {
      return;
   }

   lock (this.sync)
   {
      if (this.loaded)
      {
         return;
      }

      this.favourites = new ObservableCollection&lt;Person&gt;();
      this.storage = this.storageService.OpenPersistent(StorageKey);

      var favs = this.storage.Read&lt;List&lt;Person&gt;&gt;(StorageKey);
      if (favs == null || favs.Count == 0)
      {
         this.log.Write(&quot;FavouritesService: No favourites&quot;);
      }
      else
      {
         foreach (Person fav in favs)
         {
              this.log.Write(&quot;FavouritesService: Loading Person, hash code - &quot; + fav.GetHashCode());
              this.favourites.Add(fav);
         }
     }

      this.loaded = true;
   }
}
</pre>
<p>When we need to read the collection we use the Storage service to setup the storage mechanism once this has been done happy days simply call the Read method telling what type is being rehydrated using the specified  Unique key that was defined earlier. Iterate over what comes out and add it to our collection.</p>
<p>Now we need to be able to use the service so we head over to the bootstrapper and crank out some register and resolve calls for the service.</p>
<pre class="brush: csharp">
this.Container.Register&lt;ILogManager&gt;(c =&gt; new LoggingService(&quot;LastReplayMessenger&quot;));

this.Container.Register&lt;ILog&gt;(c =&gt; this.Container.Resolve&lt;ILogManager&gt;());

var assemblies = new List&lt;Assembly&gt; { this.GetType().Assembly, typeof(BaseModel).Assembly };

this.Container.Register&lt;IStorageService&gt;(c =&gt; new StorageService(c.Resolve&lt;ILog&gt;(), assemblies));

this.Container.Register&lt;IFavouritesService&gt;(
c =&gt; new FavouritesService(c.Resolve&lt;IStorageService&gt;(), c.Resolve&lt;ILog&gt;()));
</pre>
<p>And that’s our service registered and resolved, our next step is to inject the favourite service into the VM&#8217;s that are going to be using it.</p>
<pre class="brush: csharp">
this.Container.Register(
c =&gt;
new MainViewModel(
c.Resolve&lt;INavigationService&gt;(),
c.Resolve&lt;IMessenger&gt;(),
c.Resolve&lt;ILog&gt;(),
c.Resolve&lt;IFavouritesService&gt;()));

this.Container.Register(
c =&gt;
new ChildViewModel(
c.Resolve&lt;INavigationService&gt;(),
c.Resolve&lt;IMessenger&gt;(),
c.Resolve&lt;ILog&gt;(),
c.Resolve&lt;IFavouritesService&gt;()));
</pre>
<p>A common scenario is that we have a View which provides an experience that allows the user to add items via a list. In my case I choose a context menu which was added to the data template used by the list box. In order to do this I created a Relay Command and wired this up to the context menu from the toolkit in the data template. There are two implementations that we need to implement here first we need to be able to trigger a command from inside the data template of the listbox.</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// The select add to favourites command.
/// &lt;/summary&gt;
private RelayCommand&lt;Person&gt; selectAddToFavouritesCommand;

/// &lt;summary&gt;
/// Gets SelectAddToFavouritesCommand.
/// &lt;/summary&gt;
public RelayCommand&lt;Person&gt; SelectAddToFavouritesCommand
{
   get
   {
      return this.selectAddToFavouritesCommand ??
      (this.selectAddToFavouritesCommand = new RelayCommand&lt;Person&gt;(this.ExecuteAddToFavouritesCommand));
   }

   private set
   {
      this.selectAddToFavouritesCommand = value;
   }
}

/// &lt;summary&gt;
/// The execute add to favourites command.
/// &lt;/summary&gt;
/// &lt;param name=&quot;person&quot;&gt;
/// The person.
/// &lt;/param&gt;
private void ExecuteAddToFavouritesCommand(Person person)
{
   this.favouritesService.Add(person);
}
</pre>
<pre class="brush: xml">
&lt;toolkit:ContextMenuService.ContextMenu&gt;
&lt;toolkit:ContextMenu&gt;
&lt;toolkit:MenuItem Header=&quot;add to favourites&quot;
Command=&quot;{Binding MainViewModel.SelectAddToFavouritesCommand, Source={StaticResource Locator}}&quot;
CommandParameter=&quot;{Binding .}&quot; /&gt;
&lt;/toolkit:ContextMenu&gt;
&lt;/toolkit:ContextMenuService.ContextMenu&gt;
</pre>
<p>And the other implementation is from an app bar button.</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// The execute add to favourites command.
/// &lt;/summary&gt;
private void ExecuteAddToFavouritesCommand()
{
   this.favouritesService.Add(this.CurrentlySelectedPerson);
   this.NavigationService.Navigate(new Uri(&quot;/View/FavouritesPage.xaml&quot;, UriKind.Relative));
}
</pre>
<pre class="brush: xml">
&lt;phone:PhoneApplicationPage.ApplicationBar&gt;
&lt;shell:ApplicationBar IsVisible=&quot;True&quot;
IsMenuEnabled=&quot;True&quot;&gt;
&lt;shell:ApplicationBarIconButton x:Name=&quot;AddToFavourites&quot;
IconUri=&quot;/resources/icons/appbar.favs.addto.rest.png&quot;
Text=&quot;AddToFavourites&quot; /&gt;
&lt;/shell:ApplicationBar&gt;
&lt;/phone:PhoneApplicationPage.ApplicationBar&gt;

&lt;i:Interaction.Behaviors&gt;
&lt;Behaviors:ApplicationBarIconButtonCommand TextKey=&quot;AddToFavourites&quot;
CommandBinding=&quot;{Binding SelectAddToFavouritesCommand}&quot; /&gt;
&lt;/i:Interaction.Behaviors&gt;
</pre>
<p>Lets just quickly circle back, what we have done thus far is implement the required add to favourites functionality, but ultimately we also want to allow the user to view their favourites so next we need to create the page and the favourites VM remembering to add the new VM to the VM Locator.</p>
<p>The favourites VM.</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// The favourites view model.
/// &lt;/summary&gt;
public class FavouritesViewModel : ViewModelBaseWp7
{
    #region Constants and Fields

    /// &lt;summary&gt;
    /// The favourites service.
    /// &lt;/summary&gt;
    private readonly IFavouritesService favouritesService;

    /// &lt;summary&gt;
    /// The currently selected person.
    /// &lt;/summary&gt;
    private Person currentlySelectedPerson;

    #endregion

    #region Constructors and Destructors

    /// &lt;summary&gt;
    /// Initializes a new instance of the &lt;see cref=&quot;FavouritesViewModel&quot;/&gt; class.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;navigationService&quot;&gt;
    /// The navigation service.
    /// &lt;/param&gt;
    /// &lt;param name=&quot;messenger&quot;&gt;
    /// The messenger.
    /// &lt;/param&gt;
    /// &lt;param name=&quot;log&quot;&gt;
    /// The log.
    /// &lt;/param&gt;
    /// &lt;param name=&quot;favouritesService&quot;&gt;
    /// The favourites service.
    /// &lt;/param&gt;
    public FavouritesViewModel(
        INavigationService navigationService, IMessenger messenger, ILog log, IFavouritesService favouritesService)
        : base(navigationService, messenger, log)
    {
        this.favouritesService = favouritesService;

        ThreadPool.QueueUserWorkItem(
            state =&gt; { this.MessengerInstance.Register&lt;SelectedPersonMessage&gt;(this, this.OnReceiveMessage); });
    }

    #endregion

    /// &lt;summary&gt;
    /// Gets CurrentlySelectedCurrentlySelectedPerson.
    /// &lt;/summary&gt;
    public Person CurrentlySelectedPerson
    {
        get
        {
            return this.currentlySelectedPerson;
        }

        private set
        {
            this.SetPropertyAndNotify(ref this.currentlySelectedPerson, value, &quot;CurrentlySelectedPerson&quot;);
        }
    }

    public ReadOnlyObservableCollection&lt;Person&gt; Favourites
    {
        get
        {
            return this.favouritesService.Favourites;
        }
    }

    #region Methods

    private void OnReceiveMessage(SelectedPersonMessage obj)
    {
        if (obj == null)
        {
            return;
        }

        if (obj.Person == null)
        {
            return;
        }

        this.CurrentlySelectedPerson = obj.Person;
    }

    /// &lt;summary&gt;
    /// The is being activated.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;storage&quot;&gt;
    /// The storage.
    /// &lt;/param&gt;
    protected override void IsBeingActivated(IStorage storage)
    {
    }

    /// &lt;summary&gt;
    /// The is being deactivated.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;storage&quot;&gt;
    /// The storage.
    /// &lt;/param&gt;
    protected override void IsBeingDeactivated(IStorage storage)
    {
    }

    #endregion
}
</pre>
<p>And the favourites page which has a listbox data bound to the favourites collection exposed by the VM.</p>
<pre class="brush: xml">
&lt;Grid x:Name=&quot;ContentPanel&quot;
Grid.Row=&quot;1&quot;
Margin=&quot;12,0,12,0&quot;&gt;
&lt;ListBox ItemsSource=&quot;{Binding Path=Favourites}&quot;
SelectedItem=&quot;{Binding Path=CurrentlySelectedPerson}&quot;
ItemTemplate=&quot;{StaticResource PersonsDataTemplate}&quot;
ItemContainerStyle=&quot;{StaticResource ListBoxItemStyle1}&quot; /&gt;
&lt;/Grid&gt;
</pre>
<p>And we are done!</p>
<p>One thing that I did add here is the Last Replay Message Messenger and data binding to the selected item in the listbox so that I can highlight the newly added favourite.</p>
<p>A quick recap on what happened</p>
<ol>
<li>Create the interface for the service and expose what you need usually a collection and some management methods for managing the data</li>
<li>Create the concrete implementation adding in the IStorageService into the constructor</li>
<li>In the concrete add logic to rehydrate and stash your data</li>
<li>Update the constructor on the VM&#8217;s that need to have the add to favourites functionality</li>
<li>In the Bootstrapper register the new service  and Resolve them in the VM&#8217;s</li>
<li>Create relay commands in the VM and View to trigger the actions</li>
<li>Create the favourites page and VM</li>
<li>Update the Bootstrapper and VM Locator with the new VM</li>
<li>Expose a property for the collection so that it can be bound to in the View</li>
<li>[Optional] use the Last Replay Message to inform the favourites VM about the currently selected person</li>
</ol>
<p>What is very interesting about all this is that we so often when using a framework get familiar with a certain technique and this becomes fashionable and we try to use it everywhere and there is nothing wrong with trying out new ways of doing something. However, there also has to be a realisation that when we start getting friction trying to bend the framework api to do something that it was not really meant for its time to use something solves the problem better.</p>
<p>Interested in your comments and you can find the code up on <a href="http://wp7contrib.codeplex.com/">codeplex</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.xamlninja.com/mvvm/wp7-contrib-when-messaging-becomes-messy-and-services-shine/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>WP7 Contrib &#8211; the last messenger</title>
		<link>http://blogs.xamlninja.com/xaml/wp7-contrib-the-last-messenger</link>
		<comments>http://blogs.xamlninja.com/xaml/wp7-contrib-the-last-messenger#comments</comments>
		<pubDate>Thu, 27 Jan 2011 17:43:42 +0000</pubDate>
		<dc:creator>rich</dc:creator>
				<category><![CDATA[funq]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WP7]]></category>
		<category><![CDATA[WP7Contrib]]></category>
		<category><![CDATA[Xaml]]></category>

		<guid isPermaLink="false">http://blogs.xamlninja.com/?p=309</guid>
		<description><![CDATA[As you may already be aware the WP7C uses MVVM Light as its preferred MVVM framework. Laurent has a great implementation of a Mediator style pattern that he has aptly name the Messenger. What I really like about this is the simplicity when it comes to implementing the baked in messages and how you can [...]]]></description>
			<content:encoded><![CDATA[<p>As you may already be aware the WP7C uses MVVM Light as its preferred MVVM framework. Laurent has a great implementation of a Mediator style pattern that he has aptly name the Messenger. What I really like about this is the simplicity when it comes to implementing the baked in messages and how you can extend the IMessenger interface that Laurent has included in MVVM Light. In general these generic messages cater for the majority of problems. However, there is a case that is not particularly well catered for. What follows is focused on WP7 however, this messenger component could be recompiled under your favourite SL build and used in your MVVM Light application today.</p>
<p>Before we start to roll you are going to make sure you have all the bits installed</p>
<p>WP7 Dev tools <a href="http://go.microsoft.com/fwlink/?LinkId=201927">ISO </a>download thanks <a href="http://blogs.msdn.com/b/jaimer/">JaimeR</a></p>
<p><a href="http://mvvmlight.codeplex.com/">MVVM Light Toolkit</a></p>
<p><a href="http://wp7contrib.codeplex.com">WP7 Contrib</a></p>
<p>Now if you are using some sort of DI component, at the moment my favourite is <a href="http://funq.codeplex.com/">funq </a>(<a href="http://ninject.org/">Ninject </a>will always have a place in my heart)  you may have found yourself in a situation where by you want to pass data from one VM to another, however the VM you want to pass the data to has not yet been created. There are various ways around this like not using DI and newing up all your VM during start-up so that this is no longer an issue. But, remember we are running under WP7 and performance is never going to be what it’s like in the browser.  We also want to take advantage of DI and all the goodness that it brings to the party.</p>
<p>Which came first, the chicken or the egg ??</p>
<p>An inherent problem with using Silverlight navigation and DI and having your VM’s lazily loaded. When you navigate to a page its not until this moment in time that your VM is constructed, therefore we hit this timing problem where the VM that is loaded up and trying to send a message to a VM which has yet to be loaded. What we first started out with was an implementation that was not so polished in that we would have a Register and Send Message being defined in the VM making the call; a Register Message defined in the receiving VM; and a callback Message in the receiving VM.</p>
<p>The way in which this works would be something like :-</p>
<ol>
<li>VM SearchPeople Registers for Message CurrentlySelectedPerson</li>
<li>In response to an interaction in the View (i.e. selecting an item in a list box). The associated VM SearchPeople Sends Message CurrentlySelectedPerson from within a INPC Property</li>
<li>In response to an interaction in the View (i.e. tapping an item in a list box). The associated VM SearchPeople ‘s  RelayCommand navigates to a new page Person Details</li>
<li>VM Person Details is constructed by our DI framework</li>
<li>VM Person Details constructor Registers for the Message CurrentlySelectedPerson</li>
<li>VM Person Details constructor fires a CallBack for the MessageCurrentlySelectedPerson</li>
<li>VM SearchPeople received the Message CurrentlySelectedPerson</li>
<li>VM SearchPeople Send the Message CurrentlySelectedPerson</li>
<li>VM PersonDetails received the Message CurrentlySelectedPerson</li>
</ol>
<p>This mechanism has to deal with the timing issue of the second VM not being loaded before the message is sent from the first, we end up in a situation where the first message never works and the subsequent messages always work. Therefore, by providing a callback in the second  and sending the message from here to the first VM we solve the problem, but its not as elegant as it could be.  The main issue here is that we are forced to send our messages twice due to the fact that our recipient VM has yet to be created and we need to give it a poke.</p>
<p>What becomes apparent is that the callback mechanism is not built for this type of work and we need a more structured and direct messaging mechanism. I had a chat with Ollie and he came up with a great messaging implementation. The rest of this post is concerned with how to use this Replay Messenger in your app,  <a href="http://awkwardcoder.blogspot.com/">Ollie </a>has a great post coming where he is going to go into more detailed post on the implementation details.</p>
<p>Laurent has provided an interface called IMessenger which provides developers with the ability to extend the and create our own Messages, nice&#8230;  Let’s make a start on building out a simple implementation. If you have <a href="http://blogs.xamlninja.com/wp-content/uploads/2011/01/WP7Contrib-Last-messenger.png" rel="shadowbox[sbpost-309];player=img;"><img class="alignright size-full wp-image-325" title="WP7Contrib Last messenger" src="http://blogs.xamlninja.com/wp-content/uploads/2011/01/WP7Contrib-Last-messenger.png" alt="" width="385" height="645" /></a>all the bits installed lets make a start. First off what is this app we are going to build, well is a simple app which has some sort of people list and we can select a person from the list and navigate to a more detailed page. Not the most exciting of apps but I want to keep the context fairly striaght forward so that we can concentrate on the problem and the solution rather than being distracted by other stuff. Saying that you are going too meet some other interface from WP7Contrib, ILogManager, ILog and INavigation Service. Over on the right you can see an screen shot showing the strcuture of the sample which can be found in the Spikes dir of the WP7Contrib.</p>
<p>My intentions below are not to walk you through every step we have some planned detailed posts and maybe even some screencasts to illustrate this points, therefore I am assumming that you know about the message classes availavble to you in MVVM Light Messaging and I am also assuming that you understand how to uses a DI framework.</p>
<p>Over on the right there is a screen grab of the solution if you want to fire this up then you can find it in the Spikes dir of the WP7Contrib. I have a model class called Person this is going to hold our data;2 pages main page and child page; 2 corresponding View Models main VM and child VM; in messages I have a base message and something called the Selected Person Message; a custom Base VM for WP7 which subclasses the MVVM Light VM Base; and finally I have a BootStrapper for my DI bits.</p>
<p>So first off what we need to do is take a look at the Selected Person Message as this is the message which is a wrapper for our data that we want to pass from the Main VM to the Child VM.</p>
<pre class="brush: csharp">
namespace ReplayLastMessageMessenger.ViewModel.Messages
{
    using System;

    using ReplayLastMessageMessenger.Model;

    /// &lt;summary&gt;
    /// The currently selected search result message.
    /// &lt;/summary&gt;
    public class SelectedPersonMessage : BaseMessage
    {
        #region Constants and Fields

        /// &lt;summary&gt;
        /// The person.
        /// &lt;/summary&gt;
        private readonly Person person;

        #endregion

        #region Constructors and Destructors

        /// &lt;summary&gt;
        /// Initializes a new instance of the &lt;see cref=&quot;SelectedPersonMessage&quot;/&gt; class.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;person&quot;&gt;
        /// The person.
        /// &lt;/param&gt;
        public SelectedPersonMessage(Person person)
        {
            this.person = person;
        }

        /// &lt;summary&gt;
        /// Initializes a new instance of the &lt;see cref=&quot;SelectedPersonMessage&quot;/&gt; class.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;exception&quot;&gt;
        /// The exception.
        /// &lt;/param&gt;
        public SelectedPersonMessage(Exception exception)
        {
            this.Exception = exception;
        }

        #endregion

        #region Properties

        /// &lt;summary&gt;
        /// Gets person.
        /// &lt;/summary&gt;
        public Person Person
        {
            get
            {
                return this.person;
            }
        }

        #endregion
    }
}
</pre>
<p>The code above is boiler plate making the implementation clean and repeatable, the code above is the message that we use for passing Property data between our VM&#8217;s. </p>
<p>That’s the message built. </p>
<p>Remember, what we have in our view is a list of items, and in our case a list of people and when you select an item from the list we navigate from this page to a details page, and we do this by sending a message that contains the data of the currently selected item from the list.</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// Gets or sets CurrentlySelectedPerson.
/// &lt;/summary&gt;
public Person CurrentlySelectedPerson
{
    get
    {
        return this.currentlySelectedPerson;
    }

    set
    {
        this.SetPropertyAndNotify(ref this.currentlySelectedPerson, value, &quot;CurrentlySelectedPerson&quot;);
        this.NavigationService.Navigate(new Uri(&quot;/View/ChildPage.xaml&quot;, UriKind.Relative));
        this.MessengerInstance.Send(new SelectedPersonMessage(this.currentlySelectedPerson));
    }
}
</pre>
<p>Note, in the above code the Messenger is only responsible for sending message, its the Navigation Service that is responsible for the navigation from the list page to the details page and the details page displays the details of the data item selected from the list, therefore the Child VM will need to know the currently selected person. I will cover off the Navigation Service interface in a future post.</p>
<p>In order to do this we need to inject the IMessenger into each VM from our bootstrapper.  I am using funq for this so the code below is specific to funq however it’s the same drill register your wire ups with the container and then resolve them to an interface, This will provide a way of firing Registering and Sending those Currently Selected Person messages.</p>
<pre class="brush: csharp">
public class BootStrapper : IDisposable
{
    #region Constants and Fields

    /// &lt;summary&gt;
    /// The disposed.
    /// &lt;/summary&gt;
    private bool disposed;

    #endregion

    #region Constructors and Destructors

    /// &lt;summary&gt;
    /// Initializes a new instance of the &lt;see cref=&quot;BootStrapper&quot;/&gt; class.
    /// &lt;/summary&gt;
    public BootStrapper()
    {
        this.Container = new Container();

        this.ConfigureContainer();
    }

    #endregion

    #region Properties

    /// &lt;summary&gt;
    /// Gets Container.
    /// &lt;/summary&gt;
    public Container Container { get; private set; }

    #endregion

    #region Implemented Interfaces

    #region IDisposable

    /// &lt;summary&gt;
    /// The dispose.
    /// &lt;/summary&gt;
    public void Dispose()
    {
        if (this.Container != null)
        {
            this.Container.Dispose();
            this.Container = null;
        }
    }

    #endregion

    #endregion

    #region Methods

    /// &lt;summary&gt;
    /// The configure container.
    /// &lt;/summary&gt;
    private void ConfigureContainer()
    {
        this.Container.Register&lt;ILogManager&gt;(c =&gt; new LoggingService());

        this.Container.Register&lt;ILog&gt;(c =&gt; this.Container.Resolve&lt;ILogManager&gt;());

        this.Container.Register&lt;IMessenger&gt;(c =&gt; new LastMessageReplayMessenger());

        this.Container.Register&lt;INavigationService&gt;(
            c =&gt; new ApplicationFrameNavigationService(((App)Application.Current).RootFrame));

        this.Container.Register(
            c =&gt; new MainViewModel(c.Resolve&lt;INavigationService&gt;(), c.Resolve&lt;IMessenger&gt;(), c.Resolve&lt;ILog&gt;()));

        this.Container.Register(
            c =&gt; new ChildViewModel(c.Resolve&lt;INavigationService&gt;(), c.Resolve&lt;IMessenger&gt;(), c.Resolve&lt;ILog&gt;()));
    }

    #endregion
}
</pre>
<p>There are a couple of interfaces here that I am injecting into my VM&#8217;s these include the Navigation Service, the log manager and the log all of which we will talk about in future posts.</p>
<p>Again, Laurent has done a great job by providing a property in the View Model Base  called Messenger Instance which returns the instance of the messenger we injected in our bootstrapper, nice. There is a small nugget here as well to help with performance, as the registration of the message does not need to happen on the UI thread we can wrap this up like so.</p>
<p>The Main VM looks like this.</p>
<pre class="brush: csharp">
public MainViewModel(INavigationService navigationService, IMessenger messenger, ILog log)
    : base(navigationService, messenger, log)
{
    ThreadPool.QueueUserWorkItem(state =&gt;
    {
        // messaging
        this.MessengerInstance.Register&lt;NotificationMessageAction&lt;Person&gt;&gt;(
            this, message =&gt; message.Execute(this.CurrentlySelectedPerson));
    });
}
</pre>
<p>Now in the constructor of the Child VM its far sweeter code instead of the crufty callback and force a message in order to get the data we simply register for the replay message we are interested in, and provide a method to deal with the received message.</p>
<pre class="brush: csharp">
public ChildViewModel(INavigationService navigationService, IMessenger messenger, ILog log)
    : base(navigationService, messenger, log)
{
    ThreadPool.QueueUserWorkItem(state =&gt;
    {
        this.MessengerInstance.Register&lt;SelectedPersonMessage&gt;(this, this.OnReceiveMessage);
    });
}
</pre>
<p>The Xaml in the Main View looks like this.</p>
<pre class="brush: xml">
&lt;!--ContentPanel - place additional content here--&gt;
&lt;Grid x:Name=&quot;ContentPanel&quot;
        Grid.Row=&quot;1&quot;
        Margin=&quot;12,0,12,0&quot;&gt;
    &lt;ListBox ItemsSource=&quot;{Binding Path=Persons}&quot;
                SelectedItem=&quot;{Binding Path=CurrentlySelectedPerson, Mode=TwoWay}&quot;
                ItemTemplate=&quot;{StaticResource PersonsDataTemplate}&quot; /&gt;
&lt;/Grid&gt;
</pre>
<p>The Xaml in the Child View looks like this.</p>
<pre class="brush: xml">
&lt;!--ContentPanel - place additional content here--&gt;
&lt;Grid x:Name=&quot;ContentPanel&quot;
        Grid.Row=&quot;1&quot;
        Margin=&quot;12,0,12,0&quot;&gt;
    &lt;Grid.RowDefinitions&gt;
        &lt;RowDefinition Height=&quot;90&quot; /&gt;
        &lt;RowDefinition Height=&quot;513&quot; /&gt;
    &lt;/Grid.RowDefinitions&gt;
    &lt;StackPanel Orientation=&quot;Vertical&quot;&gt;
        &lt;TextBlock Text=&quot;{Binding CurrentlySelectedPerson.LastName}&quot;
                    FontFamily=&quot;{StaticResource PhoneFontFamilySemiLight}&quot;
                    FontSize=&quot;{StaticResource PhoneFontSizeMediumLarge}&quot; /&gt;
        &lt;TextBlock Text=&quot;{Binding CurrentlySelectedPerson.FirstName}&quot;
                    FontFamily=&quot;{StaticResource PhoneFontFamilySemiLight}&quot;
                    FontSize=&quot;{StaticResource PhoneFontSizeMedium}&quot; /&gt;
    &lt;/StackPanel&gt;
    &lt;Border Grid.Row=&quot;1&quot;
            BorderThickness=&quot;2&quot;&gt;
        &lt;Image Source=&quot;{Binding CurrentlySelectedPerson.ProfileImage}&quot; /&gt;
    &lt;/Border&gt;
&lt;/Grid&gt;
&lt;/Grid&gt;
</pre>
<p><a href="http://blogs.xamlninja.com/wp-content/uploads/2011/01/ReplayLastMessagePeopleList.png" rel="shadowbox[sbpost-309];player=img;"><img src="http://blogs.xamlninja.com/wp-content/uploads/2011/01/ReplayLastMessagePeopleList.png" alt="" title="ReplayLastMessagePeopleList" style="border: 5px solid black; margin: 5px;" width="296" height="539" class="alignnone size-full wp-image-332" /></a><br />
<a href="http://blogs.xamlninja.com/wp-content/uploads/2011/01/ReplayLastMessagePersonDetails.png" rel="shadowbox[sbpost-309];player=img;"><img src="http://blogs.xamlninja.com/wp-content/uploads/2011/01/ReplayLastMessagePersonDetails.png" alt="" title="ReplayLastMessagePersonDetails" style="border: 5px solid black; margin: 5px;" width="296" height="539" class="alignnone size-full wp-image-333" /></a></p>
<p>Just to recap our steps were :-</p>
<ol>
<li>Define the Message which wraps up the data</li>
<li>Add the IMessenger interface as a parameter in the VM constructor</li>
<li>Register the IMessenger interface with the Last Message Replay Messenger</li>
<li>In the originator register the type of message data you’re interested in with the Notification Message Action</li>
<li>In the VM which is interested in the message register for the Message defined in step 1</li>
<li>Provide a method that deals with the received messages and setups up the data context of the View</li>
</ol>
<p>You can find out more information on the <a href="http://wp7contrib.codeplex.com">WP7Contrib</a> and find out what people are saying on twitter #WP7Contrib.</p>
<p>As i mentioned at the start if you are already using MVVM Light today then you can take advantage of the Last Replay Message. Ollie is going to follow up with a more detail post on the implementation details.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.xamlninja.com/xaml/wp7-contrib-the-last-messenger/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Its a POC don&#8217;t worry about the data&#8230;</title>
		<link>http://blogs.xamlninja.com/blend/its-a-poc-dont-worry-about-the-data</link>
		<comments>http://blogs.xamlninja.com/blend/its-a-poc-dont-worry-about-the-data#comments</comments>
		<pubDate>Thu, 11 Mar 2010 13:37:43 +0000</pubDate>
		<dc:creator>rich</dc:creator>
				<category><![CDATA[Blend]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Surface]]></category>
		<category><![CDATA[Xaml]]></category>

		<guid isPermaLink="false">http://blogs.xamlninja.com/blend/its-a-poc-dont-worry-about-the-data</guid>
		<description><![CDATA[In the last post my aim was to start a conversation around the advantages of building a visual data model. But this is a POC ? Why would you do this? Well its an interesting question and I am sure that there are folks out there who like to build prototypes and POC’s in this [...]]]></description>
			<content:encoded><![CDATA[<p>In the last post my aim was to start a conversation around the advantages of building a visual data model.</p>
<p>But this is a POC ? Why would you do this? </p>
<p>Well its an interesting question and I am sure that there are folks out there who like to build prototypes and POC’s in this way, but based on my experience this usually ends up taking longer as you find yourself adding a workaround to the existing workarounds resulting in friction between what you want to do and the limitations of the framework. So the approach that I prefer to use is to take some time out at the start of the process and deconstruct the visual designs and build out a data model to represent what information needs to be presented. We can then go off and create the simple factory classes to build these data structures and take full advantage of the features supported by the framework. In essence we are using the same techniques that we would use for a production quality application but slimming down a journey through the application using more appropriate patterns.</p>
<p>This simple process is not time consuming, helps clear up any potential misunderstanding of how the application will react based on certain interactions, and it means that when deconstructing the visual designs its easy to figure out what type of control you can use in order to build the visual and if the control you are thinking about using will support the interactions required. The additional bonus here is that if you want to go a step further then you easily wire in a simple MVVM pattern, again this is something that I do however its not an essential step.</p>
<p>What I also like about this approach is that POC’s are usually built in a short timeframe and are thus open to change on a regular basis and we need to have an approach which reduces churn. By having a good data model you can limit the pain when things change as you can easily change the data object to suit and then a simple change to the Xaml. The opposite of this can result in lots of conditional logic which becomes prone to bugs and also limiting the application to potentially just a clickable mockup.</p>
<p>The other benefit which results in this approach is the level of reusability that I can pull from the POC and move into the production application. By having taken the time to produce a data structure that is usable this means that I can potentially reuse all the existing data templates, data bindings, styles, templates and certain custom controls. Again from my experience this level of reusability is normally higher than when we push forwards with a more static and tightly coupled approach.</p>
<p>To put this into a better context, a number of Surface applications that I have been involved in recently have required a ScatterView with ScatterView Items as these control provide those all important gestures for NUI interactions out of the box. Cool, but we are faced with the options either; create a known number of items and potentially recreate the same style but with different hardwired data; or create a single data template and style and take advantage of the data bind features. This can easily be achieved by data binding to the DP’s provided by the ScatterView Item that controls its placement, its easy to maintain and manage when those known changes happen. It also provides us with the flexibility to extend certain aspects rapidly without getting freaked out by the amount of conditional logic being added to the app.</p>
<p>My approach here is a simple one, create a base class for all your data controlled visuals which allow you to provide point data information so that when the objects are created you can initialise them where they need to be placed on screen. You can also add into here some more properties such as Orientation and data bind your data object property to the Orientation DP. Properties such as CanScale etc I would manipulate in a Style for the ScatterView Item, however there is no reason why you could not add them into the base. My reasons for the using a Style is so that when I am working with the designer I can easily make changes to the Style when we are both using Blend, it also allows me to share the work with designers visually, this for me is essential, personally I am more of a visual guy I prefer to see something rather than read textual content a visual helps paint the picture in a more accurate way with less room for individual perceptions of a textual instruction or description.</p>
<p>This simple approach provides; the ability to place visual elements exactly where the designer wants them;animations can be built in order to animate these visual elements on and off screen, interrogating the strongly typed data types means that we can apply the required styles on demand; reduces the complexity of app by taking advantage of data binding.</p>
<p>Just to break this down a little further, with the Tag Heuer implementation, I created a bunch of data objects for the locations around the world, London, Los Angeles, Cape Town, Sydney etc; all of which subclass the same base called Location. Location, Travel and Watches, the three different states of the app all subclass a class providing the positioning logic which intern subclasses an abstract base implementing INPC. I then have a data templates for each of the locations that we need to visualise, London, Los Angeles, Cape Town, Sydney etc. The data templates deal nicely with presenting our data, however there is a problem with layout as some of the aforementioned locations need to be positioned from left to right and some need to be positioned from right to left. To achieve this visual effect I used a different style<br />
 one for left to right and a second for right to left and wired these into the data template. I could have written c# to flip the visual tree however in this instance it was more effective to rebuild the styles in Blend it also has the advantage that I can show the designer in Blend the visual created and make any additional tweaks required.</p>
<p><a href="http://blogs.xamlninja.com/wp-content/uploads/2010/03/Illustrated_Travel.png" rel="shadowbox[sbpost-211];player=img;" target="_blank"><img style="border-bottom: 0px; border-left: 0px; margin: 5px; display: inline; float: none; border-top: 0px; border-right: 0px" title="Illustrated_Travel" border="0" alt="Illustrated_Travel" src="http://blogs.xamlninja.com/wp-content/uploads/2010/03/Illustrated_Travel_thumb.png" width="644" height="483" /></a> </p>
<p>I used the same technique for the F1 GP races and the watches area all of which have strongly typed data objects to encapsulate the visual information providing me with the advantages mentioned above to create and adapt quickly with the changes to the visual designs, it also allows me to take advantage of OO when it comes to adding additional properties to the base classes which will have a ripple effect down the object hierarchy.</p>
</p>
<p>In your next POC or prototype in WPF I hope that you will feel confident enough to try out this technique and reap the benefits that are at your disposal. Unfortunately the current version of Silverlight does not support implicit data templates, which in my humble opinion is a fundamental missing part of the Silverlight framework. Hopefully we will see this in a future release.</p>
<p> In the next post I am going to dig into how I built the watches section of the application and also dive into how interactions with the watch chrome and its content were created.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.xamlninja.com/blend/its-a-poc-dont-worry-about-the-data/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JC Decaux and Tag Heuer Surface Application deployed to Heathrow T5</title>
		<link>http://blogs.xamlninja.com/blend/jc-decaux-and-tag-heuer-surface-application-deployed-to-heathrow-t5</link>
		<comments>http://blogs.xamlninja.com/blend/jc-decaux-and-tag-heuer-surface-application-deployed-to-heathrow-t5#comments</comments>
		<pubDate>Thu, 25 Feb 2010 15:13:37 +0000</pubDate>
		<dc:creator>rich</dc:creator>
				<category><![CDATA[Blend]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Surface]]></category>
		<category><![CDATA[Xaml]]></category>

		<guid isPermaLink="false">http://blogs.xamlninja.com/?p=172</guid>
		<description><![CDATA[This is really the start of a number of posts that I have been meaning to put together for a while now. These are centred around how to rapidly build prototypes. It’s a technique that I use on a regular basis both for WPF and for Silverlight. In order for me to get across how [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blogs.xamlninja.com/wp-content/uploads/2010/02/T5_21.jpg" rel="shadowbox[sbpost-172];player=img;" target="_blank"><img style="display: inline; border: 0px;" title="T5_2" src="http://blogs.xamlninja.com/wp-content/uploads/2010/02/T5_2_thumb1.jpg" border="0" alt="T5_2" width="280" height="184" /></a> <a href="http://blogs.xamlninja.com/wp-content/uploads/2010/02/surface_unit_photos_manemailable1.jpg" rel="shadowbox[sbpost-172];player=img;" target="_blank"><img style="display: inline; border: 0px;" title="surface_unit_photos_manemailable" src="http://blogs.xamlninja.com/wp-content/uploads/2010/02/surface_unit_photos_manemailable_thumb1.jpg" border="0" alt="surface_unit_photos_manemailable" width="273" height="184" /></a></p>
<p>This is really the start of a number of posts that I have been meaning to put together for a while now. These are centred around how to rapidly build prototypes. It’s a technique that I use on a regular basis both for WPF and for Silverlight. In order for me to get across how effective this is it seems only right to provide context of how you can also take advantage of this technique.</p>
<p>More about that later, for this particular implementation I partnered with Splendid in order to produce an interactive experience for travellers at London Heathrow T5 lounges. The brief was to help raise brand awareness of the new Tag Heuer watches available and take advantage of the collaborate aspects provided by Surface.</p>
<p>The Tag Heuer Surface application has three main areas of functionality, all driven by the concept of time.<br />
<br/></p>
<p><a href="http://blogs.xamlninja.com/wp-content/uploads/2010/02/04_travel_detail11.jpg" rel="shadowbox[sbpost-172];player=img;" target="_blank"><img style="margin-top: 5px; margin-right: 5px; margin-bottom: 5px; margin-left: 10px; display: inline; border: 0px initial initial;" src="http://blogs.xamlninja.com/wp-content/uploads/2010/02/04_travel_detail1_thumb1.jpg" border="0" alt="04_travel_detail1" width="244" height="184" align="right" /></a></p>
<p><strong>Travel Guide:</strong> The application displays the current time at your departure destination, displayed on a Tag Heuer watch display with moving hands. Using a stylized world map passengers can choose popular destinations and explore local time, travel duration and view local landmarks.</p>
<p><br/><br/><br/><br/><br/><br/><br />
<a href="http://blogs.xamlninja.com/wp-content/uploads/2010/02/06_sports_detail1.jpg" rel="shadowbox[sbpost-172];player=img;" target="_blank"><img style="margin-top: 5px; margin-right: 10px; margin-bottom: 5px; margin-left: 5px; display: inline; border: 0px initial initial;" src="http://blogs.xamlninja.com/wp-content/uploads/2010/02/06_sports_detail_thumb1.jpg" border="0" alt="06_sports_detail" width="244" height="184" align="left" /></a></p>
<p><strong><strong>Sports Finder:</strong></strong> Tag Heuer have a number of sports stars as ambassadors, we chose Lewis Hamilton as the trial location was the UK. Passengers can explore the world find the next Grand Prix including a  countdown and images of last years race.</p>
<p><br/><br/><br/><br/><br/><br/><br />
<a href="http://blogs.xamlninja.com/wp-content/uploads/2010/02/08_collection_detail1_zoom1.jpg" rel="shadowbox[sbpost-172];player=img;" target="_blank"><img style="margin-top: 5px; margin-right: 5px; margin-bottom: 5px; margin-left: 10px; display: inline; border: 0px initial initial;" src="http://blogs.xamlninja.com/wp-content/uploads/2010/02/08_collection_detail1_zoom_thumb1.jpg" border="0" alt="09_collection_detail1_resize" width="244" height="184" align="right" /></a><strong><strong>Watch Explorer: </strong></strong>A Tag Heuer Application wouldn’t be quite right without the ability to explore their classic  watch collection, passengers can use gesture to explore high-res images of the men’s and women’s collections with the ability to sign-up for an email on your favourite watch. The email contains details of the watch and your nearest location to purchase.<br />
<br/><br/><br/><br/><br/><br/><br />
For a UX developer there are some really rather cool interactions used in each of the areas. I am going to try and give a higher level overview of these areas  below and then jump into the detail in separate posts. The first of these are interactions present in each of the different functional pillars of the experience illustrated above and were designed so that visual elements could be placed into specific areas, animation of these items on and off screen and designed in such away that data bound objects provided the visual positioning information. The solution I used here was a combination of strongly typed data templates with model objects that contained the required coordinates of where to be positioned on screen and styles to create the required interactions.</p>
<p>When deconstructing the visual design I knew that the ScatterView Control would do the job nicely and having the coordinates in the model meant that we can take full advantage of data binding as each ScatterView Item has a centre and orientation DP which can be used to achieve this layout. Using a different ScatterViewItem Style provided the ability to choose different interactions and visuals based on which area of functionality is in use. Note there are 2 styles for the map points; a style for map points which are right aligned and a style for those which are left aligned. Using the strongly typed data templates and the use of data binding provides a clean and easy to achieve solution that provided the required interactions. The application was aware of its state and by changing the data based on state the usage of the strongly typed data templates come into their own as these state changes are triggered resulting in the new visuals to be displayed all done using data and data bindings in the Xaml.</p>
<p>For the travel section animated clocks were used and the TimeZoneInfo class provided the ability  to calculate the time in different time zones. Here I used a dispatch timer that was ticking away and then updating the value of the data object. Each of the different time zones were associated data objects of the current location using data binding and INPC meant that we can change the time in the data object and this will trigger the animations used to rotate the hands on the watch.</p>
<p>The watch section has cool interaction where there is a 2 level zoom mechanism, I broke this one down to<a href="http://blogs.xamlninja.com/wp-content/uploads/2010/02/09_collection_detail1_resize1.jpg" rel="shadowbox[sbpost-172];player=img;" target="_blank"><img style="margin-top: 5px; margin-right: 5px; margin-bottom: 5px; margin-left: 10px; display: inline; border: 0px initial initial;" src="http://blogs.xamlninja.com/wp-content/uploads/2010/02/09_collection_detail1_resize_thumb1.jpg" border="0" alt="09_collection_detail1_resize" width="244" height="184" align="right" /></a> be a ScatterViewItem which wraps a ScatterView. This allowed for an interaction which meant the user could  use a pinch gesture in increase the size of the outer ring and then a second pinch gesture can be used to manipulate the watch being displayed. What I like about this interaction design is that it allows the user to easy move and collaborate with other users interested in seeing the detailing of the watch. More importantly this also meant that I could take full advantage of data binding and strongly typed data templates.</p>
<p>As you may have noticed there is an underlying theme happening here, data and Xaml. For me WPF is really all about your data, get the data structure right that needs to be presented on screen and we can take full advantage of the framework and reduce the amount of C# code we write to a minimum.</p>
<p>links</p>
<p>The Moodie Report <a href="http://www.moodiereport.com/document.php?c_id=1113&amp;doc_id=23335">http://www.moodiereport.com/document.php?c_id=1113&amp;doc_id=23335</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.xamlninja.com/blend/jc-decaux-and-tag-heuer-surface-application-deployed-to-heathrow-t5/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>PDC09 &#8211; Meet the Griffs Code drop</title>
		<link>http://blogs.xamlninja.com/silverlight/pdc09-meet-the-griffs-code-drop</link>
		<comments>http://blogs.xamlninja.com/silverlight/pdc09-meet-the-griffs-code-drop#comments</comments>
		<pubDate>Thu, 19 Nov 2009 18:58:35 +0000</pubDate>
		<dc:creator>rich</dc:creator>
				<category><![CDATA[Blend]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Ninject]]></category>
		<category><![CDATA[PDC09]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://blogs.xamlninja.com/?p=132</guid>
		<description><![CDATA[Ian and myself really enjoyed presenting our pre conference session  “Getting the most out of Silverlight” and we both hope that you enjoyed the sessions. The slide decks will be posted at some point by the event team and I will update the post when this happens so that you can get copies of the [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.interact-sw.co.uk/iangblog/" target="_blank">Ian</a> and myself really enjoyed presenting our pre conference session  “Getting the most out of Silverlight” and we both hope that you enjoyed the sessions. The slide decks will be posted at some point by the event team and I will update the post when this happens so that you can get copies of the decks.</p>
<p>As promised I have stashed all the final code examples up on my skydrive folder so that you can download and play with the samples. As we ran out of time in the last session what I will do in the next week or so is to record a Camtasia session and capture what I unfortunately did not get time to go over during the session.</p>
<p>I have named the zip files as intuitively as possible so these line up with the title of the session.</p>
<p>What I also wanted to briefly mention is that in the MEF and Ninject demos you will see that I am using Commands from the Silverlight Extensions project on <a href="http://www.codeplex.com/SLExtensions" target="_blank">CodePlex</a>. The command pattern that is used here is a standard command pattern common to WPF. In the current release there is no support for Commands so what you will see included in the projects are the Command classes that I need in order to harness the power of Commands.</p>
<p>In a previous life I wrote a <a href="http://consultingblogs.emc.com/richardgriffin/archive/2007/02/23/WPF-Commands-a-scenic-tour-part-I.aspx" target="_blank">post</a> on WPF commands that you may want to take a look at if you are not familiar to the Command pattern used in WPF and how it helps to separate out UI logic into you View Model and helps increase the testability of your code that responds to the behaviours in your application. The refactor that I did here was to remove the click event handler on the button and replace this with a command. There are 3 steps for refactoring out the event handler.</p>
<p>First we need to create a commands.cs file and create a Commands class which will hold all our commands associated with our view model. In essence we are going to be providing a list of possible actions that the View Model can perform in relation to the view. Once we have created the class we need to define our commands that we want which in our demo is called RefreshFeedItems then we need to add in public mechanism so that we can invoke the command from the view so that it can be wired up to a button.</p>
<pre class="brush: csharp">

using StandardViewModel.SLExtensions.Input;

public class Commands
{
      private static readonly Command refreshFeeds = new Command(RefreshFeedItems);

      public static Command RefreshFeedItems

      { get { return refreshFeeds; } } }
</pre>
<p>Now that we have defined the command that we want to fire we need to do the second part which is to wire up the command in the Xaml of the view.</p>
<pre class="brush: xml">
     Input:CommandService.Command=RefreshFeedItems

     &lt;Button Content=Refresh
                    Grid.Column=2
                    Margin=&quot;3,3,3,3&quot;
                    IsEnabled=&quot;{Binding IsRefreshEnabled}&quot;
                    Input:CommandService.Command=&quot;RefreshFeedItems&quot; /&gt;
</pre>
<p>We can now remove the click handler code behind of the view.</p>
<p>The finally part is to implement the CanExecute and Executed code in the ViewModel, so move into the Constructor of the ViewModel and here wire up the commands.</p>
<pre class="brush: csharp">
       Commands.RefreshFeedItems.CanExecute += (sender, args) args.CanExecute = true;
       Commands.RefreshFeedItems.Executed += delegate(object sender, ExecutedEventArgs args)
         {
                        Refresh();
         };
</pre>
<p>And we are done. Enjoy. One thing to note is that there are other types of commands, <a href="http://joshsmithonwpf.wordpress.com/2008/11/17/emulating-icommandsource-in-silverlight-2/" target="_blank">RelayCommand</a> and <a href="http://www.mokosh.co.uk/post/Prism-2-WPF-and-Silverlight-Commands.aspx" target="_blank">DelegateCommand</a> which are also very cool black belt ninja moves for dealing with separation when building your MVVM apps</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://blogs.xamlninja.com/silverlight/pdc09-meet-the-griffs-code-drop/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>MVVM, design time data, and Blendability</title>
		<link>http://blogs.xamlninja.com/silverlight/mvvm-design-time-data-and-blendability</link>
		<comments>http://blogs.xamlninja.com/silverlight/mvvm-design-time-data-and-blendability#comments</comments>
		<pubDate>Fri, 02 Oct 2009 08:44:15 +0000</pubDate>
		<dc:creator>rich</dc:creator>
				<category><![CDATA[Blend]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Ninject]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Xaml]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://blogs.xamlninja.com/?p=34</guid>
		<description><![CDATA[With the introduction of design time data support in Blend I thought that I would try and take advantage of using design time data and MVVM. For a while now I have been using Ninject, with a Service Locator Pattern to provide the ability to build WPF and Silverlight apps in an MVVM pattern where [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://blogs.xamlninja.com/wp-content/uploads/2009/10/Designtimedataprojectstructure1.PNG" alt="Designtimedataprojectstructure" title="Designtimedataprojectstructure" width="444" height="450" class="alignleft size-full wp-image-84" />With the introduction of design time data support in Blend I thought that I would try and take advantage of using design time data and MVVM. For a while now I have been using Ninject, with a Service Locator Pattern to provide the ability to build WPF and Silverlight apps in an MVVM pattern where I prefer to use a View first mechanism. There are a number of benefits from using this approach, one of the ones that we are good to drill to in this post is around Blendability of the controls that developers create. Prior to me using Ninject I would have a heavy reliance on the DesignerProperties IsInDesignMode call to check to see if the control was being render in Blend, as i would normally have to do something to stop the control from crashing and allow myself and the designer to use Blend in order for us to Style and Template the controls we created.</p>
<p>What we are going to cover here is the journey which i went on when adding support for design time data to my project, I really like it as the refactoring from the standard inbuilt mechanism in Blend to the final output is a nice series of steps that feel good.<br />
<a href="http://blogs.xamlninja.com/wp-content/uploads/2009/10/Designtimedata.png" rel="shadowbox[sbpost-34];player=img;"><img style="border-right-width: 0px; margin: 10px 5px 10px 10px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Designtimedata" src="http://blogs.xamlninja.com/wp-content/uploads/2009/10/Designtimedata_thumb.png" border="0" alt="Designtimedata" width="395" height="276" align="right" /></a></p>
<p>The screen shot on the right shows the simple looking UI displaying contextual data in Blend allowing the designer to see how the control will look. I think providing the ability for your application to look exactly the same at design time as at run time is going to mean that you can produce better looking applications quicker as the designer is design the screens in the context of the data.</p>
<p>When first adding the design time data to your project Blend takes over control and this means that you need to use Blend to shape your design time data classes to match your data types used in the system. So if we were building a throw away prototype then I would agree this is the best way forwards, but when you are moving from prototype to production this does not really work. On of the reasons behind the research for this post is around the transition from prototype to production and even from sketch to prototype, once we have sign off from the client on a number of ideas and we want to start to build these out then there is a high potential one will become production quality and because of this its good to have the right architecture in place, so reshaping to MVVM early on will almost certainly cost your client less.</p>
<p>The Xaml below is what i put together to represent the shape of data that was in the mock classes. Blend then hooks this data up to the design time data context for you.</p>
<p>Xaml data for shopping cart</p>
<pre class="brush: xml">
&lt;local:ShoppingCartViewModel xmlns:local=&quot;clr-namespace:DesignDataSample;assembly=DesignDataSample&quot;&gt;
    &lt;local:ShoppingCartViewModel.ShoppingCart xmlns:local=&quot;clr-namespace:DesignDataSample;assembly=DesignDataSample&quot;&gt;
        &lt;local:ShoppingCart&gt;
            &lt;local:ShoppingCart.Items&gt;
                &lt;local:ShoppingCartItem ItemName=&quot;Book Name 1&quot;
                                        ItemDescription=&quot;A very nice book!&quot;
                                        ItemImage=&quot;MySampleDataImages/Tree.jpg&quot; /&gt;
                &lt;local:ShoppingCartItem ItemName=&quot;Book Name 2&quot;
                                        ItemDescription=&quot;A very nice book!&quot;
                                        ItemImage=&quot;MySampleDataImages/Tree.jpg&quot; /&gt;
                &lt;local:ShoppingCartItem ItemName=&quot;Book Name 3&quot;
                                        ItemDescription=&quot;A very nice book!&quot;
                                        ItemImage=&quot;MySampleDataImages/Tree.jpg&quot; /&gt;
                &lt;local:ShoppingCartItem ItemName=&quot;Book Name 4&quot;
                                        ItemDescription=&quot;A very nice book!&quot;
                                        ItemImage=&quot;MySampleDataImages/Tree.jpg&quot; /&gt;
            &lt;/local:ShoppingCart.Items&gt;
        &lt;/local:ShoppingCart&gt;
    &lt;/local:ShoppingCartViewModel.ShoppingCart&gt;
&lt;/local:ShoppingCartViewModel&gt;
</pre>
<p>When the design time data shape matches your real data shape you can then go ahead and use the new d:DataContext Dependency Property and bind your design time data to this property.</p>
<p>Xaml Source code for the control</p>
<pre class="brush: xml">
&lt;UserControl
        xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
             xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
             xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
             xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
             mc:Ignorable=&quot;d&quot;
             x:Class=&quot;DesignDataSample.ShoppingCartView&quot;
             d:DataContext=&quot;{d:DesignData Source=ShoppingCartSampleData.xaml}&quot;
             DataContext=&quot;{Binding Path=ShoppingCartViewModel, Source={StaticResource serviceLocator}}&quot;
             Height=&quot;347&quot;
             Width=&quot;494&quot;&gt;
</pre>
<p>Nothing too tricky there, the new design time data context is the key to making all this happen, it also means that you can bind any sort of data you want to the design time data context to provide contextual data in Blend during design time. It was at this point that i started to think about how we can really bend the design time data features. My initial refactor was not a great result in that I ended up with 2 sets of mock data; one set of data would be used by the designers in Blend; and the second set of data would be used by the unit test, Not nice, management nightmare to ensure that both data sets are keep in sync.</p>
<p>So the goal was to provide design time data which was the same data used by the unit tests, meaning that we only have one data set to maintain and manage, allowing us to leverage the powerful features of design time data in Blend and also keeping our unit tests looking sweet, pleasing both the designers and the developers on the team.</p>
<p>In order to do this I needed to restructure the existing shape of my data classes that I use in my mock service layer classes, first I needed to change the OnCompleted method to be a virtual implementation and also the method which retrieves the data. This simple change means that we can now provide two mock services that can be injected in.</p>
<p>Refactored mock service class with new virtual methods</p>
<pre class="brush: csharp">
    using System;
    using System.Collections.ObjectModel;

    public class MockShoppingCartService : IShoppingCartService
    {
        public event GetShoppingCartCompletedHandler GetShoppingCartCompleted;

        public bool LoginToShoppingCart(string username, string password)
        {
            throw new System.NotImplementedException();
        }

        public virtual void RetrieveShoppingCart()
        {
            this.OnGetShoppingCartCompleted(null, MockShoppingCartData.CreateShoppingCartRuntime());
        }

        protected virtual void OnGetShoppingCartCompleted(Exception error, ShoppingCart result)
        {
            if (this.GetShoppingCartCompleted != null)
            {
                this.GetShoppingCartCompleted(new GetShoppingCartCompletedEventArgs(error, result));
            }
        }
    }
</pre>
<p>The new mock service class which is used specifically for working with Blend</p>
<pre class="brush: csharp">
namespace DesignDataSample.Mocks
{
    public class MockShoppingCartServiceDesignData : MockShoppingCartService
    {
        public override void RetrieveShoppingCart()
        {
            this.OnGetShoppingCartCompleted(null, MockShoppingCartData.CreateShoppingCartDesigntime());
        }
    }
}
</pre>
<p>How we can use ninject to inject the service we want to use, design time data, mock or real.</p>
<pre class="brush: csharp">
this.Bind&lt;IShoppingCartService&gt;().To&lt;MockShoppingCartService&gt;().OnlyIf(c =&gt; isBrowser);
this.Bind&lt;IShoppingCartService&gt;().To&lt;MockShoppingCartServiceDesignData&gt;().OnlyIf(c =&gt; isBlend);
this.Bind&lt;IShoppingCartService&gt;().To&lt;ShoppingCartService&gt;().OnlyIf(c =&gt; isBrowser);
this.Bind&lt;ShoppingCartViewModel&gt;().ToSelf();
</pre>
<p>Xaml code for how we leverage the data context and the new design time data context for providing contextual data.</p>
<pre class="brush: xml">
&lt;UserControl
        xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
             xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
             xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
             xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
             mc:Ignorable=&quot;d&quot;
             x:Class=&quot;DesignDataSample.ShoppingCartView&quot;
             d:DataContext=&quot;{Binding Path=ShoppingCartViewModel, Source={StaticResource serviceLocator}}&quot;
             DataContext=&quot;{Binding Path=ShoppingCartViewModel, Source={StaticResource serviceLocator}}&quot; Height=&quot;347&quot; Width=&quot;494&quot;&gt;
&lt;!--d:DataContext=&quot;{d:DesignData Source=ShoppingCartSampleData.xaml}&quot;--&gt;
    &lt;UserControl.Resources&gt;
        &lt;DataTemplate x:Key=&quot;ShoppingCartItemTemplate&quot;&gt;
            &lt;Grid Height=&quot;50&quot;&gt;
                &lt;Grid.ColumnDefinitions&gt;
                    &lt;ColumnDefinition Width=&quot;50&quot; /&gt;
                    &lt;ColumnDefinition Width=&quot;*&quot; /&gt;
                &lt;/Grid.ColumnDefinitions&gt;
                &lt;Grid.RowDefinitions&gt;
                    &lt;RowDefinition Height=&quot;*&quot; /&gt;
                    &lt;RowDefinition Height=&quot;*&quot; /&gt;
                &lt;/Grid.RowDefinitions&gt;

                &lt;Image Source=&quot;{Binding ItemImage}&quot;
                       Grid.RowSpan=&quot;2&quot; /&gt;
                &lt;TextBlock Text=&quot;{Binding ItemName}&quot;
                           Grid.Column=&quot;1&quot;
                           Margin=&quot;4,0,0,0&quot; /&gt;
                &lt;TextBlock Text=&quot;{Binding ItemDescription}&quot;
                           Grid.Column=&quot;1&quot;
                           Grid.Row=&quot;1&quot;
                           Margin=&quot;4,0,0,0&quot; /&gt;
            &lt;/Grid&gt;
        &lt;/DataTemplate&gt;
    &lt;/UserControl.Resources&gt;

    &lt;Grid x:Name=&quot;LayoutRoot&quot;
          Background=&quot;#FFB2B2B2&quot;&gt;
        &lt;Grid.ColumnDefinitions&gt;
            &lt;ColumnDefinition /&gt;
            &lt;ColumnDefinition Width=&quot;129&quot; /&gt;
            &lt;ColumnDefinition Width=&quot;121&quot; /&gt;
        &lt;/Grid.ColumnDefinitions&gt;
        &lt;Grid.RowDefinitions&gt;
            &lt;RowDefinition /&gt;
            &lt;RowDefinition Height=&quot;50&quot; /&gt;
        &lt;/Grid.RowDefinitions&gt;
        &lt;ListBox Margin=&quot;8,8,8,26&quot;
                 Grid.ColumnSpan=&quot;3&quot;
                 ItemsSource=&quot;{Binding Mode=OneWay, Path=ShoppingCart.Items}&quot;
                 ItemTemplate=&quot;{StaticResource ShoppingCartItemTemplate}&quot; /&gt;
        &lt;TextBlock Grid.Row=&quot;1&quot;
                   Text=&quot;Total Items:&quot;
                   TextWrapping=&quot;Wrap&quot;
                   Grid.Column=&quot;1&quot; /&gt;
        &lt;TextBlock Grid.Column=&quot;2&quot;
                   Grid.Row=&quot;1&quot;
                   Text=&quot;{Binding ShoppingCart.Items.Count}&quot;
                   TextWrapping=&quot;Wrap&quot; /&gt;
    &lt;/Grid&gt;
&lt;/UserControl&gt;</pre>
<p> </p>
<p>So I hope that this article has opened your eyes to how useful design time data can be to enhance the Blendability of the controls which you produce both lookless and user. In the majority of cases designers that you are working with really like that they can view the control at deign time how it will appear when running in your application and populated with data.  When implementing the MVVM pattern in you application incorporating support for design time data is also possible and provides you with the ultimate Xaml Ninja experience.</p>
<p>You can download the source from my Skydrive.</p>
<p><iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="width:98px;height:115px;padding:0;background-color:#fcfcfc;" src="http://cid-118ee1873690fc1d.skydrive.live.com/embedicon.aspx/Silverlight3/DesignData/DesignDataSample.zip"></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.xamlninja.com/silverlight/mvvm-design-time-data-and-blendability/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

