On a previous post in this series I talked about a possible approach to take when starting to learn Prism as a whole (the Tip numbering is resumed from the previous post). In this post I will get more specific and talk about one of the most used (if not the most used) pattern when developing Prism applications (either for WPF & Silverlight): MVVM.

Most people are familiar with this pattern (if you are not great places to read about it are here for WPF and over here for Silverlight), so I will not go deep into what is the main idea of it. Instead I will try to go over some core concepts that usually lead to different levels of confusion.

What’s the difference between MVVM and PresentationModel?

The above question is one asked a lot, as people tend to get confused when they hear all the talk about MVVM and then open some Prism Quickstarts or RI and find most of them “implement the PresentationModel pattern”.

Well, there is not a certain answer (and if there was I probably wouldn’t be the one who came up with it), but as far as Prism development is concerned they are synonyms. There is no difference between them, except for the coined term. As Martin Fowler explains in his PresentationModel article: “The essence of a Presentation Model is of a fully self-contained class that represents all the data and behavior of the UI window, but without any of the controls used to render that UI on the screen. A view then simply projects the state of the presentation model onto the glass.”, so if you think about it, the way to “project the state of the PresentationModel (or ViewModel) onto the glass is WPF/Silverlight DataBinding in our case (or as Julian likes to explain it: “the ViewModel is a bindable Presenter”).

Always remember the main objective, testability and decoupling.

Tip 5: MVVM and Presentation Model are synonyms.

How do I do pure MVVM?

This is another point of confusion as people tend to relate MVVM with DataTemplates and no View code behind, so they get the idea that the only way to implement the pattern is that one.

In my opinion there is no pure MVVM, it is a design pattern, so it can have many different implementations which will depend mainly on who implements it and what his requirements are. In this particular topic I would like to “branch you” to Glenn’s post “The spirit of MVVM (ViewModel), it’s not a code counting exercise.” as I agree with his point of view in this topic, so there is no point in duplicating the information.

Now that you have finished reading Glenn’s post, I hope you understand what I am trying to explain (not necessarily agree). I for once like the “View First” (you “talk” to the view) implementation to relate the View to its ViewModel in Prism could be the following (using DI):

public class MyView
{
public MyView(IMyViewModel viewModel)
{
this.DataContext = viewModel;
InitializeComponent();
}
}

In the code above, Unity’s DI provides the decoupling between the View and the ViewModel, so the ViewModel “does not have to know anything about the view” and allows you to test the VM in isolation (of course this is just one of the ways to do it).

Tip 6: There is no Silver Bullet MVVM implementation. Use the one that you like best.

How should I manage my View/ViewModel?

This question addresses both creation/destruction of View and ViewModels as well as its interaction with other components in the application. Often it is not “clear” which component should handle a specific action.

Say that when a button is clicked an event should be published. Where should this be done? Well, without information about the application and its patterns it is hard to say. It could be done in the ViewModel or it could be done in a module level controller that manages interaction with other modules, but this depends on how your application is structured.

Instead of expanding on this topic, I would like to branch you (yet again), to these posts from Ward Bell which talk about these common questions and provide some really interesting and thought answers:

Should I always use commands to communicate with the ViewModel?

Before using a command, I usually stop and think: “Can this be done in another way?, Can I achieve this same functionality with binding?”. Well, sometimes the answer is yes, and that is when I think commands are not necessary. The most common example is binding a command to execute every time and item in a Listbox is selected. This same behavior can be achieved by binding the SelectedItem property of the Listbox to your ViewModel (most of the times), and executing the required action on the setter.

Having thought of the above, what if I do need a command? Well, my first recommendation would be understanding how do Commands with attached Behaviors work, a topic explained by Julian in this great post. After that you can use the code snippet I created some time ago to help you with the tedious task of creating the classes required for this to work.

Tip 7: Before using commands, think if there is another option.

Things to add to your reading list

To help you comply with Tip 4, you can find below a couple of articles about MVVM and MVVM with Prism that I think might be of use to better understand this topic (the ones mentioned above would be in this list, but there is not need in duplicating them):

