Showing posts with label design patterns. Show all posts
Showing posts with label design patterns. Show all posts

Thursday, October 21, 2010

Why Use the MVVM Pattern with Silverlight Applications?

The probability of hearing or reading about the title question of this article if you are either a Silverlight or WPF developer is substantial. However, there are significant problems when searching for a proper answer to this question.

To begin with, there are numerous and varied ways in implementing methodologies like MVVM, most of which are used based on personal preference. To a novice trying to educate themselves, this leads to disparity in information. Complicating this factor is that many of the articles or videos that attempt to describe the MVVM pattern also include components of other architectural patterns. This adds unnecessary complexity to understanding the MVVM pattern because of the inconsistencies in the pattern being described. In this article, I will elucidate only the MVVM pattern - nothing more, nothing less.

First of all, let me answer the title question succinctly. Silverlight (XAML) and the Model-View-ViewModel (MVVM) architecture evolved together, thereby affecting each other. In effect, this means that inherent in Silverlight's framework elements and CLR objects are the mechanisms to implement MVVM's loose coupling and separation of concerns. I will go into greater detail on the specific classes and objects in .NET that are primarily involved in hooking everything up further on in this article.

The loose coupling and separation of concerns translates to the ability of large developer teams to work independently on different parts, bringing the pieces together at runtime utilizing classes or object interfaces (as opposed to user interfaces). Another enormous benefit of this is that not only can multiple developers work on different parts of the application simultaneously, designers - for the first time in the history of .NET development - and developers can work on the same code at the same time. Having designers "speaking the same language" as developers solves the longstanding dilemma of a developer taking what the designer gives them and having to rewrite everything to work with the applications. Furthermore, designers - for the first time also - can see what they are doing with data driven controls in the design view in Expression Blend. It's evident that the workflow between professional graphic designers and application developers has been monumentally improved.

Let me back up a bit and give an overview of what MVVM is and does for those of you who aren't familiar with it. MVVM, as architecture, is the mature, successful version of what n-tier attempted to accomplish: quarantine the user interface from the program logic and data. Where Model-View-Controller (MVC) may sufficiently accomplish this goal for ASP.NET applications, MVVM is a refined evolution custom-fit for Silverlight.

There have been intermediate patterns between n-tier and MVVM, all with the same goal, but none of them truly accomplishing the objective until the advent of MVVM and XAML. XAML, being an extension of XML, is inherently tool-able, resulting in the ease of building visual and other editors for those who use it.

If a new Silverlight developer were to dive into a new project without knowing better, they might attempt to put all logic into the codebehind of the MainPage.xaml.cs, as typically has been done in ASP.NET pages. Not only would this lead to difficult testing scenarios, but this methodology doesn't lend itself to long-term maintainability or extensibility. Testing code built like this needs a user interface (UI) to run and a human to debug, which adds to the complexity of finding errors. On the other hand, by using the MVVM architecture, only the "ViewModel" (which will be explained in the next couple of paragraphs) need be tested and verified before ever being bound to the UI.

Properly using MVVM, there is much less codebehind in MainPage.xaml. This is simply pure UI. Each entity in MVVM has its unique tasks, and they do them extremely well with complete separation. MVVM is an acronym for Model-View-ViewModel; let's elaborate on the functionalities of each entity.

At the uppermost level we have the "View". Ideally, the view consists only of the XAML UI and related UI logic. These are the Silverlight screens that are presented to the user. The View's responsibilities are to present data to end users and collect data from end users, period.
At the lowest level we have the "Model". This represents the entities that live on the server as well as the objects that are responsible for interacting with the data stores the application uses along with data persistence. Data interaction in Silverlight can be anything from RIA Services to web services or raw XML. Any CLR-object can be the binding source.

In between these two entities is the "ViewModel". This entity's responsibilities are numerous, but can be summarized as aggregating data that will be bound to the View, retrieved from the Model. This includes methods and states. Since Silverlight doesn't databind to methods, just properties and dependency properties, most of our data logic needs to be in property setters and getters in this ViewModel.

