Dec 7 2009

Experiments using MEF, MVVM and Silverlight 4 Beta – Part 4: Part Creator

Note – this is a multi part post:

In the last post I’ve updated the MEF MVVM example inserting some PartCreator<T> experiments and I’ve received some feedback about its usage in the ViewModel instance initialization, so I decided to build a new sample in which PartCreator<T> is used to dynamically create objects to be inserted in a collection available in the ViewModel.

The VM instance is now initialized using an import attribute:

/// &lt;summary&gt;
/// Get the ViewModel instance
/// &lt;/summary&gt;
public class ViewModelProvider
{
    public ViewModelProvider() { }

    [ImportMainPageVMAttribute]
    public object mainPageViewModelProvider { get; set; }

    /// &lt;summary&gt;
    /// Get the imported Instance of the ViewModel
    /// &lt;/summary&gt;
    public object GetVMInstance
    {
        get
        {
            PartInitializer.SatisfyImports(this);
            return mainPageViewModelProvider;
        }
    }
}

PartCreator<T> is now used in a new AddDataItemCommand which updates dynamically a collection available in the ViewModel class:

/// &lt;summary&gt;
/// A simple Command to add a new DataItem in the ViewModel collection
/// &lt;/summary&gt;
[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(ICommand))]
public class AddDataItemCommand : ICommand
{
    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        if (parameter != null)
            if (parameter is string)
            {
                var dataItem = DataItemCreator.CreatePart().ExportedValue;
                dataItem.Description = (string)parameter;
                viewModel.dataItems.Add(dataItem);
            }
    }

    [ImportMainPageVMAttribute]
    public MainPageViewModel viewModel { get; set; }

    [Import(typeof(DataItem))]
    public PartCreator&lt;DataItem&gt; DataItemCreator { get; set; }
}

MEF

The source code is available for download here.

Happy Silverlighting!


Dec 6 2009

Experiments using MEF, MVVM and Silverlight 4 Beta – Part 3: Part Creator and Creation Policy

Note – this is a multi part post:

In the last post I’ve inserted custom attributes in my MVVM implementation using MEF, in the meantime some awesome discussions and inputs on Twitter by Glenn Block have highlighted new interesting scenarios.

First of all, object instances are shared by default in MEF, however you can change this behaviour using a dedicated attribute named PartCreationPolicy during the export phase:

[PartCreationPolicy(CreationPolicy.NonShared)]
[ExportMainPageVMAttribute]
public class MainPageViewModel : ViewModelBase
{ .... class definition here .... }

In this way, all the ViewModel instances exported by MEF will be not shared and different views shall use different VM objects without any side-effect.

Another rule of thumb is avoiding calling the container directly in order to simplify architecture, as stated in this great article by Nicholas Blumhardt. This step requires the introduction of a new actor available in MEF: the declarative context adapter PartCreator<T>.

The first place in which I’ve used PartCreator<T> is in the code for the composition phase:

public MainPageView()
{
   InitializeComponent();

   PartInitializer.SatisfyImports(this);
   this.DataContext = mainPageViewModelCreator.CreatePart().ExportedValue;
}

[ImportMainPageVMAttribute]
public PartCreator<object> mainPageViewModelCreator { get; set; }

The VM instance is now retrieved calling the CreatePart() method of the PartCreator, instead of calling directly the container.

The same approach is now used to retrieve the instances relative to the aViewModelProperty and aSampleCommand:

[PartCreationPolicy(CreationPolicy.NonShared)]
[ExportMainPageVMAttribute]
public class MainPageViewModel : ViewModelBase
{
    /// <summary>
    /// Default constructor
    /// </summary>
    public MainPageViewModel() { }

    /// <summary>
    /// A Part Creator for the aViewModelProperty
    /// </summary>
    [Import("aViewModelPropertyTextProvider")]
    public PartCreator<string> aViewModelPropertyCreator { get; set; }

    /// <summary>
    /// A sample property
    /// </summary>
    private string _aViewModelProperty;
    public string aViewModelProperty
    {
        get
        {
            if (_aViewModelProperty == null)
            {
                _aViewModelProperty = aViewModelPropertyCreator.CreatePart().ExportedValue;
            }
            return _aViewModelProperty;
        }
        set { _aViewModelProperty = value; NotifyPropertyChanged("aViewModelProperty"); }
    }

    /// <summary>
    /// A Part creator for the sample command
    /// </summary>
    [Import(typeof(ICommand))]
    public PartCreator<ICommand> aSampleCommandCreator { get; set; }

