Experiments using MEF, MVVM and Silverlight 4 Beta – Part 6: Design-mode ViewModel and calling a WCF Service

Note – this is a multi part post:

Today I had the opportunity to take a look at the code written in the previous posts and insert some new stuff in order to modify the project and make new experiments about:

  1. using a different ViewModel class for the design-time and run-time;
  2. using MEF combined with the new implicit styles feature available in Silverlight 4 Beta to initialize the DataContext of the View at run-time;
  3. retrieve the data using an async call to a WCF service and passing back the results to the VM via MEF.

1 – Using different VM classes

To accomplish this task I’ve defined a new interface named IMainPageViewModel defining these members:

/// MainPage ViewModel interface
public interface IMainPageViewModel : IViewModelBase
{
    string aViewModelProperty { get; set; }
    DataItems dataItems { get; set; }
    ICommand addDataItemCommand { get; }
}

This new interface is then implemented by two classes named ViewModels.DesignMode.MainPageViewModel and ViewModels.MainPageViewModel:

/// ViewModel for the "MainPageView" used in design-mode
public class MainPageViewModel : ViewModelBase, IMainPageViewModel
{
    public MainPageViewModel()
    {
        //Initialize the properties with test data if design mode
        aViewModelProperty = "Value - Design Mode";

        //Initialize the "dataItems" property
        dataItems = new DataItems();
        dataItems.Add(new DataItem() { Description = "Sample Data Item 1 - Design Mode" });
        dataItems.Add(new DataItem() { Description = "Sample Data Item 2 - Design Mode" });
    }

    public string aViewModelProperty { get; set; }

    public DataItems dataItems { get; set; }

    public ICommand addDataItemCommand { get; set; }
}
/// ViewModel class for the "MainPageView" using MEF
[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(MainPageViewModel))]
public class MainPageViewModel : ViewModelBase, IMainPageViewModel
{
    public MainPageViewModel() {  }

    [Import("aViewModelPropertyTextProvider")]
    public string aViewModelProperty { get; set; }

    [Import(typeof(WcfDataItems))]
    public DataItems dataItems { get; set; }

    [Import(typeof(ICommand))]
    public PartCreator<ICommand> addDataItemCommandCreator { get; set; }

    private ICommand _addDataItemCommand;
    public ICommand addDataItemCommand
    {
        get {
            if (_addDataItemCommand==null)
                _addDataItemCommand = addDataItemCommandCreator.CreatePart().ExportedValue;
            return _addDataItemCommand;
        }
    }
}

The first one is associated with the View at design-time using an attached property which permits to bind an instance only at design time using this xaml (usually you should use <d:DesignProperties.DataContext>, here we are experimenting, of course):

<UserControl x:Class="SL4_MVVM_MEF.Views.MainPageView"
    ........
    xmlns:designer="clr-namespace:SL4_MVVM_MEF.Designer"
    xmlns:providersDM="clr-namespace:SL4_MVVM_MEF.Providers.DesignMode"
    >

    <!-- Design time DataContext -->
    <designer:Page.DesignDataContext>
        <providersDM:MainPageViewModelProvider/>
    </designer:Page.DesignDataContext>

    ........

DesignTimeDataContext attached dependency property:

/// DesignDataContext Attached Dependency Property
public static readonly DependencyProperty DesignDataContextProperty =
    DependencyProperty.RegisterAttached("DesignDataContext", typeof(object), typeof(Page),
        new PropertyMetadata((object)null,
            new PropertyChangedCallback(OnDesignDataContextChanged)));

/// Gets the DesignDataContext property.
public static object GetDesignDataContext(DependencyObject d)
{
    return (object)d.GetValue(DesignDataContextProperty);
}

/// Sets the DesignDataContext property.
public static void SetDesignDataContext(DependencyObject d, object value)
{
    d.SetValue(DesignDataContextProperty, value);
}

/// Handles the DesignDataContext property changes
private static void OnDesignDataContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    FrameworkElement element = (FrameworkElement)d;

    //Get the ViewModel instance only in design mode
    if ((Application.Current == null) || (Application.Current.GetType() == typeof(Application)))
       element.DataContext = e.NewValue;
}

And this is the design-time mode in Blend using the new attached property:

MEFMVVM Blend

2 – MEF and implicit styles

The new implict styles feature available in Silverlight 4 beta is used to initialize the DataContext of the MainPageView type in a declarative way in App.xaml:

<Application xmlns="http://schemas.microsoft.com/winfx/2006/ xaml/presentation"
   xmlns:x= "http://schemas.microsoft.com/winfx/2006/xaml"
   x:Class= "SL4_MVVM_MEF.App"
   xmlns:views= "clr-namespace:SL4_MVVM_MEF.Views"
   xmlns:providers= "clr-namespace:SL4_MVVM_MEF.Providers">

<Application.Resources>
    <!-- Run-time DataContext composed using MEF -->
    <Style TargetType="views:MainPageView">
        <Setter Property="DataContext">
            <Setter.Value>
          <providers:MainPageViewModelMEFProvider/>
            </Setter.Value>
        </Setter>
    </Style>
</Application.Resources>
</Application>

In this case I’ve modified the MainPageViewModelMEFProvider class and inserted a new IViewModelProvider interface in order to obtain the instance of the ViewModel initialized by MEF:

