Validate input in Xamarin.Forms using INotifyDataErrorInfo, custom Behaviors, Effects and Prism

This post is also available in the Premier Developer blog.

I have recently been investigating the support available in Xamarin.Forms for validation and, in particular, researched the possibility of using INotifyDataErrorInfo to complement the traditional approach of using Behaviors.

In simple scenarios, it’s possible to perform validation by simply attaching a Behavior to the required view, as shown by the following sample code:

In this case, we are validating the input and modifying the UI if the number of characters entered is less than 5.

What about more articulated scenarios when multiple business rules are required to be checked for the input values?

In these cases, we could take advantage of other types available to make our code more structured and extensible:

  • INotifyDataErrorInfo: available in Xamarin.Forms. When implemented it permits specifying custom validation supporting multiple errors per property, cross-property errors and entity-level errors;
  • DataAnnotations decorate the data models using attributes which specify validation conditions to be applied to the specific field;
  • Forms Behaviors specify the specific UI to be applied to the specific validation scenarios, integrating with INotifyDataErrorInfo and DataAnnotations.

To start exploring this approach, I created a new Xamarin.Forms Prism solution using the Prism Template Pack which generated the following project structure:

Then, I added the following new model to be validated using DataAnnotations and INotifyDataErrorInfo:

The model uses attributes declared in the SystemComponentModel.DataAnnotations namespace which can be referenced in the solution modifying the Portable Class Library profile of the UsingValidation common project:

Quick tip: to be able to change the PCL profile I had to remove all the NuGet packages used by the common project, remove the Windows Phone 8 profile and then add back all the removed NuGet packages to the UsingValidation PCL.

To use the capability offered by INotifyDataErrorInfo, the model needs to implements 3 members defined in the interface:

  • GetErrors() returns an IEnumerable sequence of strings containing the error messages triggered by validation;
  • the HasErrors property returns a boolean value indicating if there are validation errors;
  • ErrorsChanged event can be triggered to Notify if the validation errors have been updated.

This interface is quite flexible and is designed to be customised depending on the different scenarios needed: I took as a starting point this implementation available on GitHub and modified it accordingly: I decided to separate the implementation of INotifyDataErrorInfo in a different base class called ValidationBase which contains the following code using a Dictionary<string, List<string>> needed for storing the generated validation errors:

The validation is performed by this method which evaluates the DataAnnotations decorating the model using the Validator available in the System.ComponentModel.DataAnnotations namespace and then stores the error messages in the dictionary:

At this stage, I needed a solution for linking the UI to the model, and modifying the visuals depending on the presence or not of validation errors.

The ViewModel for the sample page, contains only a property storing an instance of the item defined in the model:

Then, the corresponding XAML contains two Entry views used for input and a ListView used for showing the validation errors:

The sample page uses a Behavior called EntryValidationBehavior which take care of changing the colour of the Entry background views in the case validation errors are present:

The UI is also fine-tuned using a Xamarin.Forms effect applied only to the UWP platform, in order to change the colour of the Entry border when validation errors occur:

And this is the result when the application is executed on Android and UWP:

Conclusions

Xamarin.Forms provides a rich set of features for implementing validation: the usage of INotifyDataErrorInfo, Data Annotations, Behaviors and Effects permit the handling of complex scenarios including multiple conditions per field, cross-property validation, entity-level validation and custom UI depending on the platform.

The source code of the sample demo is available for download on GitHub here.

Happy coding!

TypedMVVM samples for Windows 10 UWP and IoC fixes

A new version of the TypedMVVM samples is now available on CodePlex and contains a basic sample targeting Windows 10 UWP.

The repository also contains a fix for the basic IoC container: now the code correctly handles the register<T>() and resolve<T>() functions and populates the internal dictionary of object instances

My friend Lee has also pushed to GitHub a new sample using TypedMVVM for web apps here: check it out!

TypedMVVM and WinJS: Binding event handlers in a ListView ItemTemplate

