[WF4]WF4 Activity Validation

1. Basic Validation:

public class PersonInfo:NativeActivity {
        public string Name { getset; }
        public int Age { getset; }

        protected override void CacheMetadata(NativeActivityMetadata metadata) {            
            base.CacheMetadata(metadata);
            if (Age < 0) {
                metadata.AddValidationError("age must larger than 0");
            }
        }

        protected override void Execute(NativeActivityContext context) {
            Console.WriteLine(Name+" "+Age);
        }
    }

2. Activity Relation Validation
Think about this scenario: you create a composite activity and you want make sure that when users are using this composite activity, there should be at least one child activity.

    [Designer(typeof(MyCompositeDesigner))]
    public class MyCompositeActivity:NativeActivity {
        public Collection<Activity> Branches { getset; }
        public Collection<Variable> Variables { getset; }
        public Variable<int> LastIndexHint { getset; }
        public MyCompositeActivity() {
            Branches = new Collection<Activity>();
            Variables= new Collection<Variable>();
            LastIndexHint = new Variable<int>();
            this.Constraints.Add(CheckChild());
        }

        public static Constraint CheckChild() {
            DelegateInArgument<MyCompositeActivity> element = new DelegateInArgument<MyCompositeActivity>();
            return new Constraint<MyCompositeActivity> {
                Body = new ActivityAction<MyCompositeActivityValidationContext> {
                    Argument1 = element,
                    Handler = new AssertValidation {
                        Assertion=new InArgument<bool>(env=>(element.Get(env).Branches.Count!=0)),
                        Message=new InArgument<string>("please add children activities to this activity")
                    }
                }
            };
        }

        int activityCounter = 0;
        protected override void CacheMetadata(NativeActivityMetadata metadata) {
            metadata.SetChildrenCollection(Branches);
            metadata.SetVariablesCollection(Variables);
            metadata.AddImplementationVariable(this.LastIndexHint);
        }

        protected override void Execute(NativeActivityContext context) {
            ScheduleActivities(context);
        }

        void ScheduleActivities(NativeActivityContext context) {
            if(activityCounter<Branches.Count)
                context.ScheduleActivity(this.Branches[activityCounter++],OnActivityCompleted);
        }

        void OnActivityCompleted(NativeActivityContext context, ActivityInstance completedInstance) {
            ScheduleActivities(context);
        }
    }

 

 

For more info about creating a composite activity, please see:
http://xhinker.com/post/WF4My-Composite-Activity.aspx

 

 

 

blog comments powered by Disqus