Hopefully, this post has helped you understand a little more about MVVM and how to use it with Prism. As always, your feedback is appreciated, so if you believe any link should be added or anything of the sort, just drop a comment.

Shout it

kick it on DotNetKicks.com

As most of you might know, Visual Studio 2010 Beta 2 was released some days ago. Ever since, many people have asked at the Prism codeplex forums if Prism works with this latest version. That’s why with Fer we decided to migrate Prism latest release for Silverlight 3 to VS 2010 Beta 2. Our conclusion after our smoke tests is that it does work :) .

Migration Steps

  1. Migrated every solution.image
  2. Ran the tests and smoke tested each application.
  3. Fixed any issues that appeared (mostly related to missing assembly references).
  4. As a little extra, we added the White assembly references required to run the acceptance tests.

Changes Required

Below you can find a small explanation of the changes required for the migration:

  1. The Reference Implementation Tests fail (4 tests) when you run them. The fix is explained in this thread.
  2. Many projects will throw a missing assembly reference exception related to “System.Xaml.dll”. You need to add this assembly as a reference in most test projects.
  3. The Multitargeting Quickstart throws an error when running it. To fix it, change the Resources constructor modifier from internal to public.
  4. Some build errors might be thrown because of code analysis issues in Silverlight projects (CA:0055 Analysis of Silverlight assemblies is not supported):
    • Uncheck the “Enable Code Analysis on build” check box in the Code Analysis tab.
    • Make sure code analysis is not one of the compilation symbols in the Build tab.

Download

The code provides all the fixes performed, and is provided “AS IS” with no warranties and confers no rights. It is shipped under the “works on my machine” license. You can download it from here.

I hope this saves you the trouble of migrating Prism to VS 2010.

Shout it

kick it on DotNetKicks.com

Now that the Prism team has shipped a new version of the guidance, I thought it would be a good time to blog on this subject, based on some research we did with Ezequiel, Matias and Julian. This article will not focus on how to workaround the limitations of using Silverlight 3 Navigation with Prism (as the guys who wrote the posts mentioned below have done a good job on that) instead it will focus on the why of these limitations:

Warning: Technical explanation coming below.

The Silverlight team is aware of the limitations mentioned below, so they might be taken into account for a future version.

Issue Description

Pages with code behind, from remotely loaded modules cannot be navigated to, calling the Frame’s Navigate method. This prevents having functional views since they neither have code behind nor a ViewModel attached.

Cause of Issue

Note: To be able to perform the research below, add the following line in the LoadAssemblyFromStream method placed in the XapModuleTypeLoader class from the CAL:
Deployment.Current.Parts.Add(assemblyPart);

The Silverlight 3 Navigation framework goes over every AssemblyPart in the Deployment.Current.Parts collection if the Page to navigate to has code behind, as shown in the code below (PageResourceContentLoader class reflected code in the System.Windows.Navigation namespace from the System.Windows.Controls.Navigation assembly):

private static Type GetTypeFromAnyLoadedAssembly(string typeName)
        {
            Type type = null;
            foreach (AssemblyPart part in Deployment.Current.Parts)
            {
                /*THE LINE BELOW RETURNS NULL FOR REMOTELY LOADED ASSEMBLIES, BECAUSE THEY ARE NOT IN THE APPLICATION’S XAP*/
                StreamResourceInfo resourceStream = Application.GetResourceStream(new Uri(part.Source, UriKind.Relative));
                if (resourceStream != null)
                {
                    Assembly assembly = new AssemblyPart().Load(resourceStream.Stream);
                    if (assembly != null)
                    {
                        type = Type.GetType(typeName + “,” + assembly, false);
                    }
                }
                if (type != null)
                {
                    return type;
                }
            }
            return type;
        }

As the above code shows, even if the AssemblyPart is in the collection it is not found by the Application.GetReourceStream method. From the method’s MSDN site, the cause is:

