Saturday, June 16, 2007

Validator for a custom activity in Windows Workflow

Last time I talked about adding a property to a custom activity, this time I'll talk about validating the value of that property.

So we have a custom activity called UserActivity with a property called Form and we want to ensure the workflow designer has specified a value for this property. First thing to do is write our validator class, which looks like this - 

  class UserActivityValidator : ActivityValidator
  {
    public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
    {
      UserActivity activity = (UserActivity)obj;
      ValidationErrorCollection validationErrorCollection = base.Validate(manager, obj);

      // Don't validate when the activity is standalone  
      if (activity.Parent == null)
      {
        return validationErrorCollection;
      }
      
      // check Form property has been set
      if (string.IsNullOrEmpty(activity.Form))
        validationErrorCollection.Add(ValidationError.GetNotSetValidationError("Form"));

      return validationErrorCollection;
    }
  }

All we do is override the Validate method, call the base implementation, then check to see if the activity has a parent. This check ensures we don't validate the activity when we are designing and coding the activity itself. The next line does the actual work, using a helper method provided by the ValidationError class. This can be used in the most common type of validation, checking to ensure the property has a value. If that's not what you're doing, create an instance of the ValidationError class instead, using whichever constructor you need. 

Once we've written the class all that remains is to tell WF what class should be used to validate the activity, which we do by adding an attribute to the activity declaration.

[ActivityValidator(typeof(UserActivityValidator))]
public partial class UserActivity: HandleExternalEventActivity

And that's it. Now compiling a workflow assembly using the custom activity should show a compiler error if the Form property has not been set.

No comments: