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

<channel>
	<title>Manuel Felício&#039;s Weblog</title>
	<atom:link href="http://mfelicio.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://mfelicio.wordpress.com</link>
	<description>Sharing knowledge and ideas...</description>
	<lastBuildDate>Sat, 14 Jan 2012 13:04:20 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='mfelicio.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Manuel Felício&#039;s Weblog</title>
		<link>http://mfelicio.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://mfelicio.wordpress.com/osd.xml" title="Manuel Felício&#039;s Weblog" />
	<atom:link rel='hub' href='http://mfelicio.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Architecting Silverlight LOB applications (Part 6) &#8211; Building an MVVM Framework</title>
		<link>http://mfelicio.wordpress.com/2010/11/23/architecting-silverlight-lob-applications-part-6-building-an-mvvm-framework/</link>
		<comments>http://mfelicio.wordpress.com/2010/11/23/architecting-silverlight-lob-applications-part-6-building-an-mvvm-framework/#comments</comments>
		<pubDate>Tue, 23 Nov 2010 01:14:00 +0000</pubDate>
		<dc:creator>mfelicio</dc:creator>
				<category><![CDATA[.NET Development]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WCF RIA Services]]></category>

		<guid isPermaLink="false">https://mfelicio.wordpress.com/2010/11/23/architecting-silverlight-lob-applications-part-6/</guid>
		<description><![CDATA[Hello again! In this post I’m going to talk about building an MVVM framework. As I said in the previous post, this post should be about the OrderView. This view should allow users to pick items from a list of products, add them to the actual order, choose quantities, view the current total price and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mfelicio.wordpress.com&amp;blog=10086600&amp;post=108&amp;subd=mfelicio&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Hello again! In this post I’m going to talk about building an MVVM framework.</p>
<p>As I said in the previous post, this post should be about the OrderView. This view should allow users to pick items from a list of products, add them to the actual order, choose quantities, view the current total price and submit the order. Also the user should be able to filter, sort and do pagination on the product list. I’m sure you’ve seen enough blog posts from other people talking about this subject, that is getting the selected product, add it to another collection or create an order detail based on it, then update some other data on the UI and finally submit the changes back to the server. The thing is, everyone has its own way for programming and eventually when you end up in a team, you may find that two people coded the same thing in a different way, and one has a bug in situation A and the other has a bug in situation B. Having a good MVVM framework with a well defined methodology is a must to prevent these situations. In this post I want to talk about essential components you must have in an MVVM framework. Later, I’ll describe an MVVM Framework I’ve been working on which was based on WCF RIA Services but doesn’t really depend on it.</p>
<p>Since we’re following best practices, we know that using a good MVVM architecture we can come up with a solution whose fetching, filtering, sorting, paging logic is entirely separated from the view, allowing us to also have different views for the same view model. For example, we can start by using a DataGrid and a DataPager to display our items but later provide a new view that uses comboboxes to select the sort options, an album-like listbox to show the items and custom buttons for paging. Also, we should be able to separate all this logic from its actual data access logic to be able to use mock objects for our model and do unit tests for our viewmodels. That’s not an easy task but that’s what I want to achieve from now on.</p>
<p>Well, to start, .NET / Silverlight already offers us some classes and interfaces that are very handy for MVVM scenarios.</p>
<ul>
<li>INotifyPropertyChanged – Used to raise an event when a property changes. WPF / Silverlight Binding framework use this interface to update the view when a property changes. </li>
<li>INotifyCollectionChanged – Used to raise an event when an insert, remove, clear or replace operation has been done against a collection. WPF / Silverlight controls that have an ItemsSource property usually use this interface to create or delete visual items in a container. For example, ListBoxes display new ListBoxItems, DataGrids display new DataGridRows. </li>
<li>ICollectionView – Used to provide filter, sort descriptions, group descriptions, and item selection for an IEnumerable collection and have the view display only the filtered items, sorted according to the sort descriptions and highlight the selected item. (Has more features but these are the most relevant for the sake of this post). </li>
<li>IPagedCollectionView – Used to provide paging options to an IEnumerable collection. This is used by DataPagers mostly, that make calls to the MoveToPage(int pageIndex) method and allows us to register in the PageChanging event and fetch a new page of entities to be displayed. </li>
<li>There are other important interfaces like IEditableObject, IEditableCollectionView but I’m not going to cover those in this posts. They are used to update property values of an object in an atomic fashion. </li>
</ul>
<p><span id="more-108"></span>Unfortunately, WCF RIA Services collections do not implement ICollectionView or IPagedCollectionView so we have to provide our own mechanism for filtering, sorting and paging data. However, this is fairly easy to do with LINQ and <a href="http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression(VS.95).aspx">Expressions</a> and we can compose queries with some LINQ operators with WCF RIA Services. Silverlight has its own implementation of IPagedCollectionView, called System.Windows.Data.PagedCollectionView but it was designed to work with in-memory collections and not server-side “collections” (data sources). In this series I’m providing my own IPagedCollectionView/ICollectionView implementation which I’ve designed to work with any kind of data sources. Whatever option is used is entirely up to the Model in MVVM.
<p>So lets see how my MVVM Framework works.</p>
<p>First of, we have the model concept:</p>
<pre class="code"><span style="color:blue;">public interface </span><span style="color:#2b91af;">IDomainModel </span>: <span style="color:#2b91af;">IDisposable
</span>{
    <span style="color:blue;">void </span>RejectChanges();
    <span style="color:#2b91af;">ISubmitOperation </span>SaveChanges();
    <span style="color:#2b91af;">ISubmitOperation </span>SaveChanges(<span style="color:#2b91af;">Action</span>&lt;<span style="color:#2b91af;">ISubmitOperation</span>&gt; callback, <span style="color:blue;">object </span>userState);

    <span style="color:#2b91af;">IDomainQuery</span>&lt;T&gt; GetQuery&lt;T&gt;();

    <span style="color:blue;">void </span>Add&lt;T&gt;(T entity);
    <span style="color:blue;">void </span>Remove&lt;T&gt;(T entity);
    <span style="color:blue;">void </span>Attach&lt;T&gt;(T entity);
    <span style="color:blue;">void </span>Detach&lt;T&gt;(T entity);

    <span style="color:blue;">bool </span>HasChanges { <span style="color:blue;">get</span>; }
    <span style="color:blue;">bool </span>IsSubmitting { <span style="color:blue;">get</span>; }
    <span style="color:blue;">bool </span>IsLoading { <span style="color:blue;">get</span>; }
}</pre>
<p>If you’re familiar with the DomainContext API, you’ll find this interface very easy to understand. This model interface is supposed to provide you with basic functionality for retrieving data, change it and save it. For more specific operations, you can extend this interface, add specific operations and have your viewmodel depend on it.</p>
<p>The IDomainQuery interface represents a query against a certain entity type repository (whatever that may be). As a query, it allows you to filter, sort and page the data.</p>
<pre class="code"><span style="color:blue;">public interface </span><span style="color:#2b91af;">IDomainQuery </span>: <span style="color:#2b91af;">IDisposable
</span>{
    <span style="color:blue;">void </span>Cancel();
    <span style="color:blue;">void </span>Load();

    <span style="color:blue;">event </span><span style="color:#2b91af;">Action </span>Loading;
    <span style="color:blue;">event </span><span style="color:#2b91af;">Action</span>&lt;<span style="color:#2b91af;">ILoadOperation</span>&gt; Loaded;
    <span style="color:blue;">event </span><span style="color:#2b91af;">Action </span>Canceled;
}

<span style="color:blue;">public interface </span><span style="color:#2b91af;">IDomainQuery</span>&lt;T&gt; : <span style="color:#2b91af;">IDomainQuery
</span>{
    <span style="color:gray;">/// &lt;summary&gt;
    /// </span><span style="color:green;">Delegate that returns a lambda expression to apply in a Where operation
    </span><span style="color:gray;">/// &lt;/summary&gt;
    </span><span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">Expression</span>&lt;<span style="color:#2b91af;">Func</span>&lt;T, <span style="color:blue;">bool</span>&gt;&gt;&gt; FilterExpression { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }

    <span style="color:gray;">/// &lt;summary&gt;
    /// </span><span style="color:green;">SortDescription values that are applied in a OrderBy/ThenBy operation
    </span><span style="color:gray;">/// &lt;/summary&gt;
    </span><span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">SortDescriptionCollection</span>&gt; SortDescriptions { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }

    <span style="color:gray;">/// &lt;summary&gt;
    /// </span><span style="color:green;">Contains the required data that are applied in a Skip and Take operation
    </span><span style="color:gray;">/// &lt;/summary&gt;
    </span><span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">PageDescription</span>&gt; PageDescription { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }

    <span style="color:blue;">new event </span><span style="color:#2b91af;">Action</span>&lt;<span style="color:#2b91af;">ILoadOperation</span>&lt;T&gt;&gt; Loaded;
}

<span style="color:blue;">public sealed class </span><span style="color:#2b91af;">PageDescription
</span>{
    <span style="color:blue;">public int </span>PageSize { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
    <span style="color:blue;">public int </span>PageIndex { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
}</pre>
<p>Besides, it has events to let you know when it is has begun and completed the load operation. There are two important things to note in the IDomainQuery interface. First is the fact that the way you filter an IDomainQuery is how you filter a RIA Services EntityQuery and how you filter any IQueryable object. That means it’s very easy to do IDomainQuery implementations that query in-memory repositories or server-side repositories (note that EntityQuery doesn’t implement IQueryable and it’s not easy to integrate both concepts). The other important thing is that the filter, sort, page mechanism is based on delegates which means that whenever the query is executed/reexecuted these delegates are always reevaluated and will always reflect your viewmodel’s current state.</p>
<p>Last but not least, we have the operations. I’ve created interfaces for Load and Submit operations. I’ve implemented all these interfaces with classes that rely on WCF RIA Services. I’m not going to post the code of those classes but they’re available in the source code repository so you can take a look.</p>
<p>If you’re familiar with DomainContext your’re probably wondering where are the EntitySets and where do you manipulate collections. Well, since my IDomainModel implementation relies on WCF RIA Services, you can extend that class and manipulate your DomainContext to implement any operation that you want to make available in your extended IDomainModel. But with this framework they’re not supposed to be accessed in your viewmodel. Instead, I use my ICollectionView implementation, which I called DomainCollectionView.</p>
<pre class="code"><span style="color:blue;">public interface </span><span style="color:#2b91af;">IDomainCollectionView </span>: <span style="color:#2b91af;">ICollectionView</span>, <span style="color:#2b91af;">IPagedCollectionView</span>, <span style="color:#2b91af;">INotifyPropertyChanged
</span>{
    <span style="color:blue;">void </span>Add(<span style="color:blue;">object </span>item);
    <span style="color:blue;">void </span>Remove(<span style="color:blue;">object </span>item);
}

<span style="color:blue;">public interface </span><span style="color:#2b91af;">IDomainCollectionView</span>&lt;T&gt; : <span style="color:#2b91af;">IDomainCollectionView</span>, <span style="color:#2b91af;">IEnumerable</span>&lt;T&gt;
{
    <span style="color:blue;">void </span>Add(T item);
    <span style="color:blue;">void </span>Remove(T item);
}</pre>
<p>
  <br />The actual implementation relies on an IDomainQuery and will be a view for the results that are fetched in every operation. Since you can implement an IDomainQuery for any IEnumerable you can use this implementation for any data source.</p>
<p></p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">DomainCollectionView</span>&lt;T&gt; : <span style="color:#2b91af;">ViewModelBase</span>, <span style="color:#2b91af;">IDomainCollectionView</span>&lt;T&gt;
{
    <span style="color:blue;">private </span><span style="color:#2b91af;">IDomainQuery</span>&lt;T&gt; query;
    <span style="color:blue;">private </span><span style="color:#2b91af;">ObservableCollection</span>&lt;T&gt; sourceCollection;

    <span style="color:blue;">#region </span>DomainCollectionView Members

    <span style="color:blue;">public </span>DomainCollectionView(<span style="color:#2b91af;">IDomainQuery</span>&lt;T&gt; query, <span style="color:blue;">bool </span>usePaging = <span style="color:blue;">true</span>)
    {
        <span style="color:blue;">this</span>.query = query;
        <span style="color:blue;">this</span>.sourceCollection = <span style="color:blue;">this</span>.CreateSourceCollection();
        <span style="color:blue;">this</span>.CurrentItem = <span style="color:blue;">null</span>;
        <span style="color:blue;">this</span>.CurrentPosition = -1;

        <span style="color:green;">//Apply sort and paging
        </span>query.SortDescriptions = () =&gt; <span style="color:blue;">this</span>.SortDescriptions;
        <span style="color:blue;">if </span>(usePaging)
        {
            <span style="color:blue;">this</span>.canChangePage = <span style="color:blue;">true</span>;
            <span style="color:blue;">this</span>.pageSize = 10;<span style="color:green;">// default page size to 10
            </span>query.PageDescription = () =&gt; <span style="color:blue;">new </span><span style="color:#2b91af;">PageDescription </span>{ PageSize = <span style="color:blue;">this</span>.PageSize, PageIndex = <span style="color:blue;">this</span>.PageIndex };
        }

        query.Loaded += <span style="color:blue;">this</span>.OnDataRefreshed;
    }

    <span style="color:blue;">private void </span>OnDataRefreshed(<span style="color:#2b91af;">ILoadOperation</span>&lt;T&gt; loadOp)
    {
        <span style="color:blue;">using </span>(<span style="color:blue;">this</span>.DeferRefresh())
        {
            <span style="color:blue;">this</span>.sourceCollection.Clear();
            <span style="color:blue;">foreach </span>(<span style="color:blue;">var </span>entity <span style="color:blue;">in </span>loadOp.Entities)
                <span style="color:blue;">this</span>.sourceCollection.Add(entity);

            <span style="color:blue;">this</span>.ItemCount = loadOp.TotalEntityCount;
            <span style="color:blue;">this</span>.TotalItemCount = loadOp.TotalEntityCount;
        }
    }

    <span style="color:green;">//...
</span>}</pre>
<p>Now that I’ve introduced the model and the IDomainCollectionView, it is time we talk a bit about the viewmodel.</p>
<p>Unlike the model, viewmodels aren’t much reusable because they usually depend on the view’s needs. However, a lot of views in LOB apps have common needs: searching/listing entities, editing entities, create associations between entities. We can create viewmodels for these concepts and extend them only to implement business logic. All the infrastructure and plumbing can be centralized and reused everywhere.</p>
<p>In the next post I want to talk about how we can create base viewmodels for these concepts. But before we finish, I’ll leave just an initial thought on a base viewmodel that can be used to search/list entities.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">ListVM</span>&lt;T&gt; : <span style="color:#2b91af;">ViewModelBase</span>, <span style="color:#2b91af;">IListVM</span>&lt;T&gt;
{
    <span style="color:blue;">private </span><span style="color:#2b91af;">IDomainModel </span>model;

    <span style="color:blue;">public </span>ListVM() { }

    <span style="color:blue;">protected virtual </span><span style="color:#2b91af;">IDomainModel </span>CreateModel()
    {
        <span style="color:blue;">return </span><span style="color:#2b91af;">ServiceLocator</span>.Current.GetInstance&lt;<span style="color:#2b91af;">IDomainModel</span>&gt;();
    }

    <span style="color:blue;">public void </span>Initialize(<span style="color:#2b91af;">IListVMInitializeArgs </span>args)
    {
        <span style="color:blue;">this</span>.model = args.ExistingModel ?? <span style="color:blue;">this</span>.CreateModel();
        <span style="color:blue;">var </span>query = model.GetQuery&lt;T&gt;();
        <span style="color:blue;">this</span>.Entities = <span style="color:blue;">new </span><span style="color:#2b91af;">DomainCollectionView</span>&lt;T&gt;(query, args.RequiresPaging);
        query.Load();
    }

    <span style="color:blue;">public </span><span style="color:#2b91af;">IDomainCollectionView</span>&lt;T&gt; Entities
    {
        <span style="color:blue;">get</span>;
        <span style="color:blue;">private set</span>;
    }
}</pre>
<p>With just a few lines of code, we have a base viewmodel that can:</p>
<ul>
<li>Display results from a query that can be sorted and paged on the server. Just bind a datagrid to the Entities collection and play with it. </li>
<li>Reuse an existing model or create a new one. The current implementation can use a shared model for the whole app that is registered in the current Dependency Injection container or let a derived viewmodel decide what to do. </li>
</ul>
<p>I’ll let you think about it. In the next post I’ll dive deeper and add a lot more functionality in these viewmodels.</p>
<p>See you soon,</p>
<p>Happy coding.</p>
<br /> Tagged: <a href='http://mfelicio.wordpress.com/tag/architecture/'>Architecture</a>, <a href='http://mfelicio.wordpress.com/tag/mvvm/'>MVVM</a>, <a href='http://mfelicio.wordpress.com/tag/silverlight/'>Silverlight</a>, <a href='http://mfelicio.wordpress.com/tag/wcf-ria-services/'>WCF RIA Services</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mfelicio.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mfelicio.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mfelicio.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mfelicio.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mfelicio.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mfelicio.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mfelicio.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mfelicio.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mfelicio.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mfelicio.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mfelicio.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mfelicio.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mfelicio.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mfelicio.wordpress.com/108/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mfelicio.wordpress.com&amp;blog=10086600&amp;post=108&amp;subd=mfelicio&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mfelicio.wordpress.com/2010/11/23/architecting-silverlight-lob-applications-part-6-building-an-mvvm-framework/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2527691ac576f9358664f2ed14dd87df?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mfelicio</media:title>
		</media:content>
	</item>
		<item>
		<title>Architecting Silverlight LOB applications (Part 5) &#8211; Modules and UI composition</title>
		<link>http://mfelicio.wordpress.com/2010/10/13/architecting-silverlight-lob-applications-part-5-modules-and-ui-composition/</link>
		<comments>http://mfelicio.wordpress.com/2010/10/13/architecting-silverlight-lob-applications-part-5-modules-and-ui-composition/#comments</comments>
		<pubDate>Wed, 13 Oct 2010 12:35:00 +0000</pubDate>
		<dc:creator>mfelicio</dc:creator>
				<category><![CDATA[.NET Development]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Patterns]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">https://mfelicio.wordpress.com/2010/10/13/architecting-enterprise-lob-silverlight-applications-part-5/</guid>
		<description><![CDATA[In this fifth post and the next ones I’m going to write about client development and how to create a modular and composite silverlight application. In this post I’ll focus on UI composition. When building composite LOB silverlight apps you should be aware that modularity is an important requirement. As a developer it should be [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mfelicio.wordpress.com&amp;blog=10086600&amp;post=97&amp;subd=mfelicio&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this fifth post and the next ones I’m going to write about client development and how to create a modular and composite silverlight application. In this post I’ll focus on UI composition.</p>
<p>When building composite LOB silverlight apps you should be aware that modularity is an important requirement. As a developer it should be easier for you to mantain your code and add new features to your application without having to change the rest, plus your application’s XAP file doesn’t grow bigger. Every module is a separate XAP file, that can be downloaded on demand, depending on the user’s intent to use a certain functionallity.</p>
<p>Below is one possible architecture to achieve what we need.</p>
<p><a href="http://mfelicio.files.wordpress.com/2010/10/solution.png"><img style="display:block;float:none;margin-left:auto;margin-right:auto;border-width:0;" title="solution" src="http://mfelicio.files.wordpress.com/2010/10/solution_thumb.png?w=230&#038;h=510" border="0" alt="solution" width="230" height="510" /></a></p>
<p><span id="more-97"></span>The Shell folder contains the main xap, which I called MyApp. This xap is only responsible for downloading others and provide means for them to display its content inside the main application. The Modules folder contains 4 essential modules for the business scenario I’ve defined in a previous post. The Orders module allows non-employee users to fullfil new orders. The Sales module allows employees to view pending orders and process them. The statistics module allows employees to view charts and reports of sales evolution. Features for human resources department are accomplished by the Administration module, which also should allow application users to be created and/or managed. Modules and the Shell are compiled to MyApp.Web’s ClientBin folder.</p>
<p>The Infrastructure project is a key piece. It defines ways to communicate between modules (modules don’t reference other modules) and between the main application. In other words, it is a common contract shared by the modules. When it is defined or partially defined, module development can start. Notice that the development of the Orders module doesn’t depend on the development of the Sales module or the Statistics module, which means that different people can work on each one.</p>
<p>MyApp.Data.Silverlight is a project that should have WCF RIA Services generated code, plus other service clients which are used by modules.</p>
<p>The Server layer corresponds to the architecture I’ve defined in the first post.</p>
<p>So how does our Shell download the modules? We just need to specify a module catalog and give it to PRISM’s Bootstrapper which is responsible for initializing PRISM’s framework. Below is the module catalog I’ve defined for this scenario.</p>
<pre class="code"><span style="color:blue;">&lt;</span><span style="color:#a31515;">prism</span><span style="color:blue;">:</span><span style="color:#a31515;">ModuleCatalog </span><span style="color:red;">xmlns</span><span style="color:blue;">="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    </span><span style="color:red;">xmlns</span><span style="color:blue;">:</span><span style="color:red;">x</span><span style="color:blue;">="http://schemas.microsoft.com/winfx/2006/xaml"
    </span><span style="color:red;">xmlns</span><span style="color:blue;">:</span><span style="color:red;">sys</span><span style="color:blue;">="clr-namespace:System;assembly=mscorlib"
    </span><span style="color:red;">xmlns</span><span style="color:blue;">:</span><span style="color:red;">prism</span><span style="color:blue;">="clr-namespace:Microsoft.Practices.Composite.Modularity;assembly=Microsoft.Practices.Composite"&gt;

    &lt;</span><span style="color:#a31515;">prism</span><span style="color:blue;">:</span><span style="color:#a31515;">ModuleInfo </span><span style="color:red;">Ref</span><span style="color:blue;">="MyApp.Modules.Administration.xap"
                      </span><span style="color:red;">ModuleName</span><span style="color:blue;">="Administration"
                      </span><span style="color:red;">ModuleType</span><span style="color:blue;">="MyApp.Modules.Administration.Module, MyApp.Modules.Administration, Version=1.0.0.0"
                      </span><span style="color:red;">InitializationMode</span><span style="color:blue;">="WhenAvailable"&gt;
    &lt;/</span><span style="color:#a31515;">prism</span><span style="color:blue;">:</span><span style="color:#a31515;">ModuleInfo</span><span style="color:blue;">&gt;

    &lt;</span><span style="color:#a31515;">prism</span><span style="color:blue;">:</span><span style="color:#a31515;">ModuleInfo </span><span style="color:red;">Ref</span><span style="color:blue;">="MyApp.Modules.Statistics.xap"
                      </span><span style="color:red;">ModuleName</span><span style="color:blue;">="Statistics"
                      </span><span style="color:red;">ModuleType</span><span style="color:blue;">="MyApp.Modules.Statistics.Module, MyApp.Modules.Statistics, Version=1.0.0.0"
                      </span><span style="color:red;">InitializationMode</span><span style="color:blue;">="WhenAvailable"&gt;
    &lt;/</span><span style="color:#a31515;">prism</span><span style="color:blue;">:</span><span style="color:#a31515;">ModuleInfo</span><span style="color:blue;">&gt;

    &lt;</span><span style="color:#a31515;">prism</span><span style="color:blue;">:</span><span style="color:#a31515;">ModuleInfo </span><span style="color:red;">Ref</span><span style="color:blue;">="MyApp.Modules.Sales.xap"
                      </span><span style="color:red;">ModuleName</span><span style="color:blue;">="Sales"
                      </span><span style="color:red;">ModuleType</span><span style="color:blue;">="MyApp.Modules.Sales.Module, MyApp.Modules.Sales, Version=1.0.0.0"
                      </span><span style="color:red;">InitializationMode</span><span style="color:blue;">="WhenAvailable"&gt;
    &lt;/</span><span style="color:#a31515;">prism</span><span style="color:blue;">:</span><span style="color:#a31515;">ModuleInfo</span><span style="color:blue;">&gt;

    &lt;</span><span style="color:#a31515;">prism</span><span style="color:blue;">:</span><span style="color:#a31515;">ModuleInfo </span><span style="color:red;">Ref</span><span style="color:blue;">="MyApp.Modules.Orders.xap"
                      </span><span style="color:red;">ModuleName</span><span style="color:blue;">="Orders"
                      </span><span style="color:red;">ModuleType</span><span style="color:blue;">="MyApp.Modules.Orders.Module, MyApp.Modules.Orders, Version=1.0.0.0"
                      </span><span style="color:red;">InitializationMode</span><span style="color:blue;">="WhenAvailable"&gt;
    &lt;/</span><span style="color:#a31515;">prism</span><span style="color:blue;">:</span><span style="color:#a31515;">ModuleInfo</span><span style="color:blue;">&gt;
&lt;/</span><span style="color:#a31515;">prism</span><span style="color:blue;">:</span><span style="color:#a31515;">ModuleCatalog</span><span style="color:blue;">&gt;
</span></pre>
<p>Notice the InitializationMode attributes. It allows us to specify wether the modules should be downloaded as soon as possible or on demand. For now, I want my modules to download as soon as possible but later I’ll show effective techniques to download them on demand. However, that doesn’t affect the way I build them.</p>
<p>To start, our Shell can have a top bar displaying a hello message, a menu on the left and a region where modules can display its content.</p>
<pre class="code">    <span style="color:blue;">&lt;</span><span style="color:#a31515;">Border </span><span style="color:red;">BorderThickness</span><span style="color:blue;">="5" </span><span style="color:red;">CornerRadius</span><span style="color:blue;">="10"&gt;
        &lt;</span><span style="color:#a31515;">tlk</span><span style="color:blue;">:</span><span style="color:#a31515;">DockPanel </span><span style="color:red;">LastChildFill</span><span style="color:blue;">="True"&gt;
            &lt;</span><span style="color:#a31515;">shellWelcome</span><span style="color:blue;">:</span><span style="color:#a31515;">WelcomeBar </span><span style="color:red;">tlk</span><span style="color:blue;">:</span><span style="color:red;">DockPanel.Dock</span><span style="color:blue;">="Top" </span><span style="color:red;">Margin</span><span style="color:blue;">="5"/&gt;
            &lt;</span><span style="color:#a31515;">shellMenu</span><span style="color:blue;">:</span><span style="color:#a31515;">Menu </span><span style="color:red;">tlk</span><span style="color:blue;">:</span><span style="color:red;">DockPanel.Dock</span><span style="color:blue;">="Left" </span><span style="color:red;">VerticalAlignment</span><span style="color:blue;">="Stretch" </span><span style="color:red;">Margin</span><span style="color:blue;">="5,0,5,5"/&gt;
            &lt;</span><span style="color:#a31515;">shellContainer</span><span style="color:blue;">:</span><span style="color:#a31515;">MainContainer </span><span style="color:red;">Margin</span><span style="color:blue;">="0,0,5,5"/&gt;
        &lt;/</span><span style="color:#a31515;">tlk</span><span style="color:blue;">:</span><span style="color:#a31515;">DockPanel</span><span style="color:blue;">&gt;
    &lt;/</span><span style="color:#a31515;">Border</span><span style="color:blue;">&gt;
</span></pre>
<p>The visual result is something like this:</p>
<p><a href="http://mfelicio.files.wordpress.com/2010/10/shell.png"><img style="display:block;float:none;margin-left:auto;margin-right:auto;border-width:0;" title="shell" src="http://mfelicio.files.wordpress.com/2010/10/shell_thumb.png?w=492&#038;h=254" border="0" alt="shell" width="492" height="254" /></a> <a href="http://11011.net/software/vspaste"></a></p>
<p>I’d like the menu and the main container to be dynamic, in other words, have its content set dinamically by modules instead of being defined in the controls itself.</p>
<p>We could create an interface like IMenu, implemented by our Menu’s viewmodel and use it by modules to display content. While that seems to be a decoupled aproach because your modules can display its content without depending on the menu control itself, it is actually coupled to the object that will implement the IMenu interface. That means that if you want to display your menu options in other places, like a toolbar or a ribbon bar, you will need another interface to interact with those controls. A solution to this problem is to use a message publisher/subscriber technique relying on a mediator object, that is PRISM’s EventAggregator. Now what you do is publishing a message saying “I want to display this menu option” and which ever control that is interested in showing menu options subscribes that message and acts accordingly. Lets see how we can do that:</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">MenuOptionMessage </span>: <span style="color:#2b91af;">CompositePresentationEvent</span>&lt;<span style="color:#2b91af;">MenuOptionMessageArgs</span>&gt; { }

<span style="color:blue;">public class </span><span style="color:#2b91af;">MenuOptionMessageArgs
</span>{
    <span style="color:blue;">public </span><span style="color:#2b91af;">ICommand </span>Command { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
    <span style="color:blue;">public string </span>Text { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
    <span style="color:blue;">public string </span>ImageSourceUri { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }

    <span style="color:blue;">public string </span>Group { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The MenuOptionMessage is a PRISM event whose payload is a MenuOptionMessageArgs message. So whenever you want to publish a MenuOptionMessage you create a MenuOptionMessageArgs and tell the EventAggregator to broadcast it to every subscriber. The EventAggregator can be accessed through dependency injection or the IoC container. I usually create a simple utility class to keep the code cleaner:</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">Messenger
</span>{
    <span style="color:blue;">public static </span>T Get&lt;T&gt;()
        <span style="color:blue;">where </span>T : <span style="color:#2b91af;">EventBase
    </span>{
        <span style="color:blue;">var </span>ev = <span style="color:#2b91af;">ServiceLocator</span>.Current.GetInstance&lt;<span style="color:#2b91af;">IEventAggregator</span>&gt;();
        <span style="color:blue;">return </span>ev.GetEvent&lt;T&gt;();
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Now we can have our modules publish MenuOptionMessages.</p>
<p>Order Module initialization:</p>
<pre class="code"><span style="color:#2b91af;">Messenger</span>.Get&lt;<span style="color:#2b91af;">MenuOptionMessage</span>&gt;().Publish(<span style="color:blue;">new </span><span style="color:#2b91af;">MenuOptionMessageArgs
</span>{
    Command = <span style="color:#2b91af;">Commands</span>.NewOrderCommand,
    Text = <span style="color:#a31515;">"Create New Order"</span>,
    Group = <span style="color:#a31515;">"Orders"
</span>});
<span style="color:#2b91af;">Messenger</span>.Get&lt;<span style="color:#2b91af;">MenuOptionMessage</span>&gt;().Publish(<span style="color:blue;">new </span><span style="color:#2b91af;">MenuOptionMessageArgs
</span>{
    Command = <span style="color:#2b91af;">Commands</span>.ViewOrdersCommand,
    Text = <span style="color:#a31515;">"View Orders"</span>,
    Group = <span style="color:#a31515;">"Orders"
</span>});</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Sales module initialization:</p>
<pre class="code"><span style="color:#2b91af;">Messenger</span>.Get&lt;<span style="color:#2b91af;">MenuOptionMessage</span>&gt;().Publish(<span style="color:blue;">new </span><span style="color:#2b91af;">MenuOptionMessageArgs
</span>{
    Command = <span style="color:#2b91af;">Commands</span>.ViewPendingOrdersCommand,
    Text = <span style="color:#a31515;">"Pending Orders"</span>,
    Group = <span style="color:#a31515;">"Sales"
</span>});
<span style="color:#2b91af;">Messenger</span>.Get&lt;<span style="color:#2b91af;">MenuOptionMessage</span>&gt;().Publish(<span style="color:blue;">new </span><span style="color:#2b91af;">MenuOptionMessageArgs
</span>{
    Command = <span style="color:#2b91af;">Commands</span>.ViewProcessedOrdersCommand,
    Text = <span style="color:#a31515;">"Processed Orders"</span>,
    Group = <span style="color:#a31515;">"Sales"
</span>});</pre>
<p>The Menu control displays every command grouped by its Group and creates an expander for each Group. You can access the source code to confirm that.</p>
<p>Now what we need to do is have our commands display views.</p>
<p>PRISM has a region concept, where you define regions within your Shell, give them a name and then your modules inject views into those regions by specifying the name. I’m no fan of this feature because it creates tight coupling between views and regions. Besides this means that your screen logic only works with PRISM. I usually use a different approach, which allows us to also use PRISM regions but other UI frameworks as well. Besides, it is not that hard to build your own UI framework, if you keep it simple. For example, instead of thinking on regions, think about view positions.</p>
<pre class="code"><span style="color:blue;">public enum </span><span style="color:#2b91af;">ViewPosition
</span>{
    Left,
    Right,
    Top,
    Bottom,
    Center,
    Floating
}</pre>
<p><span style="font-family:Verdana;">Using the same technique we did for the Menu, whenever we want to display a view, we simply have to publish a message where we specify the position and the view itself and whoever is responsible to display that view in the specified position should subscribe the message and act accordingly. These messages should be defined in the Infastructure assembly. Lets see how the message is defined:</span></p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">CreateViewMessage </span>: <span style="color:#2b91af;">CompositePresentationEvent</span>&lt;<span style="color:#2b91af;">CreateViewMessageArgs</span>&gt; { }

<span style="color:blue;">public class </span><span style="color:#2b91af;">CreateViewMessageArgs
</span>{
    <span style="color:blue;">public </span><span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">object</span>&gt; View { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
    <span style="color:blue;">public </span><span style="color:#2b91af;">ViewPosition </span>Position { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
    <span style="color:blue;">public string </span>Title { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; } <span style="color:green;">//optional
</span>}</pre>
<p><a href="http://11011.net/software/vspaste"></a>Notice the Lazy object there. That allows you to have your view created by the subscriber instead of being created by the publisher. That allows you to use different threads when publishing/subscribing, although in this case the subscriber should use the UI thread.</p>
<p>Below is an example of how to publish a CreateViewMessage from the Order module.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">Commands
</span>{
    <span style="color:blue;">public static </span><span style="color:#2b91af;">ICommand </span>NewOrderCommand = <span style="color:blue;">new </span><span style="color:#2b91af;">ActionCommand</span>(<span style="color:#2b91af;">Commands</span>.NewOrder);
    <span style="color:blue;">public static </span><span style="color:#2b91af;">ICommand </span>ViewOrdersCommand = <span style="color:blue;">new </span><span style="color:#2b91af;">ActionCommand</span>(<span style="color:#2b91af;">Commands</span>.ViewOrders);

    <span style="color:blue;">private static void </span>NewOrder()
    {
        <span style="color:#2b91af;">Messenger</span>.Get&lt;<span style="color:#2b91af;">CreateViewMessage</span>&gt;().Publish(<span style="color:blue;">new </span><span style="color:#2b91af;">CreateViewMessageArgs
        </span>{
            View = <span style="color:blue;">new </span><span style="color:#2b91af;">Lazy</span>&lt;<span style="color:blue;">object</span>&gt;(() =&gt; <span style="color:#2b91af;">ServiceLocator</span>.Current.GetInstance&lt;<span style="color:#2b91af;">OrderView</span>&gt;()),
            Position = <span style="color:#2b91af;">ViewPosition</span>.Center,
            Title = <span style="color:#a31515;">"New Order"
        </span>});
    }

    <span style="color:blue;">private static void </span>ViewOrders()
    {
        <span style="color:green;">//to be implemented
    </span>}
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>Notice the OrderView being created by the ServiceLocator to allow dependency injection, if needed.</p>
<p>The MainContainer control is responsible for subscribing this message and display the view inside a tab control.</p>
<pre class="code"><span style="color:blue;">public partial class </span><span style="color:#2b91af;">MainContainer </span>: <span style="color:#2b91af;">UserControl
</span>{
    <span style="color:blue;">public </span>MainContainer()
    {
        InitializeComponent();
        <span style="color:blue;">if </span>(<span style="color:#2b91af;">DesignerProperties</span>.IsInDesignTool)
            <span style="color:blue;">return</span>;

        <span style="color:#2b91af;">Messenger</span>.Get&lt;<span style="color:#2b91af;">CreateViewMessage</span>&gt;().Subscribe(<span style="color:blue;">this</span>.HandleCreateView, <span style="color:#2b91af;">ThreadOption</span>.UIThread, <span style="color:blue;">true</span>, <span style="color:blue;">this</span>.CanHandleCreateView);
    }

    <span style="color:blue;">private bool </span>CanHandleCreateView(<span style="color:#2b91af;">CreateViewMessageArgs </span>args)
    {
        <span style="color:blue;">return </span>args.Position == <span style="color:#2b91af;">ViewPosition</span>.Center;
    }

    <span style="color:blue;">private void </span>HandleCreateView(<span style="color:#2b91af;">CreateViewMessageArgs </span>args)
    {
        <span style="color:blue;">this</span>.tabCtrl.Items.Add(<span style="color:blue;">new </span><span style="color:#2b91af;">TabItem
        </span>{
            Header = args.Title, Content = args.View.Value,
            VerticalContentAlignment = System.Windows.<span style="color:#2b91af;">VerticalAlignment</span>.Stretch,
            HorizontalContentAlignment = System.Windows.<span style="color:#2b91af;">HorizontalAlignment</span>.Stretch
        });
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>When you subscribe a message you can specify a predicate that tells the publish mechanism wether you really want to handle that message. In this case, the main container only wants to handle CreateViewMessages that have views to be displayed in the Center position. I could have another component subscribing the CreateViewMessage and display views inside windows whenever the position is Floating. The ThreadOption parameter is also important. Every message that deals with UI should be subscribed in the UI Thread. If you want to plug in a logger to subscribe/log messages you don’t need to subscribe on the UI thread. In that case you should use a background thread.</p>
<p>This is a very simple aproach on how to do UI composition which works and is very effective. The source code repository has been updated as well.</p>
<p>In the next post I will focus on viewmodels and how we can build the OrderView.</p>
<pre class="code"> </pre>
<br /> Tagged: <a href='http://mfelicio.wordpress.com/tag/architecture/'>Architecture</a>, <a href='http://mfelicio.wordpress.com/tag/patterns/'>Patterns</a>, <a href='http://mfelicio.wordpress.com/tag/silverlight/'>Silverlight</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mfelicio.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mfelicio.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mfelicio.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mfelicio.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mfelicio.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mfelicio.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mfelicio.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mfelicio.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mfelicio.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mfelicio.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mfelicio.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mfelicio.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mfelicio.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mfelicio.wordpress.com/97/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mfelicio.wordpress.com&amp;blog=10086600&amp;post=97&amp;subd=mfelicio&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mfelicio.wordpress.com/2010/10/13/architecting-silverlight-lob-applications-part-5-modules-and-ui-composition/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2527691ac576f9358664f2ed14dd87df?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mfelicio</media:title>
		</media:content>

		<media:content url="http://mfelicio.files.wordpress.com/2010/10/solution_thumb.png" medium="image">
			<media:title type="html">solution</media:title>
		</media:content>

		<media:content url="http://mfelicio.files.wordpress.com/2010/10/shell_thumb.png" medium="image">
			<media:title type="html">shell</media:title>
		</media:content>
	</item>
		<item>
		<title>Architecting Silverlight LOB applications (Part 4) &#8211; Metadata and localization</title>
		<link>http://mfelicio.wordpress.com/2010/09/15/architecting-silverlight-lob-applications-part-4-metadata-and-localization/</link>
		<comments>http://mfelicio.wordpress.com/2010/09/15/architecting-silverlight-lob-applications-part-4-metadata-and-localization/#comments</comments>
		<pubDate>Wed, 15 Sep 2010 23:28:00 +0000</pubDate>
		<dc:creator>mfelicio</dc:creator>
				<category><![CDATA[.NET Development]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[WCF RIA Services]]></category>

		<guid isPermaLink="false">https://mfelicio.wordpress.com/2010/09/15/architecting-enterprise-lob-silverlight-applications-part-4/</guid>
		<description><![CDATA[Specifying metadata for our entities is the easy part and here is a good place to start localizing our app. First what we have to do is create a buddy class as described in the following example: [MetadataType(typeof(Customer.CustomerMetadata))] public partial class Customer { internal class CustomerMetadata { [Display(ResourceType = typeof(Metadata), Name = "MyApp_Customer_Number")] public int [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mfelicio.wordpress.com&amp;blog=10086600&amp;post=91&amp;subd=mfelicio&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Specifying metadata for our entities is the easy part and here is a good place to start localizing our app.</p>
<p>First what we have to do is create a buddy class as described in the following example:</p>
<pre class="code">[<span style="color:#2b91af;">MetadataType</span>(<span style="color:blue;">typeof</span>(<span style="color:#2b91af;">Customer</span>.<span style="color:#2b91af;">CustomerMetadata</span>))]
<span style="color:blue;">public partial class </span><span style="color:#2b91af;">Customer
</span>{
    <span style="color:blue;">internal class </span><span style="color:#2b91af;">CustomerMetadata
    </span>{
        [<span style="color:#2b91af;">Display</span>(ResourceType = <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">Metadata</span>), Name = <span style="color:#a31515;">"MyApp_Customer_Number"</span>)]
        <span style="color:blue;">public int </span>Number;

        [<span style="color:#2b91af;">Display</span>(ResourceType = <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">Metadata</span>), Name = <span style="color:#a31515;">"CommonProperties_Email"</span>)]
        <span style="color:blue;">public string </span>Email;

        [<span style="color:#2b91af;">Include</span>]
        <span style="color:blue;">public </span><span style="color:#2b91af;">EntityCollection</span>&lt;<span style="color:#2b91af;">Order</span>&gt; Orders;
    }
}</pre>
<pre class="code">[<span style="color:#2b91af;">MetadataType</span>(<span style="color:blue;">typeof</span>(<span style="color:#2b91af;">Employee</span>.<span style="color:#2b91af;">EmployeeMetadata</span>))]
<span style="color:blue;">public partial class </span><span style="color:#2b91af;">Employee
</span>{
    <span style="color:blue;">internal class </span><span style="color:#2b91af;">EmployeeMetadata
    </span>{
        [<span style="color:#2b91af;">Display</span>(ResourceType = <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">Metadata</span>), Name = <span style="color:#a31515;">"CommonProperties_Name"</span>)]
        [<span style="color:#2b91af;">StringLength</span>(128, ErrorMessageResourceType = <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">Metadata</span>), ErrorMessageResourceName = <span style="color:#a31515;">"CommonErrors_StringLength"</span>)]
        <span style="color:blue;">public string </span>Name;

        [<span style="color:#2b91af;">Display</span>(ResourceType = <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">Metadata</span>), Name = <span style="color:#a31515;">"CommonProperties_Email"</span>)]
        <span style="color:blue;">public string </span>Email;

        [<span style="color:#2b91af;">Include</span>]
        <span style="color:blue;">public </span><span style="color:#2b91af;">Department </span>Department;
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>The DisplayAttribute attribute is very useful, as it annotates your properties with information that can be consumed in various ways. For example, when using your entity in a Datagrid, the cell headers will automatically look up for DisplayAttributes and retrieve the localized string for that property. The same applies for labels in a Dataform and if you want to create your own UI framework, you can leverage this type of annotation to start localizing your app. Notice how I’ve reused some resource names for common properties like Email. The same could have been done for Number and Name, but that really depends on each case.</p>
<p>You can place validation rules on your properties as well using attributes like StringLength, apply regular expressions or even create your own custom validation rules. The great part about this is that those rules will be available in the client as well. The DomainService makes sure that before executing operations on entities all the validation rules are applied. Note that you can’t do all kinds of validation on your entities using metadata. Some validations may require connecting to a database, transactions, etc, and such information isn’t available in this type of validation context. I recommend that such validations are performed after DomainService’s ExecuteChangeSet is invoked and right before the PersistChangeSet method.</p>
<p>More on metadata specification can be found in the documentation or other resources on the web. I just want to focus on a different aspect that not many people tend to write about. That is sharing the Resources in the client and the server. The client project will not compile if the ResourceManager Metadata isn’t available. Since it is defined on the server, you should follow these steps in order to enable it on the client:</p>
<ul>
<li>Add the resource files as a link to the client project</li>
<li>Change your client project’s default namespace to the same namespace that is defined in the server project that holds the resource files</li>
<li>Change the client project’s .csproj where it references the linked Designer.cs file and add these lines of code:
<ul>
<blockquote><p>&lt;Compile Include=&#8221;..\..\..\Server\Data\MyApp.Data\<span style="color:#ff0000;">Resources</span>\Metadata.Designer.cs&#8221;&gt;</p>
<p>      <strong>&lt;AutoGen&gt;True&lt;/AutoGen&gt;</strong>      &lt;Link&gt;<span style="color:#ff0000;">Resources</span>\Metadata.Designer.cs&lt;/Link&gt;</p>
<p>      &lt;DesignTime&gt;True&lt;/DesignTime&gt;</p>
<p>      &lt;DependentUpon&gt;Metadata.resx&lt;/DependentUpon&gt;</p>
<p>&lt;/Compile&gt;</p></blockquote>
</ul>
</li>
<li>Make sure the resource files have the same relative path in the client project as in the server project. In this case, I’ve created a Resources folder in both projects.</li>
<li>Also make sure that the resource file has Public marked as its Access Modifier.</li>
</ul>
<p>These steps are necessary because adding linked files for dependent files, like Medatata.resx / Metadata.Designer.cs won’t automatically mark them as dependent, so you need to do it manually.</p>
<p>Now you should be able to compile your application and start taking advantage of metadata in your entities.</p>
<p>To finish, I’d like to say that all the code is available at <a href="http://code.google.com/p/mfelicio-wordpress/source/browse/#svn/trunk/2010/SL-MVVM-RIA">http://code.google.com/p/mfelicio-wordpress</a> under trunk/2010/SL-MVVM-RIA. I’m sorry for the delay on this one.</p>
<p>Next posts will be covering client development.</p>
<p><a href="http://11011.net/software/vspaste"> </a></p>
<br /> Tagged: <a href='http://mfelicio.wordpress.com/tag/silverlight/'>Silverlight</a>, <a href='http://mfelicio.wordpress.com/tag/tips/'>Tips</a>, <a href='http://mfelicio.wordpress.com/tag/wcf-ria-services/'>WCF RIA Services</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mfelicio.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mfelicio.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mfelicio.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mfelicio.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mfelicio.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mfelicio.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mfelicio.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mfelicio.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mfelicio.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mfelicio.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mfelicio.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mfelicio.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mfelicio.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mfelicio.wordpress.com/91/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mfelicio.wordpress.com&amp;blog=10086600&amp;post=91&amp;subd=mfelicio&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mfelicio.wordpress.com/2010/09/15/architecting-silverlight-lob-applications-part-4-metadata-and-localization/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2527691ac576f9358664f2ed14dd87df?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mfelicio</media:title>
		</media:content>
	</item>
		<item>
		<title>Architecting Silverlight LOB applications (Part 3) &#8211; DomainServices and Repository</title>
		<link>http://mfelicio.wordpress.com/2010/08/17/architecting-silverlight-lob-applications-part-3-domainservices-and-repository/</link>
		<comments>http://mfelicio.wordpress.com/2010/08/17/architecting-silverlight-lob-applications-part-3-domainservices-and-repository/#comments</comments>
		<pubDate>Tue, 17 Aug 2010 09:37:00 +0000</pubDate>
		<dc:creator>mfelicio</dc:creator>
				<category><![CDATA[.NET Development]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[EntityFramework]]></category>
		<category><![CDATA[Patterns]]></category>
		<category><![CDATA[WCF RIA Services]]></category>

		<guid isPermaLink="false">https://mfelicio.wordpress.com/2010/08/17/architecting-enterprise-lob-silverlight-applications-part-3/</guid>
		<description><![CDATA[Hello again, In the previous post I described an overview of an architecture that could be used when developing silverlight modular apps. In this post I’ll start with a simple business domain model and create a domain layer around that model. In this example our app will be a web application for a company that [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mfelicio.wordpress.com&amp;blog=10086600&amp;post=87&amp;subd=mfelicio&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Hello again,</p>
<p>In the previous post I described an overview of an architecture that could be used when developing silverlight modular apps. In this post I’ll start with a simple business domain model and create a domain layer around that model.</p>
<p>In this example our app will be a web application for a company that sells products and that can be used by its customers to fulfill orders and its employees to process them. These orders have details which consist of products and quantities. Each product can have a product category. When a customer submits an order fulfillment, an employee of the company may process that order to prepare the items for shipping.</p>
<p>The company has a few departments, and each employee belongs to a department. This means that employees from the Sales department will be to process orders; employees from the Human Resources department will be able to recruit new employees; and employees from the Financial Department will be able to watch some charts and print reports with statistics of how sales are evolving as time goes by, sales reports, etc.</p>
<p><span id="more-87"></span></p>
<p>Authentication and authorization will be added in the future.</p>
<p>For the sake of simplicity, I’ve create the following data model.</p>
<p><a href="http://mfelicio.files.wordpress.com/2010/08/model.png"><img style="display:inline;border-width:0;" title="model" src="http://mfelicio.files.wordpress.com/2010/08/model_thumb.png?w=806&#038;h=596" border="0" alt="model" width="806" height="596" /></a></p>
<p>This model will be both our data model and domain model. It is very simple and as I said in the previous post, creating a separate domain model is optional because you can still do fine with your data entities. Since we’re using Entity Framework we’ll take advantage of LinqToEntitiesDomainService, a specific Domain Service that deals with EF’s objects.</p>
<p>Since we’re starting with our Domain layer, we’ll define a Domain Service that can be used from our Silverlight app (or other clients as well) and create the CRUD operations. I’m sure you have noticed how much (duplicated) code is generated when you use the Domain Service template from Visual Studio. Well.. suffer no more! Just create a base class for your domain services and add the following methods:</p>
<pre class="code"><span style="color:blue;">#region </span>Basic CRUD
<span style="color:blue;">protected </span><span style="color:#2b91af;">IQueryable</span>&lt;T&gt; GetQuery&lt;T&gt;()
    <span style="color:blue;">where </span>T : <span style="color:blue;">class
</span>{
    <span style="color:blue;">return this</span>.GetRepository&lt;T&gt;().GetQuery();
}
<span style="color:blue;">protected void </span>Insert&lt;T&gt;(T entity)
    <span style="color:blue;">where </span>T : <span style="color:blue;">class
</span>{
    <span style="color:blue;">this</span>.GetRepository&lt;T&gt;().Add(entity);
}
<span style="color:blue;">protected void </span>Update&lt;T&gt;(T entity)
    <span style="color:blue;">where </span>T : <span style="color:blue;">class
</span>{
    <span style="color:blue;">this</span>.GetRepository&lt;T&gt;().AttachAsModified(entity, <span style="color:blue;">this</span>.ChangeSet.GetOriginal(entity));
}
<span style="color:blue;">protected void </span>Delete&lt;T&gt;(T entity)
    <span style="color:blue;">where </span>T : <span style="color:blue;">class
</span>{
    <span style="color:blue;">this</span>.GetRepository&lt;T&gt;().Delete(entity);
}
<span style="color:blue;">#endregion

protected </span><span style="color:#2b91af;">IRepository</span>&lt;T&gt; GetRepository&lt;T&gt;()
    <span style="color:blue;">where </span>T : <span style="color:blue;">class
</span>{
    <span style="color:blue;">return this</span>.Container.Resolve&lt;<span style="color:#2b91af;">IRepository</span>&lt;T&gt;&gt;();
}</pre>
<p>The Container property is an IUnityContainer instance, that I keep on the base Domain Service. I usually have a common singleton class where the IoC container is available but I also create a child container for each Domain Service. That allows me to register specific instances in the child container and use it only within the scope of my Domain Service. This is useful for resolving repositories because my repositories depend on the ObjectContext which gets injected via dependency injection. This is how it’s done:</p>
<pre class="code"><span style="color:blue;">public abstract class </span><span style="color:#2b91af;">DomainRepositoryService</span>&lt;TContext&gt; : <span style="color:#2b91af;">LinqToEntitiesDomainService</span>&lt;TContext&gt;, <span style="color:#2b91af;">IDbContextManager
    </span><span style="color:blue;">where </span>TContext : <span style="color:#2b91af;">ObjectContext</span>, <span style="color:#2b91af;">IDbContext</span>, <span style="color:blue;">new</span>()
{
    <span style="color:blue;">protected </span><span style="color:#2b91af;">IUnityContainer </span>Container { <span style="color:blue;">get</span>; <span style="color:blue;">private set</span>; }
    <span style="color:gray;">/// &lt;summary&gt;
    /// </span><span style="color:green;">Create a child container to use THIS as the IDbContextManager implementation when resolving repositories
    </span><span style="color:gray;">/// </span><span style="color:green;">Ensures that other threads / domain services can use the main container to resolve repositories
    </span><span style="color:gray;">/// </span><span style="color:green;">and use its own instance as the IDbContextManager for the repositories they need
    </span><span style="color:gray;">/// &lt;/summary&gt;
    /// &lt;param name="context"&gt;</span><span style="color:green;">The DomainServiceContext instance</span><span style="color:gray;">&lt;/param&gt;
    </span><span style="color:blue;">public override void </span>Initialize(<span style="color:#2b91af;">DomainServiceContext </span>context)
    {
        <span style="color:blue;">base</span>.Initialize(context);

        <span style="color:blue;">this</span>.Container = <span style="color:#2b91af;">IoC</span>.Current.Container.CreateChildContainer();
        <span style="color:blue;">this</span>.Container.RegisterInstance&lt;<span style="color:#2b91af;">IDbContextManager</span>&gt;(<span style="color:blue;">this</span>);
    }

    <span style="color:blue;">#region </span>IDbContextManager Members
    <span style="color:blue;">public </span><span style="color:#2b91af;">IDbContext </span>GetDbContext()
    {
        <span style="color:blue;">return this</span>.ObjectContext;
    }
    <span style="color:blue;">#endregion
    </span><span style="color:green;">//...
</span>}</pre>
<p>That said, the specific Domain Service for our Silverlight app will look like this:</p>
<pre class="code">[<span style="color:#2b91af;">EnableClientAccess</span>()]
<span style="color:blue;">public class </span><span style="color:#2b91af;">MyAppService </span>: <span style="color:#2b91af;">DomainRepositoryService</span>&lt;<span style="color:#2b91af;">MyAppEntities</span>&gt;
{
    <span style="color:blue;">#region </span>Customer
    <span style="color:blue;">public </span><span style="color:#2b91af;">IQueryable</span>&lt;<span style="color:#2b91af;">Customer</span>&gt; GetCustomers()
    {
        <span style="color:blue;">return base</span>.GetQuery&lt;<span style="color:#2b91af;">Customer</span>&gt;();
    }
    <span style="color:blue;">public void </span>InsertCustomer(<span style="color:#2b91af;">Customer </span>entity)
    {
        <span style="color:blue;">base</span>.Insert(entity);
    }
    <span style="color:blue;">public void </span>UpdateCustomer(<span style="color:#2b91af;">Customer </span>entity)
    {
        <span style="color:blue;">base</span>.Update(entity);
    }
    <span style="color:blue;">public void </span>DeleteCustomer(<span style="color:#2b91af;">Customer </span>entity)
    {
        <span style="color:blue;">base</span>.Delete(entity);
    }
    <span style="color:blue;">#endregion
    </span><span style="color:green;">//repeat for the other entities...
</span>}</pre>
<p class="code">Notice how my Domain Layer doesn’t really care how entities are stored or managed with EF. It simply delegates that responsability to an object that implements the IRepository interface.</p>
<p class="code">This interface can be generic and often looks like:</p>
<pre class="code"><span style="color:blue;">public interface </span><span style="color:#2b91af;">IRepository</span>&lt;TEntity&gt;
    <span style="color:blue;">where </span>TEntity : <span style="color:blue;">class
</span>{
    TEntity GetEntity(<span style="color:blue;">int </span>id);
    <span style="color:#2b91af;">IQueryable</span>&lt;TEntity&gt; GetQuery();
    <span style="color:blue;">void </span>Add(TEntity entity);
    <span style="color:blue;">void </span>Update(TEntity entity);
    <span style="color:blue;">void </span>Delete(TEntity entity);
    <span style="color:gray;">/// &lt;summary&gt;
    /// </span><span style="color:green;">Abstraction on RIA's AttachAsModified extension method
    </span><span style="color:gray;">/// &lt;/summary&gt;
    /// &lt;param name="current"&gt;&lt;/param&gt;
    /// &lt;param name="original"&gt;&lt;/param&gt;
    </span><span style="color:blue;">void </span>AttachAsModified(TEntity current, TEntity original = <span style="color:blue;">null</span>);
}</pre>
<p><a href="http://11011.net/software/vspaste"></a>For simplicity I’ve included the AttachAsModified method in the IRepository. This method is important because RIA requires that the current entity being updated be attached in the ObjectContext.  Another option would be to create a separate interface that derives from IRepository and add the method there. That’s because the IRepository interface is a generic concept that can be used with many data access technologies.</p>
<p>Note that from the moment you create your Domain Service and expose your entities, imediately another person/team can start building the app using the exposed entities, while another team keeps working on the server layer adding metadata and/or validation logic which will also be available to the client application.</p>
<p>In the next post I’ll cover the metadata specification for our entities and that should be enough for our server-side layer, so far.</p>
<br /> Tagged: <a href='http://mfelicio.wordpress.com/tag/architecture/'>Architecture</a>, <a href='http://mfelicio.wordpress.com/tag/entityframework/'>EntityFramework</a>, <a href='http://mfelicio.wordpress.com/tag/patterns/'>Patterns</a>, <a href='http://mfelicio.wordpress.com/tag/wcf-ria-services/'>WCF RIA Services</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mfelicio.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mfelicio.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mfelicio.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mfelicio.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mfelicio.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mfelicio.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mfelicio.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mfelicio.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mfelicio.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mfelicio.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mfelicio.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mfelicio.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mfelicio.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mfelicio.wordpress.com/87/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mfelicio.wordpress.com&amp;blog=10086600&amp;post=87&amp;subd=mfelicio&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mfelicio.wordpress.com/2010/08/17/architecting-silverlight-lob-applications-part-3-domainservices-and-repository/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2527691ac576f9358664f2ed14dd87df?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mfelicio</media:title>
		</media:content>

		<media:content url="http://mfelicio.files.wordpress.com/2010/08/model_thumb.png" medium="image">
			<media:title type="html">model</media:title>
		</media:content>
	</item>
		<item>
		<title>Architecting Silverlight LOB applications (Part 2) &#8211; Architecture overview</title>
		<link>http://mfelicio.wordpress.com/2010/05/24/architecting-silverlight-lob-applications-part-2-architecture-overview/</link>
		<comments>http://mfelicio.wordpress.com/2010/05/24/architecting-silverlight-lob-applications-part-2-architecture-overview/#comments</comments>
		<pubDate>Mon, 24 May 2010 22:57:00 +0000</pubDate>
		<dc:creator>mfelicio</dc:creator>
				<category><![CDATA[.NET Development]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">https://mfelicio.wordpress.com/2010/05/24/architecting-enterprise-lob-silverlight-applications-part-2/</guid>
		<description><![CDATA[Continuing our series, I’d like to present an architecture that I’ve been working on and can be used in Silverlight LOB apps that are developed using DDD (Domain Driven Development) and have N-layers. The following picture describes how an application can be layered into multiple Modules, all hosted within regions of a Shell. These modules [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mfelicio.wordpress.com&amp;blog=10086600&amp;post=83&amp;subd=mfelicio&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Continuing our series, I’d like to present an architecture that I’ve been working on and can be used in Silverlight LOB apps that are developed using DDD (<strong>Domain Driven Development</strong>) and have N-layers.</p>
<p>The following picture describes how an application can be layered into multiple <strong>Modules</strong>, all hosted within regions of a <strong>Shell</strong>. These modules can communicate with each other through well defined messages and contracts defined in the module <strong>Infrastructure</strong> layer. Furthermore, they retrieve and manipulate data objects through WCF Services that are suited for DDD (called WCF RIA Services). These data objects are often called entities and can represent your <strong>Domain Model </strong>and are persisted in a data store using <strong>Data Access Objects</strong> that abstract both the data store and the data access technology you’re using. <strong>WCF RIA Services</strong> provides ways for you to manipulate your entities in the client similarly as you would do in the server when it comes to querying, changing data and submitting changes.</p>
<p><a href="http://mfelicio.files.wordpress.com/2010/05/overview.png"><img style="display:block;float:none;margin-left:auto;margin-right:auto;border:0;" title="overview" src="http://mfelicio.files.wordpress.com/2010/05/overview_thumb.png?w=595&#038;h=874" border="0" alt="overview" width="595" height="874" /></a></p>
<p>Such application often relies on server-side infrastructure for authentication and authorization, logging and error management. At the client-side they rely on frameworks that help reduce, harmonize and reuse code in module development both at the presentation logic and at the presentation views. Some layers may have components that depend on components from other layers. In such cases, we reduce these dependencies with <strong>IoC containers</strong> or similar frameworks like <strong>MEF</strong>.</p>
<p>Developing in an N-layered architecture can be troublesome when you want to reuse code that has to be specified both at server-side and at client-side when it comes to validation or other business logic. WCF RIA Services relies on metadata that describes entities how entities are defined, validated and how they behave with each other. Although this technique is very effective, there are related problems that aren’t noticed until you actually hit them and I’ll try to identify and address some of them.</p>
<p>Notice the mapping layer between the Data entities and the Domain entities. This layer is “optional” and can be useful when you don’t want to expose your data entities as your domain model. This helps achieve persistence ignorance and also allows you to create simple and lightweight classes to transport data. For simplicity, I’m not going to use this layer in the upcoming posts, so my data entities will be my domain entities.</p>
<p>In the following posts I’ll be building an app that respects these layers and will evolve over time. I’ll also build a simple framework aimed for MVVM development to show how effective this pattern can be.</p>
<p>Never soon enough, but see you soon.</p>
<br /> Tagged: <a href='http://mfelicio.wordpress.com/tag/architecture/'>Architecture</a>, <a href='http://mfelicio.wordpress.com/tag/silverlight/'>Silverlight</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mfelicio.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mfelicio.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mfelicio.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mfelicio.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mfelicio.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mfelicio.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mfelicio.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mfelicio.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mfelicio.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mfelicio.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mfelicio.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mfelicio.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mfelicio.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mfelicio.wordpress.com/83/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mfelicio.wordpress.com&amp;blog=10086600&amp;post=83&amp;subd=mfelicio&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mfelicio.wordpress.com/2010/05/24/architecting-silverlight-lob-applications-part-2-architecture-overview/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2527691ac576f9358664f2ed14dd87df?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mfelicio</media:title>
		</media:content>

		<media:content url="http://mfelicio.files.wordpress.com/2010/05/overview_thumb.png" medium="image">
			<media:title type="html">overview</media:title>
		</media:content>
	</item>
		<item>
		<title>Architecting Silverlight LOB applications (Part 1) &#8211; Concepts and technologies</title>
		<link>http://mfelicio.wordpress.com/2010/04/26/architecting-silverlight-lob-applications-part-1-concepts-and-technologies/</link>
		<comments>http://mfelicio.wordpress.com/2010/04/26/architecting-silverlight-lob-applications-part-1-concepts-and-technologies/#comments</comments>
		<pubDate>Mon, 26 Apr 2010 22:00:00 +0000</pubDate>
		<dc:creator>mfelicio</dc:creator>
				<category><![CDATA[.NET Development]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Patterns]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">https://mfelicio.wordpress.com/2010/04/26/architecting-enterprise-lob-silverlight-applications-part-1/</guid>
		<description><![CDATA[In this first part of the series I’ll focus on some open source projects in Microsoft’s Patterns &#38; Practices and other technologies that are available and can help us achieve our goal. First we have PRISM (Composite Application Guidance for WPF and Silverlight). PRISM is composed of a guidance and a set of libraries that [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mfelicio.wordpress.com&amp;blog=10086600&amp;post=76&amp;subd=mfelicio&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this first part of the series I’ll focus on some open source projects in Microsoft’s Patterns &amp; Practices and other technologies that are available and can help us achieve our goal.</p>
<p>First we have <strong>PRISM</strong> (Composite Application Guidance for WPF and Silverlight). PRISM is composed of a guidance and a set of libraries that are designed to help you more easily build modular WPF and Silverlight apps. It also has built-in components that let you take advantage of some known patterns like MVVM, Event Aggregator and Dependency Injection. There are others but I’ll focus on these three because I find them to be the most useful.</p>
<p><a href="http://mfelicio.files.wordpress.com/2010/04/prism.png"><img style="display:block;float:none;margin-left:auto;margin-right:auto;border-width:0;" title="prism" src="http://mfelicio.files.wordpress.com/2010/04/prism_thumb.png?w=445&#038;h=392" border="0" alt="prism" width="445" height="392" /></a></p>
<p>PRISM applies to client development. I think the best feature PRISM provides is the ability to specify your application modules (XAPs in Silverlight) as a catalog and load them on demand. We’ll explore this in detail in other parts of this series when we create a module catalog to be used within the application.</p>
<p><strong>Dependency injection</strong> (a specific usage of the Inversion of Control concept) is a prime technique for building loosely coupled applications because it provides ways to handle dependencies between objects. It helps you build testable code because you can easily switch concrete implementations which your objects depend on. PRISM is built using this design principle and it uses the Unity container, which implements the DI technique. PRISM also lets you use other DI containers but I’ll focus on Unity since I haven’t enough experience with others.</p>
<p>This pattern can be applied in both client and server development.</p>
<p>I didn’t find a nice and simple figure about Dependency Injection so I’ll link to <a href="http://mfelicio.wordpress.com/2010/02/07/managing-the-entity-framework-objectcontext-instance-lifetime-in-wcf-and-sharing-it-among-repositories/">this post</a> where I’ve used this technique in a WCF Service (OrderService) which used an IOrderRepository implemented by the OrderRepository class which had dependencies being injected in its constructor.</p>
<p>The <strong>MVVM</strong> pattern is becoming the alpha and the omega when building WPF and Silverlight apps. It helps you separate concerns when designing your presentation layer and if it is well thought you can create a great set of reusable code for your application and even reuse it for other applications.</p>
<p><a href="http://www.nikhilk.net/Why-ViewModel.aspx"><img style="display:block;float:none;margin-left:auto;margin-right:auto;border:0;" title="mvvm" src="http://mfelicio.files.wordpress.com/2010/04/mvvm1.png?w=699&#038;h=178" border="0" alt="mvvm" width="699" height="178" /></a></p>
<p>With MVVM you basically think of your view as a set of classes and properties and not as a set of UI controls. This allows you to easily switch your UI while keeping the same logic that it is bound to, and at the same time enables testability. Plus it allows you to reuse a set of UI logic in lots of views with less effort. This pattern is applied to client development.</p>
<p>The <strong>Event Aggregator</strong> pattern allows you to build your app with an Event Driven Architecture where components communicate with each other in a decoupled manner. It provides a way to publish and subscribe to events without knowing who is subscribing or who is publishing. The only thing you need to know is the event you are publishing or subscribing and how to react to that event. Usually modules do not depend on each other and using events as contracts to communicate between them is a good approach. This pattern applies to client development.</p>
<p>Next we’ll focus on server development.</p>
<p>Client-server communication in Silverlight has been enforced and recommended to use web services. Since we are building LOB applications it makes sense to use services that are good to deal with data. <strong>WCF services</strong> sure are good but are they ideal? What’s the cost of maintaining a complete service layer that lets us expose CRUD operations on our data and also provides us the ability to do other queries (like get products by productType), or other business operations? How many times have we done this? And how many times have we done this for different applications? How about validation of the data on the server and client side? How about proxy generation? How about the amount of data sent to the wire just to change a DateTime value on the database?</p>
<p>We all know Visual Studio’s generated code is ugly as hell and maintaining client-side complete service agents can be troublesome, because you usually need to keep it synchronized with your service contract. In Silverlight it is slightly more complicated to share an assembly with service and data contracts than WPF, because of type incompatibilities. Also we usually like our client-side data contracts to implement INotifyPropertyChanged and use ObservableCollections so we take advantage of data binding but at the server we really do not care about this.</p>
<p><strong>WCF RIA Services</strong> aims to solve all these problems and many others.. I’ll skip the “all the things RIA Services can do part”, and <a href="http://msdn.microsoft.com/en-us/library/ee707344(VS.91).aspx">point you to the right place</a> if you still don’t know. The most important features we’ll explore are query composition, data validation, change tracking, unit of work, among others.</p>
<p><a href="http://mfelicio.files.wordpress.com/2010/04/riaservices.png"><img style="display:block;float:none;margin-left:auto;margin-right:auto;border-width:0;" title="riaservices" src="http://mfelicio.files.wordpress.com/2010/04/riaservices_thumb.png?w=549&#038;h=231" border="0" alt="riaservices" width="549" height="231" /></a></p>
<p>I’ve been using RIA Services for the last 7 months and one thing I find very useful is that the way you communicate either with the server and with your model (at the client side) is through a very well defined API which makes it easy to create very generic code that can be used to create reusable viewmodels. This is especially useful when you have multiple persons working in the same project and you want to ensure that everyone will code the same way (I will definitely explore this in later posts).</p>
<p>WCF RIA Services current release is the RC2, it has a go live license, so we’re good to go.</p>
<p>This doesn’t mean you shouldn’t use WCF as well. There are cases where WCF RIA Services isn’t well suited to work for. For example, file uploading or downloading. In this situation it’s preferable that you create a WCF Service or an HttpHandler to deal with this particular case.</p>
<p>For our data layer the best options nowadays are still <strong>NHibernate</strong> (using Linq to NHibernate) or<strong> Entity Framework</strong>. Nevertheless, we should encapsulate our data access through repository objects and do not use our data access technology directly in our services. I’ve got a very <a href="http://mfelicio.wordpress.com/2010/01/11/encapsulating-entity-access-in-entityframework-by-using-the-repository-pattern/">simple post</a> that talks exactly about this. In this case, we can use any or both. RIA Services generates code on the client based on reflection and other metadata that is applied in our server side entities. If you use Entity Framework with RIA Services it already has a specific metadata provider that is able to understand relationships between entities and generate them correctly in the client. If you wish to use NHibernate you will have to specify additional metadata in your entities. For simplicity I’ll use Entity Framework. There are other resources on the web that explains how to use NHibernate.</p>
<p>Last but not least, I’d like to talk about <strong>MEF</strong>. MEF stands for<strong> </strong><a href="http://mef.codeplex.com/"><span style="text-decoration:underline;">Managed Extensibility Framework</span></a>, has been shipped with .NET 4 (SL4 also) and is designed to help us compose our apps in a decoupled way much easier than using an IoC container for dependency injection. You simply annotate your classes with Import/Export attributes and MEF will resolve dependencies between objects for you. Of course there’s more we can do. You can provide metadata when exporting an object and import only objects that follow some criteria. MEF can be used to download XAP’s when an Import must be satisfied and the exported object is in another XAP, which helps building modular apps. It is said that the new Prism version will use MEF for its modularity features, which makes it even more interesting.</p>
<p>In the next post I will start with a simple business scenario and follow a top-down approach by designing an architecture built upon these technologies. I haven’t had much time lately but I’m trying to catch up so see you soon!</p>
<br /> Tagged: <a href='http://mfelicio.wordpress.com/tag/architecture/'>Architecture</a>, <a href='http://mfelicio.wordpress.com/tag/patterns/'>Patterns</a>, <a href='http://mfelicio.wordpress.com/tag/silverlight/'>Silverlight</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mfelicio.wordpress.com/76/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mfelicio.wordpress.com/76/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mfelicio.wordpress.com/76/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mfelicio.wordpress.com/76/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mfelicio.wordpress.com/76/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mfelicio.wordpress.com/76/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mfelicio.wordpress.com/76/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mfelicio.wordpress.com/76/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mfelicio.wordpress.com/76/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mfelicio.wordpress.com/76/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mfelicio.wordpress.com/76/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mfelicio.wordpress.com/76/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mfelicio.wordpress.com/76/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mfelicio.wordpress.com/76/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mfelicio.wordpress.com&amp;blog=10086600&amp;post=76&amp;subd=mfelicio&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mfelicio.wordpress.com/2010/04/26/architecting-silverlight-lob-applications-part-1-concepts-and-technologies/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2527691ac576f9358664f2ed14dd87df?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mfelicio</media:title>
		</media:content>

		<media:content url="http://mfelicio.files.wordpress.com/2010/04/prism_thumb.png" medium="image">
			<media:title type="html">prism</media:title>
		</media:content>

		<media:content url="http://mfelicio.files.wordpress.com/2010/04/mvvm1.png" medium="image">
			<media:title type="html">mvvm</media:title>
		</media:content>

		<media:content url="http://mfelicio.files.wordpress.com/2010/04/riaservices_thumb.png" medium="image">
			<media:title type="html">riaservices</media:title>
		</media:content>
	</item>
		<item>
		<title>Architecting Silverlight LOB applications</title>
		<link>http://mfelicio.wordpress.com/2010/03/20/architecting-silverlight-lob-applications/</link>
		<comments>http://mfelicio.wordpress.com/2010/03/20/architecting-silverlight-lob-applications/#comments</comments>
		<pubDate>Sat, 20 Mar 2010 18:24:00 +0000</pubDate>
		<dc:creator>mfelicio</dc:creator>
				<category><![CDATA[.NET Development]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Patterns]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://mfelicio.wordpress.com/2010/03/20/architecting-enterprise-lob-silverlight-applications/</guid>
		<description><![CDATA[This post is an introduction to a series of posts that I will be doing about how we can architect an enterprise data-centric Silverlight application. While Silverlight is a powerful platform to create great interactive user experiences for Web, Desktop (and now) Mobile, it is also Microsoft’s best bet to create a multi-platform, cross-browser technology. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mfelicio.wordpress.com&amp;blog=10086600&amp;post=68&amp;subd=mfelicio&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This post is an introduction to a series of posts that I will be doing about how we can architect an enterprise data-centric Silverlight application. While Silverlight is a powerful platform to create great interactive user experiences for Web, Desktop (and now) Mobile, it is also Microsoft’s best bet to create a multi-platform, cross-browser technology.</p>
<p>A lot of people think of Silverlight as just another Adobe Flash rival because of the RIA aspects both technologies offer and the strong multimedia support that Silverlight has. While this is true, we can get much more from Silverlight if we think of it as good technology for the software industry in Information Technologies. IT projects are all about manipulation, visualization and understanding data.</p>
<p>Silverlight, which is a subset of WPF (excellent to deal with data through data binding) and still a .NET application, when combined with today’s most popular patterns and some key technologies for software engineering, can be a very productive, straight-forward, reliable and successful technology to build this kind of applications, and at the same time, provide great UX.</p>
<p>In this series of posts I will try to cover key aspects when you are architecting an application that can start small, are meant to last for years and over time evolve into a bigger application due to new requirements and be developed by multiple teams without resulting in a big mess of code that no one ever wants to touch.</p>
<p>Such applications often are built using the following principles:</p>
<ul>
<li>Separation of Concerns
<ul>
<li>The most important principle. Ability to divide and conquer by creating layers in your application that are meant to deal with a specific problem, task or functionality, thus reducing complexity. The rest of the principles are all based on this one.</li>
</ul>
</li>
<li>Loosely coupling
<ul>
<li>Ability to create multiple components that can work together but do not depend on each other.</li>
</ul>
</li>
<li>Flexibility
<ul>
<li>Ability to respond to future changes, either by completely switching the underlying technology or business needs.</li>
</ul>
</li>
<li>Extensibility
<ul>
<li>Ability to create new functionality by extending or reusing existing one.</li>
</ul>
</li>
<li>Modularity
<ul>
<li>Ability to create well defined (cohesion) independent business areas in your application that can be evolved separately, integrate with each other and even be deployed separately.</li>
</ul>
</li>
<li>Testability
<ul>
<li>Ability to avoid/prevent unexpected bugs by changes or new functionality you make, by testing your application’s logic, behavior or dependencies.</li>
</ul>
</li>
<li>Maintainable
<ul>
<li>Ability to quickly find the code you need to change, understand it and change it, even if the one who wrote it in the first place is not around anymore (happens frequently).</li>
</ul>
</li>
<li>Reutilization
<ul>
<li>Ability to reduce code by creating components that will be reused by other components that require a specific functionality.</li>
</ul>
</li>
<li>UI Independence
<ul>
<li>Ability to switch your presentation controls without breaking neither your presentation logic nor your application logic.</li>
</ul>
</li>
<li>Localization
<ul>
<li>Ability to target multiple languages, thus increasing your range of customers.</li>
</ul>
</li>
</ul>
<p>I’m thinking in starting with an overall architecture, choose the right technologies, build a small application on top of it and then keep composing it. I’ll start with .NET 3.5 and later on move to .NET 4.</p>
<p>See you soon!</p>
<br /> Tagged: <a href='http://mfelicio.wordpress.com/tag/architecture/'>Architecture</a>, <a href='http://mfelicio.wordpress.com/tag/patterns/'>Patterns</a>, <a href='http://mfelicio.wordpress.com/tag/silverlight/'>Silverlight</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mfelicio.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mfelicio.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mfelicio.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mfelicio.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mfelicio.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mfelicio.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mfelicio.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mfelicio.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mfelicio.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mfelicio.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mfelicio.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mfelicio.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mfelicio.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mfelicio.wordpress.com/68/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mfelicio.wordpress.com&amp;blog=10086600&amp;post=68&amp;subd=mfelicio&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mfelicio.wordpress.com/2010/03/20/architecting-silverlight-lob-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2527691ac576f9358664f2ed14dd87df?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mfelicio</media:title>
		</media:content>
	</item>
		<item>
		<title>Silverlight for Windows Phone 7 and Symbian sooner than we think?</title>
		<link>http://mfelicio.wordpress.com/2010/03/15/silverlight-for-windows-phone-7-and-symbian-sooner-than-we-think/</link>
		<comments>http://mfelicio.wordpress.com/2010/03/15/silverlight-for-windows-phone-7-and-symbian-sooner-than-we-think/#comments</comments>
		<pubDate>Mon, 15 Mar 2010 21:09:26 +0000</pubDate>
		<dc:creator>mfelicio</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[Mobile]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://mfelicio.wordpress.com/?p=63</guid>
		<description><![CDATA[While MIX10 is taking place, it is expected that Microsoft anounces a Silverlight beta release along with developer tools for Symbian (running on Nokia S60 5th Edition platform, source) and also for Windows Phone 7 series. I&#8217;ve been developing web app&#8217;s since I&#8217;ve started my career but I had the chance to develop some mobile app&#8217;s [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mfelicio.wordpress.com&amp;blog=10086600&amp;post=63&amp;subd=mfelicio&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>While <a title="MIX10" href="http://live.visitmix.com/" target="_blank">MIX10</a> is taking place, it is expected that Microsoft anounces a Silverlight beta release along with developer tools for Symbian (running on Nokia S60 5th Edition platform, <a title="source" href="http://blogs.zdnet.com/microsoft/?p=5550" target="_blank">source</a>) and also for Windows Phone 7 series.</p>
<p>I&#8217;ve been developing web app&#8217;s since I&#8217;ve started my career but I had the chance to develop some mobile app&#8217;s as well, and I gotta tell you, for me developing for mobile devices is very challenging and much more interesting than web app&#8217;s. </p>
<p>I really enjoy .NET Compact Framework but when you want to do some cool UX stuff it&#8217;s a pain in the butt.</p>
<p>Last couple of years I&#8217;ve been working mostly with Silverlight/WPF and I&#8217;ve been waiting for a Silverlight release for Windows Mobile 7 (now called Windows Phone 7 series) for a long time.</p>
<p>I can&#8217;t wait until I start developing for mobile devices with Silverlight, and now being able to target Symbian devices as well it feels like the cherry on top of the cake.</p>
<p>On a side note, I&#8217;ll be attending Microsoft&#8217;s technology event in Portugal, Techdays 2010 on 20th,21st,22nd of April, and I&#8217;ll be most interested on Architecture, Web/UX, Mobility and Cloud sessions. I hope everyone has a chance to participate!</p>
<br /> Tagged: <a href='http://mfelicio.wordpress.com/tag/mobile/'>Mobile</a>, <a href='http://mfelicio.wordpress.com/tag/silverlight/'>Silverlight</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mfelicio.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mfelicio.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mfelicio.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mfelicio.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mfelicio.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mfelicio.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mfelicio.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mfelicio.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mfelicio.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mfelicio.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mfelicio.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mfelicio.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mfelicio.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mfelicio.wordpress.com/63/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mfelicio.wordpress.com&amp;blog=10086600&amp;post=63&amp;subd=mfelicio&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mfelicio.wordpress.com/2010/03/15/silverlight-for-windows-phone-7-and-symbian-sooner-than-we-think/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2527691ac576f9358664f2ed14dd87df?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mfelicio</media:title>
		</media:content>
	</item>
		<item>
		<title>Source-code used in this blog is now available</title>
		<link>http://mfelicio.wordpress.com/2010/03/10/source-code-for-this-blog-is-now-available/</link>
		<comments>http://mfelicio.wordpress.com/2010/03/10/source-code-for-this-blog-is-now-available/#comments</comments>
		<pubDate>Wed, 10 Mar 2010 23:44:19 +0000</pubDate>
		<dc:creator>mfelicio</dc:creator>
				<category><![CDATA[Blog Management]]></category>

		<guid isPermaLink="false">http://mfelicio.wordpress.com/?p=60</guid>
		<description><![CDATA[Hi everyone, I&#8217;ve just created a project at google.code to host the source-code of examples in this blog. Check it out at https://code.google.com/p/mfelicio-wordpress/ I use Tortoise to access the SVN repository. As I keep posting I will be updating the sources at google.code. If anyone has trouble accessing it I will be willing to help.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mfelicio.wordpress.com&amp;blog=10086600&amp;post=60&amp;subd=mfelicio&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Hi everyone,</p>
<p>I&#8217;ve just created a project at google.code to host the source-code of examples in this blog.</p>
<p>Check it out at <a href="https://code.google.com/p/mfelicio-wordpress/">https://code.google.com/p/mfelicio-wordpress/</a></p>
<p>I use Tortoise to access the SVN repository.</p>
<p>As I keep posting I will be updating the sources at google.code.</p>
<p>If anyone has trouble accessing it I will be willing to help.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mfelicio.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mfelicio.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mfelicio.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mfelicio.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mfelicio.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mfelicio.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mfelicio.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mfelicio.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mfelicio.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mfelicio.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mfelicio.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mfelicio.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mfelicio.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mfelicio.wordpress.com/60/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mfelicio.wordpress.com&amp;blog=10086600&amp;post=60&amp;subd=mfelicio&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mfelicio.wordpress.com/2010/03/10/source-code-for-this-blog-is-now-available/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2527691ac576f9358664f2ed14dd87df?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mfelicio</media:title>
		</media:content>
	</item>
		<item>
		<title>Resolving wcf service instances with an IoC container</title>
		<link>http://mfelicio.wordpress.com/2010/02/07/resolving-wcf-service-instances-with-an-ioc-container/</link>
		<comments>http://mfelicio.wordpress.com/2010/02/07/resolving-wcf-service-instances-with-an-ioc-container/#comments</comments>
		<pubDate>Sun, 07 Feb 2010 02:14:06 +0000</pubDate>
		<dc:creator>mfelicio</dc:creator>
				<category><![CDATA[.NET Development]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://mfelicio.wordpress.com/2010/02/07/resolving-wcf-service-instances-with-an-ioc-container/</guid>
		<description><![CDATA[In wcf, services are created and disposed by the wcf runtime through an IInstanceProvider implementation. The default implementation calls the parameterless constructor of the service. The easiest way to provide our own IInstanceProvider is to add a behavior to our service host by using an IServiceBehavior. We can achieve our goal as simple as this: [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mfelicio.wordpress.com&amp;blog=10086600&amp;post=56&amp;subd=mfelicio&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In wcf, services are created and disposed by the wcf runtime through an IInstanceProvider implementation. The default implementation calls the parameterless constructor of the service. The easiest way to provide our own IInstanceProvider is to add a behavior to our service host by using an IServiceBehavior.</p>
<p>We can achieve our goal as simple as this:</p>
<pre class="code"><span style="color:blue;">public sealed class </span><span style="color:#2b91af;">IoCInstanceProvider </span>: <span style="color:#2b91af;">IInstanceProvider
</span>{
    <span style="color:blue;">private readonly </span><span style="color:#2b91af;">Type </span>serviceType;

    <span style="color:blue;">public </span>IoCInstanceProvider(<span style="color:#2b91af;">Type </span>serviceType)
    {
        <span style="color:blue;">this</span>.serviceType = serviceType;
    }

    <span style="color:blue;">public object </span>GetInstance(<span style="color:#2b91af;">InstanceContext </span>instanceContext)
    {
        <span style="color:blue;">return </span>GetInstance(instanceContext, <span style="color:blue;">null</span>);
    }
    <span style="color:blue;">public object </span>GetInstance(<span style="color:#2b91af;">InstanceContext </span>instanceContext, <span style="color:#2b91af;">Message </span>message)
    {
        <span style="color:blue;">return </span><span style="color:#2b91af;">IoC</span>.Current.Container.Resolve(<span style="color:blue;">this</span>.serviceType);
    }
    <span style="color:blue;">public void </span>ReleaseInstance(System.ServiceModel.<span style="color:#2b91af;">InstanceContext </span>instanceContext, <span style="color:blue;">object </span>instance)
    {
        <span style="color:blue;">if </span>(instance <span style="color:blue;">is </span><span style="color:#2b91af;">IDisposable</span>)
            (instance <span style="color:blue;">as </span><span style="color:#2b91af;">IDisposable</span>).Dispose();
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a>The IoC class is just a singleton I use that exposes an Inversion of Control container like Unity.</p>
<p><span id="more-56"></span></p>
<p>The IoCInstanceProvider can be used in an existing service by applying an IServiceBehavior to that service through its ServiceHost. The following class shows how we can do this:</p>
<pre class="code"><span style="color:blue;">public sealed class </span><span style="color:#2b91af;">IoCServiceHostBehavior </span>: <span style="color:#2b91af;">IServiceBehavior
</span>{
    <span style="color:blue;">public void </span>ApplyDispatchBehavior(<span style="color:#2b91af;">ServiceDescription </span>serviceDescription, <span style="color:#2b91af;">ServiceHostBase </span>serviceHostBase)
    {
        <span style="color:blue;">foreach </span>(<span style="color:blue;">var </span>channelDispatcherBase <span style="color:blue;">in </span>serviceHostBase.ChannelDispatchers)
        {
            <span style="color:blue;">var </span>channelDispatcher = channelDispatcherBase <span style="color:blue;">as </span><span style="color:#2b91af;">ChannelDispatcher</span>;
            <span style="color:blue;">if </span>(channelDispatcher != <span style="color:blue;">null</span>)
            {
                <span style="color:blue;">foreach </span>(<span style="color:blue;">var </span>endpointDispatcher <span style="color:blue;">in </span>channelDispatcher.Endpoints)
                {
                    endpointDispatcher.DispatchRuntime
                                      .InstanceProvider = <span style="color:blue;">new </span><span style="color:#2b91af;">IoCInstanceProvider</span>(serviceDescription.ServiceType);
                }
            }
        }
    }
    <span style="color:blue;">public void </span>AddBindingParameters(<span style="color:#2b91af;">ServiceDescription </span>serviceDescription, <span style="color:#2b91af;">ServiceHostBase </span>serviceHostBase, <span style="color:#2b91af;">Collection</span>&lt;<span style="color:#2b91af;">ServiceEndpoint</span>&gt; endpoints, <span style="color:#2b91af;">BindingParameterCollection </span>bindingParameters)
    {

    }
    <span style="color:blue;">public void </span>Validate(<span style="color:#2b91af;">ServiceDescription </span>serviceDescription, <span style="color:#2b91af;">ServiceHostBase </span>serviceHostBase)
    {

    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The ApplyDispatchBehavior method ensures that for every endpoint provided by the service host for a given serviceDescription, the InstanceProvider used to create the service by the wcf runtime is our own IoCInstanceProvider.</p>
<p>Now we create our own ServiceHost class and make sure we add this behavior before the service host gets opened (if we don’t, the behavior will not get applied).</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">IoCServiceHost </span>: <span style="color:#2b91af;">ServiceHost
</span>{
    <span style="color:blue;">public </span>IoCServiceHost(<span style="color:#2b91af;">Type </span>svcType, <span style="color:blue;">params </span><span style="color:#2b91af;">Uri</span>[] baseAddresses)
        : <span style="color:blue;">base</span>(svcType, baseAddresses) { }

    <span style="color:blue;">public </span>IoCServiceHost(<span style="color:blue;">object </span>singletonInstance, <span style="color:blue;">params </span><span style="color:#2b91af;">Uri</span>[] baseAddresses)
        : <span style="color:blue;">base</span>(singletonInstance, baseAddresses) { }

    <span style="color:blue;">protected override void </span>OnOpening()
    {
        <span style="color:blue;">this</span>.Description.Behaviors.Add(<span style="color:blue;">new </span><span style="color:#2b91af;">IoCServiceHostBehavior</span>());
        <span style="color:blue;">base</span>.OnOpening();
    }
}</pre>
<p>In my previous post, I used an example where I had a wcf service that used the Repository pattern with EntityFramework to query data instead of using the ObjectContext directly. I kept a parameterless constructor in the service and commented the constructor that should be used if I could have my service be resolved by the IoC container. Following the guidance of this post we can finally use that constructor and throw away the parameterless one.</p>
<pre class="code">[<span style="color:#2b91af;">DbContextBehavior</span>]
<span style="color:blue;">public class </span><span style="color:#2b91af;">OrderService </span>: <span style="color:#2b91af;">IOrderService
</span>{
    <span style="color:blue;">private readonly </span><span style="color:#2b91af;">IOrderRepository </span>orderRepository;
    <span style="color:green;">//not used anymore
    //public OrderService()
    //{
    //    this.orderRepository = IoC.Current.Container.Resolve&lt;IOrderRepository&gt;();
    //}
    </span><span style="color:blue;">public </span>OrderService(<span style="color:#2b91af;">IOrderRepository </span>repository)
    {
        <span style="color:blue;">this</span>.orderRepository = repository;
    }
    <span style="color:green;">//..
</span>}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>If we want to host our service in a console application we can simply do this:</p>
<pre class="code"><span style="color:blue;">var </span>host = <span style="color:blue;">new </span><span style="color:#2b91af;">IoCServiceHost</span>(<span style="color:blue;">typeof</span>(<span style="color:#2b91af;">OrderService</span>));
host.Open();
<span style="color:green;">//wait for calls...
</span>host.Close();</pre>
<p>If we’re hosting it in an asp.net environment and have an .svc file we need to edit the asp markup file and specify a ServiceHostFactory class in the Factory attribute. The following code shows how we can write a ServiceHostFactory class uses our IoCServiceHost:</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">IoCServiceHostFactory </span>: <span style="color:#2b91af;">ServiceHostFactory
</span>{
    <span style="color:blue;">protected override </span><span style="color:#2b91af;">ServiceHost </span>CreateServiceHost(<span style="color:#2b91af;">Type </span>serviceType, <span style="color:#2b91af;">Uri</span>[] baseAddresses)
    {
        <span style="color:blue;">return new </span><span style="color:#2b91af;">IoCServiceHost</span>(serviceType, baseAddresses);
    }
}</pre>
<p>I’ve used this approach in several projects (professional and academic) and I’m very happy with the results. Being able to have my services be resolved with an IoC container helps me mantain/evolve my services in many different ways and always keep my code as clean and decoupled as possible. I hope you can take benefits from this technique too.</p>
<br /> Tagged: <a href='http://mfelicio.wordpress.com/tag/wcf/'>WCF</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mfelicio.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mfelicio.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mfelicio.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mfelicio.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mfelicio.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mfelicio.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mfelicio.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mfelicio.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mfelicio.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mfelicio.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mfelicio.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mfelicio.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mfelicio.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mfelicio.wordpress.com/56/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mfelicio.wordpress.com&amp;blog=10086600&amp;post=56&amp;subd=mfelicio&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mfelicio.wordpress.com/2010/02/07/resolving-wcf-service-instances-with-an-ioc-container/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2527691ac576f9358664f2ed14dd87df?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mfelicio</media:title>
		</media:content>
	</item>
	</channel>
</rss>
