Archive

Posts Tagged ‘Validation’

(Enterprise Validation Block, Interfaces) => BIG Trouble

January 8th, 2009

I had a first look at Microsoft’s Enterprise Validation Block 4.1 today and trashed it before I even got really started. The reason: The thing doesn’t really support OO-architectures that rely on interfaces / polymorphism.

 

I ran my test with this simple interface / implementation:

public interface IModel
{
  [StringLengthValidator(1, 5, MessageTemplate = "First rule failed.")]
  string First { get; set; }

  [StringLengthValidator(1, 5, MessageTemplate = "Second rule failed.")]
  string Second { get; set; }

  [StringLengthValidator(1, 5, MessageTemplate = "Third rule failed.")]
  string Third { get; set; }
}

public class Model : IModel
{
  public string First { get; set; }

  public string Second { get; set; }

  public string Third { get; set; }
}
 

Now look at this test:

public void Test()
{
  Model model = new Model();

  var result = Validation.Validate(model);
  foreach (var validationResult in result)
  {
    Console.Out.WriteLine(validationResult.Message);
  }
}

 

The code above won’t output a single validation error, because it only checks the Model class for validation attributes. And there are none – the rules have been declared in the IModel interface. My bad.
The code below, on the other hand, works. Notice that the model variable is declared using the interface type:

public void Test()
{
  IModel model = new Model();

  var result = Validation.Validate(model);
  foreach (var validationResult in result)
  {
    Console.Out.WriteLine(validationResult.Message);
  }
}

 

Now, it gets really ugly when you’re having attributes at different places. After this initial test, I moved the third validation rule into the implementing Model class and removed the Third property from the interface:

public interface IModel
{
  [StringLengthValidator(1, 5, MessageTemplate = "First rule failed.")]
  string First { get; set; }

  [StringLengthValidator(1, 5, MessageTemplate = "Second rule failed.")]
  string Second { get; set; }
}

public class Model : IModel
{
  public string First { get; set; }

  public string Second { get; set; }

  [StringLengthValidator(1, 5, MessageTemplate = "Third rule failed.")]
  public string Third { get; set; }
}

 

As a result, validating for the IModel interface returns two validation errors, and validating for the Model class reports a single error for the third rule. Now think about handling scenarios where your class implements several interfaces that may provide validation rules. Ouch.

 

Support for inheritance was the absolute first thing I tested. Frankly, it is beyond me how this library could make it into production over a year ago with this kind of behavior.

This not only promotes bad design, it’s also dangerous as hell because refactoring silently breaks your validation.

Author: Categories: C# Tags:

Combining WPF Validation Rules and IDataErrorInfo to Resolve Conversion Errors

January 8th, 2009

This article discusses a few approaches to overcome binding conversion errors in WPF by combining model validation (through IDataErrorInfo) and WPF validation rules. Practically, I’m going to outline three approaches to the same solution:

  • Inline declaration
  • Using attached properties
  • Using custom binding classes

 

image

The Problem

WPF validation through IDataErrorInfo is a great feature if you already have validation logic in you model. However: There is a problem if the user enters a value that cannot be written to model due to value conversion errors. Let’s start with a simple sample:

  • A TextBox is bound to a numeric Age property of your model.
  • As soon as the user enters a value in the Textbox, the property on the model is updated. The model then validates whether the entered value is valid (range from 1 to 130 years).
  • However: If the user enters a string rather than a number (e.g. “30a”), the value conversion to an integer fails. In this case, WPF does not show an error at all:

image

 

Karl Shifflet recently updated his article on this very subject, where he outlines an MVVM-based approach to the problem (highly recommended reading material!).

In my case, however, I was looking for a simpler solution. I had validation and views already in place and just wanted a visual representation of invalid input that cannot be bound to the model.

 

WPF Validation Rules to the Rescue

And this is where the good old WPF Validation Rules come back into play:

  1. A binding with ValidatesOnDataErrors=True ensures that the model validation logic is being invoked.
  2. Additional WPF Validation Rules take care of invalid input that can not be bound to the model.

 

<TextBox x:Name="txtAge">
  
  <TextBox.Text>
    <Binding Path="Age" ValidatesOnDataErrors="True">
      <Binding.ValidationRules>
        <rules:NumericRule />
      </Binding.ValidationRules>
    </Binding>
  </TextBox.Text>

</TextBox>

 

That’s it already! An invalid numeric value (below minimum, above maximum) is handled by the model, everything else is caught be the NumericRule (see attached sample for the sources).

image

 

Simplify Markup 1: Attached Properties

The above sample has one catch – it forces me to write rather verbose XAML. This is where attached properties come to the rescue. Here’s the same thing using an attached property:

 

<TextBox x:Name="txtAge"
  Text="{Binding Path=Age, ValidatesOnDataErrors=True}"
  rules:Editors.TextRule="{StaticResource numericRule}"  
/>

 

In the sample above, I declared an attached property of type ValidationRule that points to by custom rule. However, depending on your case, you can make your attached property as simple/complex as you need. A great article on this subject was published by WPF master Josh Smith on CodeProject, where he outlines this exact pattern.

 

Simplify Markup 2: Custom Binding Classes

As an alternative to attached properties – especially in case you want to define multiple parameters – a custom binding expression might be a simpler approach. If you use a simple Decorator helper class, creating your custom binding class is a breeze:

 

<TextBox x:Name="txtCustomBinding"
  Text="{local:RuleBinding Path=Age, MinValueOverride=20}"
/>

 

Here’s my custom binding class, derived from BindingDecoratorBase:

using System;
using System.Windows.Controls;
using System.Windows.Data;
using Hardcodet.Wpf.ValidationRules;

namespace Hardcodet.Wpf.CustomBinding
{
  /// <summary>
  /// A binding extension that checks for a given
  /// numeric value.
  /// </summary>
  public class RuleBinding : BindingDecoratorBase
  {
    /// <summary>
    /// An optional override for the minimum value,
    /// that can be used to narrow the allowed range.
    /// </summary>
    public int? MinValueOverride { get; set; }


    /// <summary>
    /// Creates a new instance of the binding with default values.
    /// </summary>
    public RuleBinding()
    {
      //set default binding directives
      ValidatesOnDataErrors = true;
      UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
    }


    /// <summary>
    /// This method is being invoked during initialization.
    /// </summary>
    /// <param name="provider">Provides access to the bound items.</param>
    /// <returns>The binding expression that is created by
    /// the base class.</returns>
    public override object ProvideValue(IServiceProvider provider)
    {
      //create the validation rule
      ValidationRule rule;
      if (MinValueOverride.HasValue)
      {
        //create a rule that also narrows the minimum value
        rule = new MinNumericRule() {MinValue = MinValueOverride.Value};
      }
      else
      {
        //just make sure the value is numeric
        rule = new NumericRule();
      }

      Binding.ValidationRules.Add(rule);

      //delegate binding creation etc. to the base class
      object val = base.ProvideValue(provider);
      return val;
    }
  }
}

 

The attached sample shows you all the techniques I described above.

Download sample project: validationrules.zip

kick it on DotNetKicks.com

Author: Categories: Uncategorized Tags: ,