.NET according to Bruce

Activity Validation for Bound Properties

Advertisements

One of the readers (Andrew) of my Pro WF book recently had a question about page 114 of the book. This page contains the code for a custom activity validator class that enforces design-time requirements. In this example, I wanted to make sure that two properties of the target activity were set at design-time.

Andrew pointed out that the code only accepts statically set values for the properties. If you set these dependency properties by binding them to another property, the validation fails. He’s right. That particular example code only demonstrates how to validate against statically set values.

To solve the problem, all you need to do is call the IsBindingSet method of the base Activity class. Here is the revised code from page 114 (Listing 3-11) that now works for statically set or bound property values:


using System;
using System.Workflow.ComponentModel.Compiler;

namespace CustomActivityComponents
{
    /// <summary>
    /// Validator for MyCustomActivity
    /// </summary>
    public class MyCustomActivityValidator : ActivityValidator
    {
        public override ValidationErrorCollection Validate(
            ValidationManager manager, object obj)
        {
            ValidationErrorCollection errors = base.Validate(manager, obj);
            //only validate a single custom activity type
            if (obj is MyCustomActivity)
            {
                MyCustomActivity activity = obj as MyCustomActivity;
                //only do validation when the activity is in a workflow
                if (activity.Parent != null)
                {
                    if (activity.MyInt == 0)
                    {
                        if (!activity.IsBindingSet(MyCustomActivity.MyIntProperty))
                        {
                            errors.Add(
                                ValidationError.GetNotSetValidationError(
                                    "MyInt"));
                        }
                    }

                    if (activity.MyString == null ||
                        activity.MyString.Length == 0)
                    {
                        if (!activity.IsBindingSet(MyCustomActivity.MyStringProperty))
                        {
                            errors.Add(new ValidationError(
                                "MyString Property is incorrect", 501));
                        }
                    }
                }
            }
            return errors;
        }
    }
}
Advertisements