Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework UI Validation using WinForms

I'm interested in setting up client side validation using a WinForms application and Entity Framework 5. I understand that there's the IValidatableObject interface that I can implement to perform and custom validation that I may need for each entity.

However, since I'm using WinForms I'd like to use the ErrorProvider to present the user with a nice notification when there is a validation error as they fill out a form. Is this functionality able to be achieved using the IValidatableObject interface or would I need to implement the IDataErrorInfo interface on my entities as well in order to have the ErrorProvider work properly?

If you have any other suggestions on a better alternative to this please let me know and I'll gladly look into that as well.

like image 817
NuNn DaDdY Avatar asked Jan 22 '13 04:01

NuNn DaDdY


1 Answers

Lets say you have an Entity called Car and this class contains an property which need be validated.

public class Car
{
  [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public int Id { get; set; }

  // Accepted values have to be between 1 and 5.
  public int NeedToBeValidatedRange { get; set; }
}

You have to create a base class for all your entites in my example I will called Entity.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;

/// This is the base class for all entities and it provide a change notfication.
public abstract class Entity : INotifyPropertyChanged
{
  // Event fired when the property is changed!
  public event PropertyChangedEventHandler PropertyChanged;


  /// Called when int property in the inherited class is changed for ther others properties like (double, long, or other entities etc,) You have to do it.
  protected void HandlePropertyChange(ref int value, int newValue, string propertyName)
  {
    if (value != newValue)
    {
      value = newValue;
      this.Validate(propertyName);
      this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
  }

  /// Validate the property 
  /// <returns>
  /// The list of validation errors
  /// </returns>
  private ICollection<ValidationResult> PropertyValidator(string propertyName)
  {
    var validationResults = new Collection<ValidationResult>();
    PropertyDescriptor property = TypeDescriptor.GetProperties(this)[propertyName];

    Validator.TryValidateProperty(
      property.GetValue(this),
      new ValidationContext(this, null, null) { MemberName = propertyName },
      validationResults);

    return validationResults;
  }

  /// Validates the given property and return all found validation errors.
  private void Validate(string propName)
  {
    var validationResults = this.PropertyValidator(propName);
    if (validationResults.Count > 0)
    {
      var validationExceptions = validationResults.Select(validationResult => new ValidationException(validationResult.ErrorMessage));
      var aggregateException = new AggregateException(validationExceptions);
      throw aggregateException;
    }
  }
}

Now you shall modfiy the Car class and it should be like that:

public class Car : Entity
{
  private int id;
  private int needToBeValidatedRange;

  [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public int Id
  {
    get
    {
      return this.id;
    }
    set
    {
      this.HandlePropertyChange(ref this.id, value, "Id");
    }
  }

  [Range(1, 5)]
  public int NeedToBeValidatedRange
  {
    get
    {
      return this.needToBeValidatedRange;
    }
    set
    {
      this.HandlePropertyChange(ref this.needToBeValidatedRange, value, "NeedToBeValidatedRange ");
    }
  }
}

Somewhere in the user interface you are creating the car entities:

Car car1 = new Car();
car1.NeedToBeValidatedRange = 3;  // This will work!

Car car2 = new Car();
car2.NeedToBeValidatedRange = 6;  // This will throw ValidationException
  • WPF support very good ValidationException.
  • Winforms support partially ValidationException but now you are free how to handle this.
like image 163
Bassam Alugili Avatar answered Sep 18 '22 15:09

Bassam Alugili