I have recently received a request in the TypedMVVM forums about binding event handlers to a specific WinJS ListView item template.

I’ve then decided to improve the current samples available in the repository by adding some basic commands, using the RelayCommand<T> class, that can be fired by pressing a button associated to each item of the ListView:

The key here is to add the “win-interactive” class to the specific button element contained in the template (otherwise the click event will not be triggered) and then use WinJS.Utilities.markSupportedForProcessing() in the model to allow the declarative binding to be correctly applied:

Specific instances of the ListView model can be created by the sample service responsible for initialising the ViewModel data:

As usual, the sample code is available for download here.

Cordova Windows Store apps and certificate expired error

I was updating TypedMVVM to the latest Visual Studio 2013 Update 4 and Cordova tools (using the new free Community Edition) and trying to deploy the sample to the Windows 8 emulator when I received the following

error APPX0108: The certificate specified has expired

As pointed here by Microsoft Open Technologies, the certificate available in the Visual Studio template has just expired and is not possible to deploy Windows Store apps using the old one.

To solve this problem I’ve then downloaded from here the updated certificate and copied to the following location inside the Visual Studio project:

res/native/windows/CordovaApp_TemporaryKey.pfx

The updated code is available for download on CodePlex.

TypedMVVM: Samples updated for Apache Cordova

I’ve recently installed the Multi-Device Hybrid Apps template on Visual Studio in order to try out the development of native mobile applications (targeting Android, iOS, Windows Store and Windows Phone) using HTML, CSS and JavaScript using the Apache Cordova framework.

As a first example, I decided to reuse all the TypeScript code available in my library TypedMVVM available on CodePlex.

The process was very simple and didn’t take long: I was able to quickly create a basic “Hello World” application successfully deployed on the Ripple – Nexus 7 Android emulator

TypedMVVM_Cordova

As usual, the updated code is available for download on Codeplex.

Microsoft Patterns & Practices: Prism for the Windows Runtime – My favourite resources

As you may know, the Microsoft Patterns & Practices team has recently released the final version of  “Prism for Windows Runtime“, available for download here on CodePlex.

Prism for Windows Runtime

This project contains a complete guidance for building Windows Store apps using C# and XAML and includes the following resources:

Big kudos to all the p & p team: they did an amazing job and I personally felt honored to have the possibility of providing feedback whilst the project was in development.

This is really a great guidance for building Windows Store applications that can be easily tested, maintained and extended: every developer building complex apps will benefit from it.

Other useful links:

Happy coding everyone!

Silverlight 4, MEF and MVVM: EventAggregator, ImportingConstructor and Unit Tests

I had recently the possibility to use MEF and Silverlight in a sample project together with Prism, this is for sure a great combination of frameworks for bulding applications using maintainable and extensible code. I don’t think that using MEF excludes the usage of Prism and vice versa,  the choice should be pondered and analyzed accordingly to the problem to solve.

Starting from the previous experiments, I decided to refactor and cleanup the MVVM approach in order to:

  • obtain simpler code;
  • inserting an EventAggregator managed by MEF to exchange messages;
  • maintaining the Visual Studio designer/Blend support;
  • trying a simple unit test using the framework available in the Silverlight Toolkit.
  1. Using the EventAggregator

The first step is inserting in the project the Prism EventAggregator downloading the “Microsoft.Practices.Composite.dll” and “Microsoft.Practices.Composite.Presentation.dll” libraries from the Prism site on Codeplex.

It’s now possible to make available in the application an instance of it using this syntax:

public class EventAggregatorProvider
{
   [Export(typeof(IEventAggregator))]
   public IEventAggregator eventAggregator { get { return new EventAggregator(); } }
}

In this way we are able to import it in the ViewModel class using an [ImportingConstructor] attribute:

[ImportingConstructor]
public MainPageViewModel(IEventAggregator eventAggregator, IDataItemsService dataItemsService)
{
   _eventAggregator = eventAggregator;
   _dataItemsService = dataItemsService;
}