“The GetResourceStream method allows you to load an arbitrary resource file from one of the following locations:

  • Embedded in the application assembly in the application package.
  • Embedded in a library assembly that is included in the application package.
  • Included in the application package.”

So only assemblies in the application’s original .xap file are found and not for other modules.

I hope the above explanation was useful.

Shout it

kick it on DotNetKicks.com

The patterns & practices team has just released Prism-v2.1, an updated version of the Composite Application Guidance for WPF & Silverlight, which has some breaking changes, mostly related to Silverlight 3 (from the “New in this release” article):

image

  • All Visual Studio projects (Composite Application Library, reference implementation, and Quickstarts) were migrated to use Silverlight 3.
  • TabRegionControlAdapter was modified to support binding in the TabItem’s control header in Silverlight 3.
  • CreateXap.bat file was modified to search for Silverlight 3 assemblies if the Silverlight 2 reference assemblies cannot be found.
  • Implemented the WeakEvent Pattern for the DelegateCommand’s and CompositeComand’s (more on this below).

If you were using Prism 2.0, either for WPF or Silverlight development, I would recommend you to start using this new version, as there is also an implementation “of the WeakEvent Pattern for the DelegateCommand’s and CompositeComand’s CanExecuteChanged event to fix a possible memory leak in the applications using the Composite Application Library commands”.

You can download the latest version of the guidance from here.

Kudos to the Prism team!!!

Shout it

kick it on DotNetKicks.com

A question we get asked frequently is: “How do I start learning Prism? Is there a particular order for the Quickstarts? What other web resources do you recommend to start learning?”. If you are in this situation, or just want to have some more insight on a particular Prism topic, this is the post for you (I always wanted to say that, just like TV announcements :))

The basic question: “How do I start learning Prism?”

The first thing you should do to start learning Prism (assuming you know WPF/Silverlight), is begin with the documentation. It is really clear in what it tries to explain, provides great samples and explains a lot of the common doubts when starting to develop applications with Prism. There is not a particular order to learn Prism, so you should tackle it in the way you feel comfortable. Pay special attention to the Technical Concepts section, as it really helps understand how things come together.

Tip 1: Read the Prism documentation.

If while reading the documentation you have any doubts, or want to dig deeper into any particular topic you have many different options (and search queries in your favorite search engine). However, there are some things I believe you should take a look at:

  • Prism KB. There you will find links on many different topics (you can find a picture of them below), that could be videos, sample applications or blog post which will help you better understand some of Prism concepts.
  • Watch videos. There are lots of video tutorials going around, but these two collections are particularly good. Videos from P&P team & 10 Things to Know About Silverlight Prism.
Tip 2: Use the Prism KB and watch videos (these and also these particularly).

image

Prism KB site

But, what if I have some doubts while learning?

That is why developer communities were created, and as any other p&p asset Prism has its own forum at Codeplex where you can ask questions about any topic (technical concepts, how do I?, etc). The forum has a really active community, and is also monitored by the p&p Client Sustained Engineering Team (which we are part of). So if you have a question that has been bugging you for some time, and have not found the answer anywhere you can always drop by the forum.

Tip 3: Ask questions in the Prism Codeplex forum.

Last, but definitely not least…

There are some frequent Prism bloggers that you should follow, as they have some really interesting posts about how to use Prism and its insides. Below I will provide the list of those I follow (which is probably really short in comparison to the one I should be following), and for some the most interesting/requested post in my opinion:

As an extra, you can also follow the clientdev twitter, in which we tweet about the latest news about different .Net Client Development technologies (mostly Silverlight & WPF) and can be really useful when learning about Prism.

Tip 4: Read tons of articles about Prism.

I hope this article will help your Prism learning process, and please provide any feedback you might have so I can improve this guidance, like comments on the bloggers.

Shout it

kick it on DotNetKicks.com

Yesterday I blogged about the Prism-v2 Reference Implementation migrated to Silverlight 3 with Out of Browser Capabilities. You can read that post here.