/// Interface for the ViewModelProvider
public interface IViewModelProvider
{
    object GetViewModel { get; }
}
/// Get the ViewModel instance using MEF
public class MainPageViewModelMEFProvider : IViewModelProvider
{
    public MainPageViewModelMEFProvider() { }

    [Import(typeof(MainPageViewModel))]
    public IViewModelBase ViewModel { get; set; }

    /// Get the Instance of the ViewModel using MEF
    public object GetViewModel
    {
        get
        {
           PartInitializer.SatisfyImports(this);
           return ViewModel;
        }
    }
}

3 – retrieve the data using an async call to a WCF service

I’ve added to the solution a simple WCF service which returns a collection of DataItems:

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class DataItemService : IDataItemService
{
    [OperationContract]
    public List<DataItemFromService> GetDataItems()
    {
        // Add your operation implementation here
        return new List<DataItemFromService>()
        {
            new DataItemFromService() {Description="DataItem from service 1"},
            new DataItemFromService() {Description="DataItem from service 2"},
            new DataItemFromService() {Description="DataItem from service 3"}
        };
    }
}

interface IDataItemService
{
    List<DataItemFromService> GetDataItems();
}

public class DataItemFromService
{
    public string Description { get; set; }
}

Since the project uses MEF composition and [Import] /[Export] attributes to initialize all the members of the VM class, I’ve used the same approach for the dataItems collection, retrieving data from an async call to the WCF service using a WcfDataItems class:

/// A sample collection of DataItems from WCF
[Export(typeof(WcfDataItems))]
public class WcfDataItems : DataItems
{
    public WcfDataItems()
    {
        //Initialize the collection
        DataItemWcfService.DataItemServiceClient svc = new DataItemWcfService.DataItemServiceClient();
        svc.GetDataItemsCompleted += (s1, e1) =>
        {
            if (e1.Result != null)
                e1.Result.ToList().ForEach(d =>
                    {
                        //Retrieve a new DataItem
                        DataItem di = DataItemCreator.CreatePart().ExportedValue;
                        di.Description = d.Description;
                        this.Add(di);
                    });
            isLoading = false;
        };
        svc.GetDataItemsAsync();
        isLoading = true;
    }

    [Import(typeof(DataItem))]
    public PartCreator<DataItem> DataItemCreator { get; set; }
}

The code is available for download here.

Happy Silverlighting!

Experiments using MEF, MVVM and Silverlight 4 Beta – Part 5: Enabling Blend and the Visual Studio designer

Note – this is a multi part post:

In the last post I’ve updated the sample project introducing PartCreator<T>, in this one I will illustrate a method to make available sample data during the editing of the solution in Blend or in the Visual Studio designer, in order to obtain a result like this (a similar approach is used in the awesome MVVM light toolkit by Laurent Bugnion):

MEFMVVM Blend

First of all, I’ve created a class ViewModelProvider to obtain dinamically an instance of the ViewModel and directly used in xaml to create the VM instance, in this way it’s possibile to see sample data during the design phase:

public class ViewModelProvider : IViewModelProvider
{
    public ViewModelProvider() { }

    [Import(typeof(MainPageViewModel))]
    public IViewModelBase mainPageViewModelProvider { get; set; }

    /// <summary>
    /// Get the Instance of the ViewModel
    /// </summary>
    public IViewModelBase GetVMInstance
    {
        get
        {
            //Verify if Design Mode
            if ((Application.Current == null) || (Application.Current.GetType() == typeof(Application)))
            {
                return new MainPageViewModel();
            }
            else
            {
                //If not in Design Mode uses MEF to compose the objects
                PartInitializer.SatisfyImports(this);
                return mainPageViewModelProvider;
            }
        }
    }
}

I’ve not already found a method to activate MEF compositions during design time, so an instance of the ViewModel class is explicitely created in code if we are in the tool designers, otherwise SatisfyImports() executes the MEF magic as usually.

It’s now necessary to initialize the properties values in order to display sample data at design time, this step can be done in the constructor of the MainPageViewModel:

[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(MainPageViewModel))]
public class MainPageViewModel : ViewModelBase, IMainPageViewModel
{
    ///
    /// Default constructor
    ///
    public MainPageViewModel()
    {
        if ((Application.Current == null) || (Application.Current.GetType()==typeof(Application)))
        {
            //Initialize the properties with test data if design mode
            aViewModelProperty = "Value - Design Mode";
            dataItems = new SampleDataItems(); dataItems.ToList().ForEach(d=>d.Description+=" - Design Mode");
        }
    }

    ///
    /// A sample property
    ///
    [Import("aViewModelPropertyTextProvider")]
    public string aViewModelProperty { get; set; }

    ///
    /// A sample collection
    ///
    [Import(typeof(DataItems))]
    public DataItems dataItems { get; set; }

    ///
    /// A Part creator for the addDataItemCommandCreator
    ///
    [Import(typeof(ICommand))]
    public PartCreator addDataItemCommandCreator { get; set; }

    private ICommand _addDataItemCommand;
    public ICommand addDataItemCommand
    {
        get {
            if (_addDataItemCommand==null)
                _addDataItemCommand = addDataItemCommandCreator.CreatePart().ExportedValue;
            return _addDataItemCommand;
        }
    }
}

Inside Visual Studio, it’s now possibile to edit the User Interface and visualize the sample data defined in the constructor:

VisualStudio2010

The source code is available for download here.

Hope this helps!

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!

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!

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!

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!

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!

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!