Category Archives: Prism

[Spanish] Webcast Disponible: Arquitectura MVVM para la construcción de aplicaciones Windows Store

For those who don’t read Spanish, this blog post provides details about a Spanish speaking webcast that Diego Poza and I presented last week for the MSDN Latin American community.

La semana pasada junto con mi amigo Diego “Tony” Poza hicimos un Web Cast en el cual explicamos diferentes formas de crear aplicaciones Windows Store con una arquitectura mantenible y flexible.

Queremos agradecerles a todos los asistentes, ya que fue una sesión muy interactiva y con muchas preguntas muy interesantes.

Algunos de los temas que se trataron durante el Web Cast fueron:

  • Cómo tomar ventaja de las PCL (bibliotecas de clases portables).
  • Cómo decidir si usar un framework o no.
  • Manejo de dependencias de los ViewModels.
  • Pruebas unitarias.

Video Online

Para los interesados, les dejamos a continuación los detalles del evento y los links para descargar la grabación o verla online:

Si tienen alguna otra pregunta pueden contactarnos por twitter (@dschenkelman y @diegopoza).


A continuación incluyo algunos de los links referenciados utilizados durante la charla:

Binding to View Model properties in Data Templates. The RootBinding Markup Extension

If you work with Silverlight and MVVM, you must have probably been forced to do some weird thing to bind to a property in your view model (say a Command) from a DataTemplate. Some of the common approaches I have seen and used myself are:

  • Using some kind of binding helper as a View’s resource.
  • Having a View Model wrap the entity of each collection item, and add the command to the View Model.

Although this are perfectly valid approaches, they require extra work compared to the good old {Binding} syntax we are all used to.

Now that Silverlight 5 Beta is out, we can take advantage of the XAML Markup Extensions to help is in this kind of tasks, using a simpler and more intuitive approach.

Read More

Dynamically updating an application’s functionality using IronPython

About a month ago I blogged about an e-mail sender program that used the MVVM pattern to integrate business logic written in Iron Python with presentation logic written in C#. In this post I will show another great benefit of using this approach. The source code related to this post can be downloaded from here.

The old e-mail client only allowed users to send e-mails using a Hotmail or a Gmail account. Let’s say we our application to support new e-mail providers without having to restart it. When discussing this with Martin Salias, he suggested me to use a FileSystemWatcher, which is the approach I decided to take.

The first thing we need to do is create a FileSystemWatcher instance in the ViewModel’s constructor and have it listen to changes in the directory where the Python modules are obtained from. As we only want to get updates when a python module is updated, we specify that filter as well:

private void InitializeFileSystemWatcher()
    this.fsWatcher = new FileSystemWatcher(PythonModulesPath, "*.py");
    this.fsWatcher.EnableRaisingEvents = true;
    this.fsWatcher.Changed += FileSystemChanged;

Now we need to re-load the modules being used by our application once a change in the path specified occurs and update the UI accordingly:

private void FileSystemChanged(object sender, FileSystemEventArgs e)

    //update all bound properties

To check how this is working follow these steps:

  1. Open the solution provided in the .zip file and run it.
  2. Expand the Combobox control to verify that only Gmail and Hotmail are supported.image
  3. Find the New Modules folder inside the .zip file and copy the module to the WPFClientbinDebugPython Code directory. Replace the existing file.image
  4. Expand the Combobox control to verify that Yahoo has been added as a provider.image
  5. (Optional) If you have a yahoo account send an e-mail to test that it works correctly.

Although this sample is quiet simple, I think it is a great way to illustrate the flexibility of having this kind of application.

WPF Guitar Hero using MVVM & MVP

Last semester, at the University, along with other students (Alejandra Stamato, Gonzalo Zamudio and Manuel Soldini), we had to create a game similar to Guitar Hero for the Algorithms & Programming III subject. Being a University subject, it had some specific requirements (mostly related to model specification and the entities that needed to be included). Additionally, we were given the choice to use either C# or Java to develop the game.

Some of the requirements:

  • Use TDD to develop the game. This lead to approximately 100 unit tests.
  • Use a presentation pattern (similar to MVC). We decided to use WPF and the MVVM pattern. Additionally, we took some elements from MVP to simplify the interaction between the view and the view model.
  • Have a code base that is easy to read.
  • Use known design patterns when necessary. That is way during the development process we determined to use the Iterator and Strategy patterns among others.
Disclaimer: The solution we developed was required to be coded in Spanish. I have spent time translating almost all the code, but there are some small parts that have not been translated (mostly related to strings and XML).

Below you can see an image of the game running and this is the link to download the code. I have the idea of “Prisming it up” a bit, but in the meantime I think publishing the code should be positive.  Of course, any feedback you might have is welcome.

