Posts mit dem Label Silverlight 5 werden angezeigt. Alle Posts anzeigen
Posts mit dem Label Silverlight 5 werden angezeigt. Alle Posts anzeigen

Freitag, 29. Juni 2012

A flexible way for validation in Silverlight

There are numerous ways to do validation in Silverlight. Plenty of blog posts have been written about all of them, so I will just provide a list with links and then I will focus on the approach I implemented recently.


Binding property Mechanism Description
ValidatesOnExceptions Exceptions
  • Easy to implement
  • Synchronous
  • Only one error per property at a time.
ValidatesOnDataErrors IDataErrorInfo
  • Must not throw exception in property setter
  • Synchronous
  • Only one error per property at a time
ValidatesOnNotifyDataErrorInfo INotifyOnDataErrorInfo
  • Supports asynchronous validation
  • Can deliver multiple properties at a time
  • Enabled in Binding by default
Data Annotations Attributes
  • Easy to implement
  • Multiple validation rules per property

The INotifyOnDataErrorInfo approach provides the most flexibility. The fact that it is enabled by default saves you a lot of time in case you have a lot of views currently not using any validation rules. But the implementation of the interface seems like a lot of work. So I started thinking about how to make things easy.

How things should work

My idea was to write validation code like this:

    public String Description
    {
      get
      {
        return Get(() => Description);
      }
      set
      {
        Set(() => Description, value);
      }
    }

    public IEnumerable<ValidationError> Validate_Description()
    {
      if (Description.Length < 20)
        yield return new ValidationError("Description is too short.");
    }

The Get() / Set() methods are described in our view model base class. I wanted to use tha same aproach for validation as we use for executing commands through methods prefixed with Execute_.

How to get things to work

The wohle magic happens in the view model base class. This is the one to implement the INotifyOnDateErrorInfo interface:

public abstract class ViewModelBase :  INotifyPropertyChanged, INotifyDataErrorInfo
{
    public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

    public virtual bool HasErrors
    {
      get { return Get(() => HasErrors); }
      set { Set(() => HasErrors, value); }
    }


    public IEnumerable GetErrors(string propertyName)
    {
      
    }

    protected virtual void OnValidationChanged(String PropertyName)
    {
      if (ErrorsChanged != null)
        ErrorsChanged(this, new DataErrorsChangedEventArgs(PropertyName));
    }
}

In the constructor of the class we scan for methods that start with the prefix Validate_ to create validation rules for them. To do so, we define an interface IValidationRule and a class RelayValidator - very similar to the ICommand / RelayCommand implementation:

public interface IValidationRule
{
  IEnumerable<ValidationError> GetValidationErrors(Object Value);
}

public class RelayValdiator : IValidationRule
{
  private Func<object, IEnumerable<ValidationError>> ValidateFunction;
  
  public RelayValdiator(Func<Object, IEnumerable<ValidationError>> Validator)
  {
    this.ValidateFunction = Validator;
  }

  public IEnumerable<ValidationError> GetValidationErrors(Object Value)
  {
    return ValidateFunction(Value);
  }
}

The object parameter passed to the GetValidationErrors method is the property value to be validated. Now we can build up a Dictionary<String, List<IValidationRule>> containing the property name as key and a list of validation rules for the property (as I wanted to be able to have multiple validation rules later).

var ValidateMethodNames = 
  this.GetType().GetMethods()
      .Where(m => m.Name.StartsWith(VALIDATE_PREFIX))
      .Select(m => m.Name.StripLeft(VALIDATE_PREFIX.Length));

var result = ValidateMethodNames
      .ToDictionary(
        name => name, 
        name => new List<IValidationRule>() 
        { 
          new RelayValdiator(x => GetValidationErrors(name, x)) 
        }
      );

The function GetValidationErrors is defined in the base class as well:

private IEnumerable<ValidationError> GetValidationErrors(
                                                   String PropertyName, Object PropertyValue)
  {
    var validateMethodInfo = ViewModel.GetType().GetMethod(VALIDATE_PREFIX + PropertyName);
    if (validateMethodInfo == null)
      return null;

    return (IEnumerable<ValidationError>)
            validateMethodInfo.Invoke(ViewModel, 
            validateMethodInfo.GetParameters().Length == 1 ? new[] { PropertyValue } : null);
    }

The method takes the passed in method name, looks up the method in the class via reflection and invokes it. One little trick is done here anyway: the Validate_Description method as shown above does not take a parameter, as we do not need it in the view model where we can access the value directly. So we see wether we have a parameter and if not, we just do not pass it.

With this in place, we can easily implement the GetErrors method, where m_ValidationRules is the above constructed dictionary.

public IEnumerable GetErrors(string propertyName)
{
  if (propertyName.IsNullOrEmpty())
    return null;

  if (m_ValidateionRules == null)
    return null;

  if (!m_ValidateionRules.ContainsKey(propertyName))
    return null;

  var rules = m_ValidateionRules[propertyName];
  var result = rules.SelectMany(r => r.GetValidationErrors(Get<Object>(propertyName)))
                    .Select(e => new ValidationError(propertyName, e.ErrorMessage));

  // Update HasErrors property

  return result;
}

As mentioned before, the Get<Object>(propertyName) method is part of the view model and delivers the value of a property given its name. It is based on a dictionary as well.

The one thing we missed so far is the HasErrors property. Of course we want it to be set automatically according to the validation errors. So we introduce a list of property names with properties being in an errenous state. Each time we encounter an error we add the name to the list, otherwise we remove it. So if the list contains any element HasErrors must be true, if it is empty it must be false. This is done by the following code, to be inserted in the above listing at the comment:

var propertyHasErrors = result != null && result.Count() > 0;

if (propertyHasErrors)
  if (!m_ErrorProperties.Contains(propertyName))
    m_ErrorProperties.Add(propertyName);
else
  m_ErrorProperties.Remove(propertyName));

HasErrors = m_ErrorProperties.Count != 0;

Further steps

In the first place there is quite some code to write to get things working. But once you have it, you can do some other neat things. For example you can define attributes for validation:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class IsNotNullValidation : Attribute, IValidationRule
{
  public IEnumerable<ValidationError> GetValidationErrors(object Value)
  {
    var StringValue = Value as String;

    if (StringValue != null && StringValue.IsNullOrEmpty())
    {
      yield return new ValidationError("Der Wert darf nicht leer sein.");
    }

    if (Value == null)
      yield return new ValidationError("Der Wert darf nicht leer sein.");
  }
}

You can stack them on top of your properties. The only thing to do is to not only scan for perfixed methods but for attributes as well and add them to your dictionary.

Happy validating!

Mittwoch, 13. Juni 2012

Get hold of the view in the view model

The Problem


Triggered by a tweet from Vaughn Vernon about the question on how to get a reference to the view in a view model I decided to post the solution I used for this.

In general it is not a good practice though, but I needed it sometime as well (mostly because of some part of the system that was not designed with MVVM in mind).

The Solution


I defined an interface for the view and let the view implement it. The interface contains a a reference to the view model through an interface. The view model resides in the views DataContext so we route the property to this:

public interface IView
{ 
  IViewModel ViewModel { get; set; }
}

public partial class View : UserControl, IView
{ 
  public IViewModel ViewModel 
  { 
    get { return DataContext as IViewModel; }
    set { this.DataContext = value; } 
  }
}

The interface for the view model contains a reference to the view through its interface.

public interface IViewModel
{ 
    IView View { get; set; }
}

public class ViewModel : VMBase, IViewModel
{ 
    public IView View { get; set; }
}

Now in the XAML of the view I wire up the view model

<UserControl>
    <UserControl.DataContext>
        <local:ViewModel />
    </UserControl.DataContext>
</UserControl>

In the loaded-event of the view I set the reference back to the view model:

public void Control_Loaded(Object sender, EventArgs e)
{
  if (ViewModel != null)
    ViewModel.View = this;
}

And thats it.

What I like about this solution is that your view / view model know each other only by means of an interface, which gives you a certain amount of decoupling. But it is quite a bit of additional code...

The Drawbacks

As I mentioned earlier it is generally not a good practice to try to do this. Mostly it points to the fact that the system is not MVVMable - but sometimes reality knocks at the door...
A problem with this apporach is timing. If you need the view reference say in the constructor of your view model you wont be successful with the above technique. But you can use it in commands or any time after the view was loaded which was always sufficient for me.
Finally I don't claim that this is a general purpose solution to all cases one might want to use this - it is just what did the job for me.

Maybe it might be helpful to someone else...





Montag, 21. Mai 2012

Limits of COM Interop in Silverlight 5?

You can read a whole lot of posts about the P/Invoke capabilities of Silverlight 5. For some weired reasons I needet to initiatie an OLE Drag and Drop from Silverlight to Visual Basic 6.

I thought to use P/Invoke to call the Ole32.dll DoDragDrop Method, which is used under the hood by equally named WinForms function. It has the following signature:

[DllImport("ole32.dll")]
static extern int DoDragDrop(IDataObject pDataObject, IDropSource pDropSource,
   int dwOKEffect, int[] pdwEffect);

Even though there is a IDataObject Interface in Silverlight it is not the matching one for this COM call. So I decided to marshal it by hand, as well as the IDropSource interface. This is were the trouble starts.

The IDataObject interface looks like this (at least this is what I think is right):

  [ComImport]
  [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
  [Guid("0000010E-0000-0000-C000-000000000046")]
  public interface IDataObject
  {
    void GetData([In] ref FORMATETC format, out STGMEDIUM medium);
    void GetDataHere([In] ref FORMATETC format, ref STGMEDIUM medium);
    [PreserveSig]
    int QueryGetData([In] ref FORMATETC format);
    [PreserveSig]
    int GetCanonicalFormatEtc([In] ref FORMATETC formatIn, out FORMATETC formatOut);
    void SetData([In] ref FORMATETC formatIn, [In] ref STGMEDIUM medium,
      bool release);

    IEnumFORMATETC EnumFormatEtc(DATADIR direction);
    [PreserveSig]
    int DAdvise([In] ref FORMATETC pFormatetc, ADVF advf, IAdviseSink adviseSink, out int connection);
    void DUnadvise(int connection);
    [PreserveSig]
    int EnumDAdvise(out IEnumSTATDATA enumAdvise);
  }

As you can see, there are lots of other types and interfaces in there. All in all there are nine further interfaces, six structs and six enumerations needed to merely define this interface. I did all of it, but when I try to run the code I get the following error:



The error message is "Invalid managed / unmanaged type combination" - which is refered to on stack overflow with the solution that the struct layout must be set to sequential. I felt that this was not my problem but I tried it - with no luck.

What makes me wonder is the second part of the error message. It tells us that marshalling from and to COM interface pointer is not supported. As far as I can see this is a limitation of P/Invoke in Silverlight - but I can find no reference elsewehere on the net. All P/Invoke samples call rather simple functions that accept only primitive data types.

Anyway I have uploaded the whole source code so anyone who feels lucky today can give it a try...