    /// <summary>
    /// A sample command
    /// </summary>
    public ICommand aSampleCommand
    {
        get
        {
            return aSampleCommandCreator.CreatePart().ExportedValue;
        }
    }

    /// <summary>
    /// A simple property
    /// </summary>
    private string _aSimpleProperty = "A simple property sample";
    public string aSimpleProperty {
        get { return _aSimpleProperty; }
        set { _aSimpleProperty = value; NotifyPropertyChanged("aSimpleProperty"); }
    }
}

The VM instance is then created in xaml using a ViewModelPartCreator class:

/// <summary>
/// Get the ViewModel instance via the PartCreator<T>
/// </summary>
public class ViewModelPartCreator
{
    public ViewModelPartCreator() { }

    [ImportMainPageVMAttribute]
    public PartCreator<object> mainPageViewModelPartCreator { get; set; }

    /// <summary>
    /// Get the imported Instance of the ViewModel
    /// </summary>
    public object GetVMInstance
    {
        get
        {
            PartInitializer.SatisfyImports(this);
            return mainPageViewModelPartCreator.CreatePart().ExportedValue;
        }
    }
}

MainPageView.xaml:

<UserControl x:Class="SL4_MVVM_MEF.Views.MainPageView"
    .......
    xmlns:partCreators="clr-namespace:SL4_MVVM_MEF.PartCreators"
    >

    <UserControl.DataContext>
        <partCreators:ViewModelPartCreator/>
    </UserControl.DataContext>

    <StackPanel>
        <StackPanel Orientation="Horizontal">
            <TextBox Text="A ViewModel property MEF imported:" FontWeight="Bold"/>
            <TextBox Text="{Binding GetVMInstance.aViewModelProperty}" Margin="10,0,0,0"/>
        </StackPanel>
        <StackPanel Orientation="Horizontal">
            <TextBox Text="A ViewModel simple property:" FontWeight="Bold"/>
            <TextBox Text="{Binding GetVMInstance.aSimpleProperty}" Margin="10,0,0,0"/>
        </StackPanel>
        <Button x:Name="CommandButton" Command="{Binding GetVMInstance.aSampleCommand}" CommandParameter="This is a Command parameter"
                Content="Click me!" Margin="0,10" Width="200"/>
    </StackPanel>
</UserControl>

As usually the source code is available for download here.

A special thanks to Glenn Block for the awesome suggestions on Twitter :)

Happy Silverlighting!


Dec 5 2009

Experiments using MEF, MVVM and Silverlight 4 Beta – Part 2: Custom attributes

Note – this is a multi part post:

In the last post, I’ve used the new MEF framework available in Silverlight 4 Beta to build a simple MVVM sample exporting, importing and then composing the ViewModel object with the xaml View.

As pointed by Glenn Block in his last blog post, it’s not a good practice to use magic strings in the Export/Import attributes, so I decided to investigate further and to use custom ones.

The new VM class is now modified as follow:

[ExportMainPageVMAttribute]
public class MainPageViewModel : ViewModelBase
    {
public MainPageViewModel()
        {

        }
/// <summary>
/// A sample property
/// </summary>
[Import("aViewModelPropertyTextProvider")] public string aViewModelProperty { get; set; }
/// <summary>
/// A sample command
/// </summary>
[Import(typeof(ICommand))]
public ICommand aSampleCommand {get; set;}
    }

 You can note the presence of a custom attribute named [ExportMainPageVMAttribute] defined in this way:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class ExportMainPageVMAttribute : ExportAttribute
    {
public ExportMainPageVMAttribute(): base(typeof(ViewModelBase))
        {

        }
    }

This new type permits to export and make available to the view the instance of the VM class via a new custom [ImportMainPageVMAttribute]:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ImportMainPageVMAttribute : ImportAttribute
    {
public ImportMainPageVMAttribute() : base(typeof(ViewModelBase))
        {

        }
    }

The project now uses composition to initialize the aViewModelProperty  and aSampleCommand via a string provider

public class TextProvider
    {
[Export("aViewModelPropertyTextProvider")]
public string ViewModelPropertyProvider { get { return "This is the content of a ViewModel property"; } }
    }

and an [Export] attribute for our sample command:

/// <summary>
/// A simple Command in SIlverlight 4 Beta
/// </summary>
[Export(typeof(ICommand))]
public class AViewCommand : ICommand
    {
public bool CanExecute(object parameter)
        {
            return true;
        }

public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            if (parameter != null)
if (parameter is string) MessageBox.Show((string)parameter);
        }
    }

As usually the source code is available for download here.

Happy Silverlighting!


Dec 1 2009

First experiments using MEF, MVVM and Silverlight 4 Beta