The prerequisites are:

  • Visual Studio 2010
  • .Net Framework 4.0
  • (Optional) NUnit version 2.5.7 to run the Unit Tests


Shout it

Using MVVM to bring IronPython and WPF together

A couple of weeks ago I decided to start a code kata using IronPython, with the objective of learning how C# and IronPython code could be integrated and used together. I had previously used Python (my favorite choice for University assignments), but this was my first try with the DLR version.

(If you just can’t wait to get to the code, just scroll to the bottom of this post).

The first step is to get IronPython. As the project is hosted at codeplex, you can simply access and select the Downloads tab. I chose to download the latest stable release (v2.6.1).

I created some simple classes to wrap around Python’s e-mail libraries and begun research on how to use them from C# code in a WPF application. The following were some of the most useful resources I found:

After the initial spikes, I created a simple application with a single V-VM pair, which let’s you send e-mails using either a Gmail or Hotmail account (disregard the poor-man’s UI).


Let’s go over the pythonic parts of the ViewModel.

First I defined the following four attributes:

private ScriptEngine engine;
private ScriptRuntime python;
private dynamic emailWrapper;
private dynamic emailDispatcher;

The ScriptEngine is used to customize the paths to search for Python modules. Unless the paths are configured correctly, you will get errors when importing modules that are part of Python’s standard library. As the following code shows, the path for the Python standard library and the relative path for my Python modules are being added to the list of paths:

private void SetPythonLibraryPath()
            ICollection<string> paths = engine.GetSearchPaths();
            paths.Add(@"C:Program Files (x86)IronPython 2.6 for .NET 4.0Lib");
            paths.Add(Path.Combine(Directory.GetCurrentDirectory(), "Python Code"));

Then, I get the ScriptRuntime from the ScriptEngine using its Runtime property. The ScriptRuntime is used to load the python modules into the dynamic fields mentioned above. The emailWrapper and emailDispatcher fields will store the modules with the same name.

private void LoadPythonModules()
           string wrapperPath = Path.Combine("Python Code", "");
           string dispatcherPath = Path.Combine("Python Code", "");

           emailDispatcher = python.UseFile(dispatcherPath);
           emailWrapper = python.UseFile(wrapperPath);

Now that I have access to the modules, I can simply instance classes or call functions from them. This is because the dynamic type resolves the operations at runtime.

private void SendEmail()
            string providerAccount = String.Format("{0}@{1}.com", this.UserAccount, this.Provider);
            dynamic email = emailWrapper.Email(this.Subject, this.ToAddress, providerAccount);
            dynamic dispatcher = emailDispatcher.EmailDispatcher(providerAccount, this.Password, this.Provider);
            dispatcher.send(email);             ...

private void PopulateProviders()
            this.Providers = new ObservableCollection<string>();
            foreach (string provider in emailDispatcher.getProviders())

Note: A way to use python objects while maintaining compile time checking is having Python objects implement CLR interfaces. There might be scenarios in which type safety brings more benefits, but in this case I thought interface implementation was un-pythonic.

That’s pretty much it. I’ll probably continue working on this small application, to show a couple more things that can be achieved with this kind of integration. Things that come to mind are:

  • Sharing variables between Python and C# scopes
  • Changing the application’s behavior by updating Python modules without the need to rebuild the application.

Downloading the sample

You can download the sample code from here. The code is provided “AS IS” with no warranties and confers no rights.

I hope this small introductions is useful for you and I’d love to get your thoughts on this approach.


Thanks to Martin Salias, Iron Python expert (among other technologies), for reviewing the code and contributing with ideas, and to Fer, Mati and Diego who witnessed the first demo of the application and also provided useful ideas.

MVVM para WPF y Silverlight @Codecamp Buenos Aires

El Sábado 4 de Septiembre, junto a mis amigos Diego Poza y Matias Bonaventura, vamos a dar una charla en Codecamp Buenos Aires sobre patrones de presentación en WPF y Silverlight 4, enfocandonos principalmente en Model View ViewModel (también conocido como MVVM).

Durante la charla vamos a mostrar las diferencias entre una aplicación que usa patrones y una que no, haciendo enfasis en temas como la cantidad de código utlilizado, testabilidad y extensibilidad entre otros. Así mismo, realizaremos una demo mostrando como refactorear una simple aplicación sin patrones hacia MVVM.

La charla comienza a las 10:15hs, asi que no duden en anotarse para el Codecamp y pasar por la charla.

Como en años anteriores, otros Southies van a estar presentando sobre los siguientes temas, asi que no se lo pierdan:

Nos vemos alla 🙂

Learning Prism (Composite Application Guidance for WPF & Silverlight) MVVM Fundamentals

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;

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