When an [ImportingConstructor] is found, MEF looks for an [Export] for each parameter available in the constructor, in this case we must have exported an “IEventAggregator” and an “IDataItemsService”.

We are now able to access the instance of the EventAggregator and Publish/Subscribe to events using a syntax like:

//Call the Service
_dataItemsService.GetDataItems();

//Subscribe to the "DataItemsReceivedEvent"

_eventAggregator. GetEvent(). Subscribe(
    dataItemsReceived =>
    {
        this.dataItems = dataItemsReceived;
    },
    true
);

In this case we are receiving the result of the async calls via the EventAggregator and a DataItemsReceivedEvent:

public class DataItemsReceivedEvent : CompositePresentationEvent {  }

DataItemsService code publishing the Event:

//Initialize the collection
DataItemWcfService.DataItemServiceClient svc = new DataItemWcfService.DataItemServiceClient();
svc.GetDataItemsCompleted += (s1, e1) =>
{
    if (e1.Result != null)
    {
        var dataItems = new DataItems();
        e1.Result.ToList().ForEach(d =>
        {
            dataItems.Add(new DataItem() { Description = d.Description });
        });

        //Publish the DataItems
        _eventAggregator. GetEvent(). Publish(dataItems);

        isLoading = false;
    }
};
svc.GetDataItemsAsync();
isLoading = true;
}

2. Maintaining the Visual Studio designer/Blend support

In the previous experiments I enabled design-time data by inserting a new ViewModel class which can create some confusion, so I decided to skip this step and using a unique ViewModel following this approach:

  • the ViewModel parameterless constuctor contains the initialization for data to be used during design time and tests;
  • the other constructor marked with the MEF [ImportingConstructor] attribute enables initialization of services and event aggregator.
[ImportingConstructor]
public MainPageViewModel(IEventAggregator eventAggregator, IDataItemsService dataItemsService)
{
    _eventAggregator = eventAggregator;
    _dataItemsService = dataItemsService;
}

3 – Unit Test

To verify the approach described, I’ve inserted a new “Silverlight Unit Test project” to the solution (note that the “Silverlight Toolkit” must be installed to use this feature) and then a simple Test method containing the following code:

[TestClass]
public class Tests
{
    [TestMethod]
    [Description("Test the creation of a ViewModel and the initialization of Design/Test Data")]
    public void TestViewModelCreation()
    {
        var vm = new MainPageViewModel();
        Assert.IsNotNull(vm);
        Assert.AreEqual(vm.dataItems.Count, 2);
    }
}

Since MEF is only used to compose run-time Parts, I’m not using it in the Unit Tests.

So we have now a new piece of code, which I’ve called a “MEFModule” organized with a MVVM approach and ready for design-time support, unit tests and extensibility: ready to be inserted in a Navigation applicationdynamically loaded and enabled for design time using Blend Sample Data, stay tuned.

The source code is available for download here.

Happy Silverlighting!

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 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):



    <!-- Design time DataContext -->
    
        
    

    ........

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:




    <!-- Run-time DataContext composed using MEF -->

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 GetDataItems()
    {
        // Add your operation implementation here
        return new List()
        {
            new DataItemFromService() {Description="DataItem from service 1"},
            new DataItemFromService() {Description="DataItem from service 2"},
            new DataItemFromService() {Description="DataItem from service 3"}
        };
    }
}

interface IDataItemService
{
    List 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 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; }

    ///

    /// Get the Instance of the ViewModel
    /// 

    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!

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(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</pre>
Cool, don’t you love this F# syntax? It’s so readable 🙂
<p align="justify">Now we are ready to bind the MainPageVM to a xaml view inserting this simple code:</p>

<pre>

     <!-- Example of binding to a F# ViewModel Command -->
     <button></button>

     <!-- Example of binding to a F# ViewModel property -->
     

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!!