Note – this is a multi part post:

MEF (Managed Extensibility Framework) is a new library available in Silverlight 4 Beta which permits to build applications that can be incrementally extended in a declarative way using three simple concepts (read this post by Glenn Block for more infos):

  • Export an object;
  • Import it;
  • Compose it.

Mixing MEF and commanding, Silverlight has now a great support for structuring projects using a ViewModel approach, so I decided to use these new characteristics to build a simple solution.

Given an existing project, I added a ViewModel class implementing INotifyPropertyChanged:

    [Export("MainPageViewModel"))]
    public class MainPageViewModel : ViewModelBase
    {
        public MainPageViewModel()
        {
            aViewModelProperty = "This is the content of a ViewModel property";

            aSampleCommand = new AViewCommand();
        }

        public string aViewModelProperty { get; set; }

        public ICommand aSampleCommand {get; set;}
    }

The problem I’ve solved using MEF is the binding of the DataContext property of the UserControl to a ViewModel class instance, so I’ve exported it using the MEF [Export] attribute.

The [Import] attribute and the PartInitializer.SatisfyImports(this);  are then used in the code behind of the xaml view in order to import and compose the ViewModel instance with the DataContext:

        public MainPage()
        {
            InitializeComponent();

            PartInitializer.SatisfyImports(this);
            this.DataContext = mainPageViewModel;
        }

        [Import("MainPageViewModel")]
        public object mainPageViewModel { get; set; }

And this is the result:

MEFMVVM

As usually the source code is available for download here.

Happy Silverlighting!


Dec 1 2009

Having fun with Silverlight 4 Beta and the Speech APIs

Silverlight 4 Beta is now available, one of the more interesting features is the ability to use Late Binding for automation APIs via the new dynamic keyword and the ComAutomationFactory class.

A great example is already available on the official http://silverlight.net site, using automation to control Excel in trusted applications.

With the same approach it’s possible to control any object exposed via COM so I’ve coded a (very simple) example to demonstrate the usage of the Speech APIs using this new automation bridge (thanks to Justin Angel on Twitter for the inspiration :) ).

Just reference in your Silverlight 4 Beta project the dll Microsoft.CSharp.dll contained in the SDK folder to enable the usage of the dynamic keyword.

Then enable elevated-trust by activating the Out of Browser mode and clicking on the “Require elevated trust when running out of browser” checkbox:

ElevatedTrustOOB

The code used is very simple, just create an instance of the COM object using the ComAutomationFactory.CreateObject() method:

dynamic speech = ComAutomationFactory.CreateObject("Sapi.SpVoice");

Then use the Speak method to make Silverlight speak (sorry, no code completion here, we’re using late binding):

speech.Speak("Hi Guys! This is Silverlight 4 Beta speaking!");

The complete Silverlight 4 Beta project is available for download here.

SpeechCapture

Have fun and happy Silverlighting!


Nov 8 2009

Multi-Touch gesture recognition in Silverlight 3

In this article, Jesse Bishop illustrates how to receive and interpret multi-touch input and translate these events into standard gestures, source code available!


Nov 8 2009

.NET RIA Services: the place to start

Just a quick shout-out to post a new section of the silverlight.net site which contains all the necessary resources to start with .NET RIA Services:

RiaServices

Enjoy Rapid Application Development for Rich Internet Applications (RAD for RIA) in Silverlight!


Oct 19 2009

Visual Studio 2010 Beta 2 and updated Silverlight Toolkit available

Lot of news this week!

Visual Studio 2010 and .NET Framework 4 Beta 2 are now available for download here, Jeff Beehler has posted some useful info about this “go live” release.

The new Silverlight Toolkit October 2009 Release is also available on Codeplex featuring Visual Studio 2010 support and various improvements on existing components (like drag-and-drop for items controls).

Read these posts by Tim Heuer and Jeff Wilcox for more details and enjoy!


Oct 15 2009

Silverlight and ViewModel meet F#

Many MVVM implementations are available on the net, personally I love the approach used by Laurent Bugnion in the MVVM Light toolkit and Michael Sync in the Silverlight MVVM toolkit (Jeremiah Morril have posted a great article about this pattern, don’t forget to read it here).

All these examples use C#, what about F# for describing ViewModel classes? F# is a very powerful and readable language and permits to perform operations using a small amount of code. Last, but not least, at this time it’s a first citizen .NET language and can be easily used in Silverlight applications as well.

How can we build a Silverlight MVVM solution using F#?

First of all, download and install the F# for Silverlight templates and samples.