As previously promised, now I'll explain the specific objects in the .NET Framework that are involved in making MVVM and Silverlight work together. The binding mechanism in Silverlight links the View and ViewModel through primarily dependency properties and data context. Each framework element in the View (controls, UI elements, etc.) has a dependency property. These properties can be bound to instances of exposed public properties in the ViewModel. The ViewModel can update the View via the INotifyPropertyChanged interface in the ViewModel base, which is used to discover if the value of the properties have changed by raising the OnPropertyChanged event. This is a two-way conversation that extracts all of the data and logic from the View, but doesn't alter the UI's normal functionalities.

Lastly, I'd like to describe one last tremendous benefit of utilizing this pattern. Because all the logic is in the ViewModel, this entity can be copied from a Silverlight application and inserted into a WPF or Surface application, for instance. This cross-platform extensibility greatly increases return on investment (ROI) for companies that target multiple platforms.

- By Kim Schmidt, Guest Author from the Silverlight Group

Monday, May 17, 2010

MEF (Microsoft Extensibility Framework) made simple (ish)

Microsoft Extensibility Framework or MEF is one of the great features in Silverlight, designed around making Silverlight applications more extensible generally and provides a much more complete story for the separation of concerns. MEF then begs the question 'Why we care?' and 'What can MEF really do?' and we will address that here.

Let us talk about a real world example for a moment.

Say you are a vertical selling corporation of some kind, meaning that you sell to companies that do similar things. For example you might be selling to retail stores and your application will show their products. One of the problems is that your application will need to integrate with their CMS (Content Management System) to get product data. In Silverlight 3 your customers might need to provide a WCF Service to talk too. That WCF service they then provide has to have a certain API Signature or worse still they might need your code and need to recompile or YOU have to recompile for each customer or some other hack to make the application work.

Using MEF your customer still will need to get the data somewhere but it makes it easier on them to do this without mucking with your code. To make it work a customer can drop a 'XAP' that provides the content and your application doesn't care about WCF API signatures or other requirements that make it difficult to wire it into the existing system. Your customers can now easily extend, change or filter what and how their data gets to the application you built for their vertical.

In many ways this is like making the model of your application (speaking in the MVVM since) 'open source' and not only pulls the model out of the rest of the application into just about anything else and lets that model be manipulated by the client without rebuilding the application in any way.

Getting Started With MEF?

MEF is pretty straight forward to get started using since it is part of the Silverlight framework in these name spaces and you need to make sure you reference them at the project level.

System.ComponentModel.Composition
System.ComponentModel.Composition.Initialization

Now that we have the bits available, using MEF is as easy as Importing, Exporting and maybe a little code. The main idea is to be able to code or property decorations to allow MEF to find elements either being exported or imported and tie them together. We can look at this process as being able to export the data, import the data and composing the data in an abstract way that allows the elements of this process to be abstracted from our application to a degree that it can be done externally to the application post compile. "Gah!," you say? Let's take a look at the next section and learn more about this process?

MEF'd Properties in and out of our Application

Here we will work out the basics of using MEF in our application. We can start simple by creating some properties and decorate them so that we can build out our application and have them magically set by MEF. Ok maybe it is not magic so let's focus on the properties that will be set first and see how it is done. Take a look at the following code sample:

[Import("SomeValue")]
public string SomeValue;

You can see here we have 2 lines of code. The second line is our traditional string property of some object like a string. The declaration line before it is what exposes our property to MEF and allows MEF to set it. You'll note that we use a magic string here. I know this is generally not well thought of by your standard architecture astronaut but you need to have a key value in the form of a magic string to have MEF do the data mapping unless you want to define your own import attributes which we will talk about later on. Next we can take a look at the code that sets this value.

CompositionInitializer.SatisfyImports(this);

You can see here that we are doing this programmatically and we get our data from the MEF catalog. By doing this in the constructor we allow MEF to go get our data where it is coming from and loading it and we can then use it as needed in our view. This MEF process is much like dependency injection might be used in a MVVM View. Really making this work then requires that we also have this object we are talking about in our constructor. To make this week we still need to have a simple class that exports that data in such a way as we can have some data. The following code does that.

[Export("SomeValue")]
public string SomeValue = "foobar";

Notice the export declaration in this sample. When this current assembly is running we get this data element automatically added to the catalog. Going back to the sample that included the catalog you can see that we created an instance and added the current application running as our package. Once we have added a package to our catalog we can then create a container that using the container we can then ask MEF to match the elements together to do our 'binding' So how then do we make this a two way street or deal with larger collections?

Making our Properties a 2 way Street