Today I wanted to compare the validation provided by the RI to the one that comes with Silverlight 3. I came up to the conclusion that the approach provided by p&p is pretty similar to one of the approaches Silverlight 3 allows related to validation. You can watch this video about Silverlight 3 Validation which explains some of the possibilities you have.

After that I decided to replace the RI’s validation using Silverlight 3 and was able to do it with some minor changes (you can check the OrdersDetailsView and OrdersDetailsPresentationModel which have most of the changes).

A different approach to reduce code behind through attached behaviors in the views can be used to keep a list of the validation errors. This blog post provides more information about it.

After all the changes were made, the following is the outcome with invalid data input:

Prismv2 RI Validation Error

Source Code

Disclaimer

This code is provided “AS IS” with no warranties, and confers no rights.

Download

You can get source code here: Prism v2 RI with SL3 Validation.zip .

More info

The following are some other posts related to Prism and Silverlight 3:

Fun validating :)

kick it on DotNetKicks.com

Shout it

A couple of months ago I migrated the Composite Application Guidance for WPF and Silverlight (Prism-v2) Reference Implementation to Silverlight 3 Beta version and added Out-of-Browser functionality to it. You can read all about that here.

Today I updated the same application but for the latest Silverlight 3 release. The main difference is the update to the Out of Browser settings. While before you had to add some configuration to your AppManifest file, now you can just click the properties of your Silverlight project and check the Enable running application out of the browser option. Then you can modify the settings. (You can read about that and other updates in the release version in Tim Heuer’s post), so I did…

Out of Browser Settings

This will automatically generate an OutOfBrowserSettings.xml file. After that quick update I was able to run the application out of the browser:
Running OOB RI

Source Code

Disclaimer

This code is provided “AS IS” with no warranties, and confers no rights.

Download

You can get source code here: Prismv2 SL3 RI with OOB.zip.

More info

The following are some other posts related to Prism and Silverlight 3:

I hope this update is useful for you :)

kick it on DotNetKicks.com

Shout it

Today I tweaked the Event Aggregator Quickstart that comes with the Prism-v2 source code to show how Silverlight 3 Child Windows could be used in a Silverlight Composite Application.

Child Window Overview

Silverlight 3 has a new template called ChildWindow. It is basically a user control (unlike a Popup you can edit its XAML), but it allows you to create modal windows for your application, such as dialogs.

Template Dialog to add Child Window control

To use this dialog, you just have to create a new instance of it and call its Show method. As this call is asynchronic, you need to handle the Closed event to know when the dialog interaction has finished.

Sample Scenario

The Quickstart’s scenario shows how to use the Event Aggregator to add funds of a particular customer, so what I did is add a confirmation dialog before adding the fund. After you select the customer and fund (both of them as in the original Quickstart) and click the Add button following dialog pops up:

 Dialog to decide whether to add the fund or not

As expected, if you click “Yes” the fund will be added, and if you click “No” or close the dialog it won’t.

Child Window Sample
Disclaimer

This code is provided “AS IS” with no warranties, and confers no rights.

Download

You can get the sample from here: ChildWindowSample.zip.

kick it on DotNetKicks.com

Shout it

Today I finally decided to blog about the Prism-v2 Silverlight reference implementation using Silverlight 3 Beta.

In this post I will explain the process and some of the modifications I made to the application to use some of Silverlight’s new features and provide the outcoming source code.

So after opening the RI with SL 3 installed the well known migration wizard appeared.

convertsolution

The migration was a pretty straightforward process, and after less than a minute it finally succeeded and was ready for use.

Note: The steps above enable the Reference Implementation to run with Silverlight 3 correctly. From now on I will just add some functionality new in Silverlight 3.

So with Julian, Ezequiel and Matias we started to think which of the new features from Silverlight 3 could be shown working in the Reference Implementation.

After a small talk, our choice was out-of-browser (OOB) functionality.

Implementing Out-Of-Browser (OOB) functionality

For those who have not yet had the chance to read about this Silverlight 3 feature I will provide some links at the end of this article.

To enable OOB, I opened the AppManifest.xml file, and changed its content to the following:

<Deployment xmlns=http://schemas.microsoft.com/client/2007/deploymentxmlns:x=http://schemas.microsoft.com/winfx/2006/xaml>
  <Deployment.Parts>
  </Deployment.Parts>
  <Deployment.ApplicationIdentity>
    <ApplicationIdentity
        ShortName=Prism-v2 RI Silverlight 3Title=Prism-v2 Reference Implementation working out of the Browser with Silverlight 3>
      <ApplicationIdentity.Blurb>
        Prism-v2 RI running out of browser in Silverlight 3
      </ApplicationIdentity.Blurb>
    </ApplicationIdentity>
  </Deployment.ApplicationIdentity>
</Deployment>

Having done that, OOB should have been enabled. I ran the application and right clicked to check if this worked correctly. After confirming that I wanted to install the application, the following message was shown:

install

Ok, the objective was complete. However, that picture is not the one that represents our application the best.I created some images, added them to a folder in the StockTraderRI project (Icons folder). After setting the build action of each image to “Content” and I updated the code in the AppManifest.xml so the icons would be used in the OOB application:

<Deployment xmlns=http://schemas.microsoft.com/client/2007/deploymentxmlns:x=http://schemas.microsoft.com/winfx/2006/xaml>
  <Deployment.Parts>
  </Deployment.Parts>
  <Deployment.ApplicationIdentity>
    <ApplicationIdentity
        ShortName=Prism-v2 RI Silverlight 3Title=Prism-v2 Reference Implementation working out of the Browser with Silverlight 3>
      <ApplicationIdentity.Blurb>
        Prism-v2 RI running out of browser in Silverlight 3
      </ApplicationIdentity.Blurb>
      <ApplicationIdentity.Icons>
        <Icon Size=16×16>Icons/icon16.png</Icon>
        <Icon Size=32×32>Icons/icon32.png</Icon>
        <Icon Size=48×48>Icons/icon64.png</Icon>
        <Icon Size=128×128>Icons/icon128.png</Icon>
      </ApplicationIdentity.Icons>
    </ApplicationIdentity>
  </Deployment.ApplicationIdentity>
</Deployment>

After that, the picture changed to show one of the pictures chosen:

install2

After checking both options (there is no need to check any of the options, I just did), the application was launched out of the browser :)

oob

Source Code

Disclaimer

This code is provided “AS IS” with no warranties, and confers no rights.

Download

You can get source code here: Prism-v2 RI with OOB capabilities.zip.

UPDATE 2009-07-13: I updated the application for the official Silverlight 3 release. You can check it out here.

Final thoughts

For more information about out-of-browser experience you can check:

Some other posts related to Silverlight 3 and Prism-v2:

I hope this post is useful to you, and your feedback, opinions and thoughts are always welcome to continue improving.

kick it on DotNetKicks.com

Shout it

This is a post I have had pending for a long time. As usual it came up after I saw this question in the Composite WPF & Silverlight forums at Codeplex.

The user wanted a lightweight download, and was only using the Event Aggregator from the CAL’s latest bits. I thought that this would really test Prism’s extensibility, so I created a single assembly which only contained things required by the Silverlight Event Aggregator.

UPDATE: This assembly also works when using Silverlight 3 Beta version.

The following picture will easen the process of explaining/understanding all the classes this assembly requires. It was taken using the .Net Reflector. (Clicking it will probably make it easier to read)

Afterwards I tested the correct functionality of this assembly using the EventAggregator Quickstart by replacing the events used in it with events from this new assembly.Everything worked like a charm, so Prism-v2 passed this “extensibility test” :)

Glenn Block has a post that explains how to perform Event Aggregation with MEF (with and without EventAggregator), so perhaps you could find that post interesting if you have read this far.

You can check out other posts in this series:

Standalone Silverlight Event Aggregator Binaries

Disclaimer

This assembly is provided “AS IS” with no warranties, and confers no rights.

Download

You can get the assembly here: Composite.EventAggregator.Silverlight.

kick it on DotNetKicks.com

Shout it