Let’s start by defining a simple F# ViewModel class containing a simple “Name” property and a “SearchCommand”, this one using the DelegateCommand implementation available in Prism:

namespace SilverlightViewModelFSharp.ViewModels

open System.ComponentModel
open Microsoft.Practices.Composite.Presentation.Commands;
open System.Windows

type MainPageVM() =

   //Definition of the PropertyChanged event
   let event = Event<PropertyChangedEventHandler, PropertyChangedEventArgs>()

   //Definition of the "name" property
   let mutable name = "This is the value of a property defined in the F# ViewModel"

   //Definition of a test Command
   let searchCommand = new DelegateCommand<string>(fun (x) -> MessageBox.Show(x) |> ignore )

   //INotifyPropertyChanged interface
   interface INotifyPropertyChanged with
      member this.add_PropertyChanged(e) = event.Publish.AddHandler(e)
      member this.remove_PropertyChanged(e) = event.Publish.RemoveHandler(e)

   //Definition of the "Name" property
   member this.Name
        with get() = name
        and  set(v) =
             name <- v
             event.Trigger(this, new PropertyChangedEventArgs("Name"))

   //Definition of the "SearchCommand"
   member this.SearchCommand
        with get() = searchCommand

Cool, don’t you love this F# syntax? It’s so readable :)

Now we are ready to bind the MainPageVM to a xaml view inserting this simple code:

<StackPanel Orientation="Vertical">
     <!-- Example of binding to a F# ViewModel Command -->
     <Button Height="40" Content="Click me!"
           cmd:Click.Command="{Binding SearchCommand}"
           cmd:Click.CommandParameter="Hello from a ViewModel F# Command parameter"/>

     <!-- Example of binding to a F# ViewModel property -->
     <TextBlock Text="{Binding Name}" Height="40"/>
</StackPanel>

To make the ViewModel magic work, just assign the MainPageView DataContext with the F# ViewModel:

public MainPageView()
   {
       InitializeComponent();
       this.DataContext = new MainPageVM();
   }

The source code is available for download here.

New: updated the source code for Visual Studio 2010 Beta 2.

Happy Silverlighting!!


Sep 6 2009

NDepend: a great tool to analyze Silverlight / Expression assemblies and save precious time

I usually work with early-stage products containing poor or no documentation, in such cases a tool to help understand the tools and libraries you are using can really be a time saver.

Recently I’ve received a gift by Patrick Smacchia, Microsoft C# MVP, author of a cool tool named NDepend which permits to analyze and  compare .NET libraries in order to better understand and eventually optimize your code.

In this period, a cool topic is examined in several community posts: Behaviors and their usage in Silverlight and Expression Blend. They are powerful and permit to easily reuse your code, wrap powerful animation and effects in your libraries and then visually insert them in your application using Blend (in this way the designer/developer work-flow integration is really simplified).

If you use a behavior in your application, you have to write something similar this, where interactivity represents the System.Windows.Interactivity namespace (see my previous post for the source code of these behaviors):

<interactivity:Interaction.Behaviors>

<behaviors:TouchDrag TouchDragEnabled="True"/>

<behaviors:TouchZoom TouchZoomEnabled="True"/>

</interactivity:Interaction.Behaviors>

Using NDepend it’s possible to analyze this namespace and obtain a Dependency graph to better understand the internal structure of Microsoft.Expression.Interactions and System.Windows.Interactivity:

DependencyGraph

But this is only a starting point, we can also analyze the Metrics and go in more detail into the Interactivity ns (curiosity: it contains 2348 IL instructions):

InteractivityMetrics

Metrics about “Behavior<T>”, 9 IL instructions:

Metrics

Metrics about “Interaction”, 140 IL instructions:

InteractionsMetrics

Metrics about “TriggerBase”, 122 IL instructions:

InteractionsTriggerBase

The Dependency Matrix view permits to verify that  16 members of the namespace System.Windows.Interactivity are used by 36 methods of the assembly Microsoft.Expression.Interactions:

DependencyMatrix

And then left-click the dependency matrix to see a graph of the objects involved:

ObjetcsInvolvedGraph

 As you can see it’s very simple to quickly analyze (and learn) the structure of a selected library using NDepend, the graphical visualization of the relations between the objects is very useful to better understand the internals, and then become a better developer :)

More features available permit to compare different versions of the same libraries and perform custom queries to obtain more detailed information about the code using a dedicated language and syntax (this is a topic I’ve to investigate further, so stay tuned).

It’s my intention to start using NDepend regularly, its features are really incredible and are indispensable to understand the way of work of thirdy-part libraries.

Thank you Patrick for this great tool!