A popular construct in Silverlight and in the XAML world altogether is the ObservableCollection. ObservableCollections allow us to do lots of things but let us focus on the fact that it is a bindable collection of data that we want to be populated by MEF. Now take a look at the following lines that show a declaration and a collection property of come class.

[Export("SomeStuffs")]
public string Stuff1 = "blah1, blah";

[Export("SomeStuffs")]
public string Stuff2 = "blah2, blah";

[ImportMany("SomeStuffs", AllowRecomposition = true)]
public ObservableCollection SomeStuffs { get; set; }

As you can see this looks mostly like the first property we looked at earlier but here we are creating an observablecollection. The ImportMany declaration above it he collection allows the multiple element collection to come through and by also setting 'AllowRecomposition' the property can then be set over and over again by MEF. From this standpoint point we are ready to really build something separate from our application.

Exporting a Class in a Separate Xap

To create a Xap we can use a standard Silverlight project that we add to our solution. Since we are going to load the xap we can get rid of the classes (x and y). Create a class called z and make it look like this code:

public class SomeClass
{
[Export("SomeValue")]
public string SomeValue = "foobar3";
}

In this class you can see we create a class with 4 properties and use export to the same key name. This creates the effect of the values being exported to the MEF catalog as a collection that will get associated with the collection we created in the last section. For this to work we need to make sure that our Xap is referenced in our first app.

Downloading Xap Dynamically

Now that we have our collection and a new xap with a class that exports values we want we can look at importing the Xap and using MEF to wire that up to the data we need. Take a look at the following code:

[Import("SomeValue", AllowRecomposition=true)]
public string SomeValue;

DeploymentCatalog catalog = new DeploymentCatalog("MEFModel.xap");

// in constructor:
CompositionInitializer.SatisfyImports(this);

catalog.DownloadCompleted += new EventHandler(catalog_DownloadCompleted);
catalog.DownloadAsync();


void catalog_DownloadCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
// some code...
}

This code can be added to the constructor of our application just after the call to AddPackage. You can see that we pass a Relative URI to our other Xap and that we add it to the package when it loads. This can also be an event handler to to the load. In this case we get the content added to the package and it gets wired up based on the name key values that we have set by the ImportMany and Export declarations. Now the cool thing is that we don't need to keep this in the constructor. We can call this same 'DownloadPackageAsync' from any event handler or other block of code that we need. We could use this to load content dynamically pending on certain conditions such as localization.

This is all wonderful but there is one problem with using a separate Xap that has the MEF bits in it. This means that both Xaps have MEF and now ours Xaps are twice blotted from MEF using more memory then needed. Fortunately there is way around this is to set the additional Xaps to use include this in the build. In Visual Studio in the other projects find the Library reference to the MEF and right click and select properties. On the reference property pain there is a property called 'Copy Local' and we need to set this to false. This way only one copy of the MEF bits will be in the overall application saving Xap size by not blotting all the Xaps with the same bits.

Monday, August 3, 2009

MSDN Webcast: geekSpeak: Composite Application Development (Level 200)

Start Date: Wednesday, August 19, 2009 12:00 PM Pacific Time (US & Canada)
Duration: 60 minutes
Audience: developer

In this geekSpeak, Microsoft Most Valuable Professional (MVP) David Kelley discusses composite application development in Microsoft Silverlight and Windows Presentation Foundation (WPF). He covers the Silverlight Designer/Developer workflow, tooling, design patterns, anti-practices, and working with distributed teams. Your hosts for this geekSpeak are Glen Gordon and Mithun Dhar.

The geekSpeak webcast series brings you industry experts in a "talk-radio" format hosted by developer evangelists from Microsoft. These experts share their knowledge and experience about a particular developer technology and are ready to answer your questions in real time during the webcast. To ask a question in advance of the live webcast, or for post-show resources, be sure to visit the geekSpeak blog.

Guest Presenter: David Kelley, Senior Software Architect, IdentityMine

David Kelley is a Microsoft Most Valuable Professional (MVP) for Microsoft Silverlight, and he has been building Web-based, distributed applications for more than ten years. He is a Silverlight user experience architect at IdentityMine, and his passion is building user experiences that are elegant and easy to use. David's career highlights include a Silverlight demonstration with Bill Gates at TechEd 2008, and developing the "Entertainment Tonight" Web site for the Silverlight 1 launch and Emmy Awards. In his spare time, David is the executive officer of the Seattle Designer Developer Interaction Group.


Click Here to Register

Saturday, July 4, 2009

Azure Simon

Davide Zordan posted a version of Silverlight Simon up in the cloud at http://azuretestapp.cloudapp.net

Davide had also added multi touch support to the WPF version. You can check out the code on the codeplex project http://Simon.codeplex.com/

Tuesday, June 16, 2009

MVVM Silverlight

So this topic has been going around for some time about building MVVM Implmentations in Silverlight a couple of people I know are doing toolkits (surprise surprise WPF guys mostly) but here are two of my favorites include Michaels:

http://silverlightmvvm.codeplex.com/

and Laurents:

http://blog.galasoft.ch/archive/2009/06/14/mvvm-lsquolightrsquo-toolkit-for-wpf-and-silverlight.aspx

any real dive into the topic should also include shawn's blog/posts starting with say this one http://wildermuth.com/2009/06/10/DevTeach_Silverlight_MVVM=Easy_Demo

In any case since I've been focusing on the composite apps as of late I'm going to work on something based on Michaels and get that posted.

Wednesday, February 11, 2009

The Ultimate Design Pattern

So I'm building out all these different variations on Command Pattern for Silverlight and writting articles on MVP or pMVP or MVVM or M-WTF and some times the entire discussion gets so esoteric that I want to screen. I mean really how the heck to you entirely seperate presenter from the model and view for example? in Silverlight its NEVER entirely seperate, not really. Anyway so as always Dr. WPF is the man and has a solution... W-V-poo which I think applies to Silverlight as much as WPF. Check out the article:

http://www.drwpf.com/blog/Home/tabid/36/EntryID/27/Default.aspx

Tuesday, February 3, 2009

Cool Silverlight 'Patterns'

My friend Nathan sent me this link to this cool Silverlight UX Pattern tool. From Infragistics in Silverlight lets you explore UX patterns visually and by tags and more. Check it out:

http://quince.infragistics.com

Wednesday, December 17, 2008

Xaml Guidelines, Part 1

Check out Jonathan, Jared and Nathan on Xaml Guidelines on Channel 9. I know this is focused alot of WPF but as suggested on their post it applies to Silverlight AND wpf.

http://channel9.msdn.com/shows/Continuum/XAML-Guidelines-Part-1/Default.aspx?wa=wsignin1.0

Friday, November 21, 2008

Silverlight 2 Architecture and CodeCamp

So I was going todo a couple of sessions recently at a seattle local even called codecamp. I had a family related complication and was not able to attend (I did let the organizers know BEFORE it started, so don't go harping on me for doing it at the last moment).

Anyway one guy emailed me about getting that content available. of course this stuff will be in my book and I'm doing the presentations at DevTeach etc. but up front I'd like to point out a few things that might help get people going in the right direction.

So from a design pattern stand point the entire discussion frequently has more in comon with Hell Fire and brime stone religous discussions then real logical 'Useful' disuccusions that are actually helpful. It really is all kind of esoteric mumbo jumbo at some level.

In an effort not to get sucked into a religous war I'm going to go WAYYYY out of a limb and say the best design pattern is in fact MVP (model view presentor) as discribed in the following posts by others:



Phil Haack
http://haacked.com/archive/2006/08/09/ASP.NETSupervisingControllerModelViewPresenterFromSchematicToUnitTestsToCode.aspx
Tim Ross
http://timross.wordpress.com/2008/03/16/implementing-the-mvp-pattern-in-silverlight/

There are several ways todo it and I'm not even saying that this one is correct just it happens to be my choice for no other reason then it helps get back to some nice old CS101 ideas like 'gasp' OBJECT ORIENTED or Encapsulation sorts of things.

my code behinds are simple may data model objects are clean and my Xaml is Zen with the universe.

lets just say for the sake of moving foward that I'm going with the MVP design pattern as my prescribed method. Alot of what you do on top of that is more or less common sense. Follow stand coding conventions as they apply, following Preformance best practices where they apply, and most of all consistency.

do it, all do it and do it the same...

I really don't care which way but really I should never be able to tell who did and I should seem lots of oh yea that is logical and is the best way.

really thats is the bottom line. More to come as I work out a detailed talk track for the SLV421 presentation in case I want to give it to say my friend John todo the same presentation at another conference... ;)