-
Notifications
You must be signed in to change notification settings - Fork 231
Expand file tree
/
Copy pathActivityValidationServices.cs
More file actions
586 lines (496 loc) · 25 KB
/
ActivityValidationServices.cs
File metadata and controls
586 lines (496 loc) · 25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
// This file is part of Core WF which is licensed under the MIT license.
// See LICENSE file in the project root for full license information.
using System.Activities.Runtime;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
namespace System.Activities.Validation;
public static class ActivityValidationServices
{
private static readonly ValidationSettings defaultSettings = new();
internal static readonly ReadOnlyCollection<Activity> EmptyChildren = new(Array.Empty<Activity>());
internal static ReadOnlyCollection<ValidationError> EmptyValidationErrors = new(new List<ValidationError>(0));
public static ValidationResults Validate(Activity toValidate) => Validate(toValidate, defaultSettings);
public static ValidationResults Validate(Activity toValidate, ValidationSettings settings)
{
if (toValidate == null)
{
throw FxTrace.Exception.ArgumentNull(nameof(toValidate));
}
if (settings == null)
{
throw FxTrace.Exception.ArgumentNull(nameof(settings));
}
if (toValidate.HasBeenAssociatedWithAnInstance)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.RootActivityAlreadyAssociatedWithInstance(toValidate.DisplayName)));
}
if (settings.PrepareForRuntime && (settings.SingleLevel || settings.SkipValidatingRootConfiguration || settings.OnlyUseAdditionalConstraints))
{
throw FxTrace.Exception.Argument(nameof(settings), SR.InvalidPrepareForRuntimeValidationSettings);
}
InternalActivityValidationServices validator = new(settings, toValidate);
return validator.InternalValidate();
}
public static Activity Resolve(Activity root, string id) => WorkflowInspectionServices.Resolve(root, id);
internal static void ThrowIfViolationsExist(IList<ValidationError> validationErrors, ExceptionReason reason = ExceptionReason.InvalidTree)
{
Exception exception = CreateExceptionFromValidationErrors(validationErrors, reason);
if (exception != null)
{
throw FxTrace.Exception.AsError(exception);
}
}
private static Exception CreateExceptionFromValidationErrors(IList<ValidationError> validationErrors, ExceptionReason reason)
{
if (validationErrors != null && validationErrors.Count > 0)
{
string exceptionString = GenerateExceptionString(validationErrors, reason);
if (exceptionString != null)
{
return new InvalidWorkflowException(exceptionString);
}
}
return null;
}
internal static List<Activity> GetChildren(ActivityUtilities.ChildActivity root, ActivityUtilities.ActivityCallStack parentChain, ProcessActivityTreeOptions options)
{
ActivityUtilities.FinishCachingSubtree(root, parentChain, options);
List<Activity> listOfChildren = new();
foreach (Activity activity in WorkflowInspectionServices.GetActivities(root.Activity))
{
listOfChildren.Add(activity);
}
int toProcessIndex = 0;
while (toProcessIndex < listOfChildren.Count)
{
foreach (Activity activity in WorkflowInspectionServices.GetActivities(listOfChildren[toProcessIndex]))
{
listOfChildren.Add(activity);
}
toProcessIndex++;
}
return listOfChildren;
}
internal static void ValidateRootInputs(Activity rootActivity, IDictionary<string, object> inputs)
{
IList<ValidationError> validationErrors = null;
ValidationHelper.ValidateArguments(rootActivity, rootActivity.EquivalenceInfo, rootActivity.OverloadGroups, rootActivity.RequiredArgumentsNotInOverloadGroups, inputs, ref validationErrors);
// Validate if there are any extra arguments passed in the input dictionary
if (inputs != null)
{
List<string> unusedArguments = null;
IEnumerable<RuntimeArgument> arguments = rootActivity.RuntimeArguments.Where((a) => ArgumentDirectionHelper.IsIn(a.Direction));
foreach (string key in inputs.Keys)
{
bool found = false;
foreach (RuntimeArgument argument in arguments)
{
if (argument.Name == key)
{
found = true;
// Validate if the input argument type matches the expected argument type.
if (inputs.TryGetValue(key, out object inputArgumentValue))
{
if (!TypeHelper.AreTypesCompatible(inputArgumentValue, argument.Type))
{
ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.InputParametersTypeMismatch(argument.Type, argument.Name), rootActivity));
}
}
// The ValidateArguments will validate Required in-args and hence not duplicating that validation if the key is not found.
break;
}
}
if (!found)
{
unusedArguments ??= new List<string>();
unusedArguments.Add(key);
}
}
if (unusedArguments != null)
{
ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.UnusedInputArguments(unusedArguments.AsCommaSeparatedValues()), rootActivity));
}
}
if (validationErrors != null && validationErrors.Count > 0)
{
string parameterName = "rootArgumentValues";
ExceptionReason reason = ExceptionReason.InvalidNonNullInputs;
if (inputs == null)
{
parameterName = "program";
reason = ExceptionReason.InvalidNullInputs;
}
string exceptionString = GenerateExceptionString(validationErrors, reason);
if (exceptionString != null)
{
throw FxTrace.Exception.Argument(parameterName, exceptionString);
}
}
}
internal static void ValidateArguments(Activity activity, bool isRoot, ref IList<ValidationError> validationErrors)
{
Fx.Assert(activity != null, "Activity to validate should not be null.");
if (ValidationHelper.GatherAndValidateOverloads(activity, out Dictionary<string, List<RuntimeArgument>> overloadGroups, out List<RuntimeArgument> requiredArgumentsNotInOverloadGroups, out ValidationHelper.OverloadGroupEquivalenceInfo equivalenceInfo, ref validationErrors))
{
// If we're not the root and the overload groups are valid
// then we validate the arguments
if (!isRoot)
{
ValidationHelper.ValidateArguments(activity, equivalenceInfo, overloadGroups, requiredArgumentsNotInOverloadGroups, null, ref validationErrors);
}
}
// If we are the root, regardless of whether the groups are
// valid or not, we cache the group information
if (isRoot)
{
activity.OverloadGroups = overloadGroups;
activity.RequiredArgumentsNotInOverloadGroups = requiredArgumentsNotInOverloadGroups;
activity.EquivalenceInfo = equivalenceInfo;
}
}
private static string GenerateExceptionString(IList<ValidationError> validationErrors, ExceptionReason reason)
{
// 4096 is an arbitrary constant. Currently clipped by character count (not bytes).
const int maxExceptionStringSize = 4096;
StringBuilder exceptionMessageBuilder = null;
for (int i = 0; i < validationErrors.Count; i++)
{
ValidationError validationError = validationErrors[i];
if (!validationError.IsWarning)
{
// create the common exception string
if (exceptionMessageBuilder == null)
{
exceptionMessageBuilder = new StringBuilder();
switch (reason)
{
case ExceptionReason.InvalidTree:
exceptionMessageBuilder.Append(SR.ErrorsEncounteredWhileProcessingTree);
break;
case ExceptionReason.InvalidNonNullInputs:
exceptionMessageBuilder.Append(SR.RootArgumentViolationsFound);
break;
case ExceptionReason.InvalidNullInputs:
exceptionMessageBuilder.Append(SR.RootArgumentViolationsFoundNoInputs);
break;
}
}
string activityName = validationError.Source == null ? "<UnknownActivity>" : validationError.Source.DisplayName;
exceptionMessageBuilder.AppendLine();
exceptionMessageBuilder.Append(string.Format("'{0}': {1}", activityName, validationError.Message));
if (exceptionMessageBuilder.Length > maxExceptionStringSize)
{
break;
}
}
}
string exceptionString = null;
if (exceptionMessageBuilder != null)
{
exceptionString = exceptionMessageBuilder.ToString();
if (exceptionString.Length > maxExceptionStringSize)
{
string snipNotification = SR.TooManyViolationsForExceptionMessage;
exceptionString = exceptionString[..(maxExceptionStringSize - snipNotification.Length)];
exceptionString += snipNotification;
}
}
return exceptionString;
}
internal static string GenerateValidationErrorPrefix(Activity toValidate, ActivityUtilities.ActivityCallStack parentChain, ProcessActivityTreeOptions options, out Activity source)
{
bool parentVisible = true;
string prefix = "";
source = toValidate;
// Processing for implementation of activity
// during build time
if (options.SkipRootConfigurationValidation)
{
// Check if the activity is a implementation child
if (toValidate.MemberOf.Parent != null)
{
// Check if activity is an immediate implementation child
// of x:class activity. This means that the activity is
// being designed and hence we do not want to add the
// prefix at build time
if (toValidate.MemberOf.Parent.Parent == null)
{
prefix = "";
source = toValidate;
}
else
{
// This means the activity is a child of immediate implementation child
// of x:class activity which means the activity is not visible.
// The source points to the first visible parent activity in the
// parent chain.
while (source.MemberOf.Parent.Parent != null)
{
source = source.Parent;
}
prefix = SR.ValidationErrorPrefixForHiddenActivity(source);
}
return prefix;
}
}
// Find out if any of the parents of the activity are not publicly visible
for (int i = 0; i < parentChain.Count; i++)
{
if (parentChain[i].Activity.MemberOf.Parent != null)
{
parentVisible = false;
break;
}
}
// Figure out the source of validation error:
// - For hidden activity - source will be closest visible public parent
// - For visible activity - source will be the activity itself
// In current design an activity is visible only if it is in the root id space.
// In future, if we provide a knob for the user to specify the
// id spaces that are visible, then this check needs to be changed
// to iterate over the parentChain and find the closest parent activity that
// is in the visible id spaces.
while (source.MemberOf.Parent != null)
{
source = source.Parent;
}
if (toValidate.MemberOf.Parent != null)
{
// Activity itself is hidden
prefix = SR.ValidationErrorPrefixForHiddenActivity(source);
}
else
{
if (!parentVisible)
{
// Activity itself is public but has a private parent
prefix = SR.ValidationErrorPrefixForPublicActivityWithHiddenParent(source.Parent, source);
}
}
return prefix;
}
internal static void RunConstraints(ActivityUtilities.ChildActivity childActivity, ActivityUtilities.ActivityCallStack parentChain, IList<Constraint> constraints, ProcessActivityTreeOptions options, bool suppressGetChildrenViolations, ref IList<ValidationError> validationErrors)
{
if (constraints != null)
{
Activity toValidate = childActivity.Activity;
LocationReferenceEnvironment environment = toValidate.GetParentEnvironment();
Dictionary<string, object> inputDictionary = new(2);
for (int constraintIndex = 0; constraintIndex < constraints.Count; constraintIndex++)
{
Constraint constraint = constraints[constraintIndex];
// there may be null entries here
if (constraint == null)
{
continue;
}
inputDictionary[Constraint.ToValidateArgumentName] = toValidate;
ValidationContext validationContext = new(childActivity, parentChain, options, environment);
inputDictionary[Constraint.ToValidateContextArgumentName] = validationContext;
IDictionary<string, object> results = null;
try
{
results = WorkflowInvoker.Invoke(constraint, inputDictionary);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
ValidationError constraintExceptionValidationError = new(SR.InternalConstraintException(constraint.DisplayName, toValidate.GetType().FullName, toValidate.DisplayName, e.ToString()), false)
{
Source = toValidate,
Id = toValidate.Id
};
ActivityUtilities.Add(ref validationErrors, constraintExceptionValidationError);
}
if (results != null && results.TryGetValue(Constraint.ValidationErrorListArgumentName, out object resultValidationErrors))
{
IList<ValidationError> validationErrorList = (IList<ValidationError>)resultValidationErrors;
if (validationErrorList.Count > 0)
{
validationErrors ??= new List<ValidationError>();
string prefix = GenerateValidationErrorPrefix(childActivity.Activity, parentChain, options, out Activity source);
for (int validationErrorIndex = 0; validationErrorIndex < validationErrorList.Count; validationErrorIndex++)
{
ValidationError validationError = validationErrorList[validationErrorIndex];
validationError.Source = source;
validationError.Id = source.Id;
if (!string.IsNullOrEmpty(prefix))
{
validationError.Message = prefix + validationError.Message;
}
validationErrors.Add(validationError);
}
}
}
if (!suppressGetChildrenViolations)
{
validationContext.AddGetChildrenErrors(ref validationErrors);
}
}
}
}
internal static bool HasErrors(IList<ValidationError> validationErrors)
{
if (validationErrors != null && validationErrors.Count > 0)
{
for (int i = 0; i < validationErrors.Count; i++)
{
if (!validationErrors[i].IsWarning)
{
return true;
}
}
}
return false;
}
private class InternalActivityValidationServices
{
private readonly ValidationSettings _settings;
private readonly Activity _rootToValidate;
private IList<ValidationError> _errors;
private ProcessActivityTreeOptions _options;
private Activity _expressionRoot;
private readonly LocationReferenceEnvironment _environment;
internal InternalActivityValidationServices(ValidationSettings settings, Activity toValidate)
{
_settings = settings;
_rootToValidate = toValidate;
_environment = settings.Environment ?? new ActivityLocationReferenceEnvironment();
_environment.IsValidating = !settings.ForceExpressionCache;
if (settings.SkipExpressionCompilation)
{
_environment.CompileExpressions = true;
_environment.IsValidating = false;
}
}
internal ValidationResults InternalValidate()
{
_options = ProcessActivityTreeOptions.GetValidationOptions(_settings);
if (_settings.OnlyUseAdditionalConstraints)
{
// We don't want the errors from CacheMetadata so we send those to a "dummy" list.
IList<ValidationError> suppressedErrors = null;
ActivityUtilities.CacheRootMetadata(_rootToValidate, _environment, _options, new ActivityUtilities.ProcessActivityCallback(ValidateElement), ref suppressedErrors);
}
else
{
// We want to add the CacheMetadata errors to our errors collection
ActivityUtilities.CacheRootMetadata(_rootToValidate, _environment, _options, new ActivityUtilities.ProcessActivityCallback(ValidateElement), ref _errors);
}
return new ValidationResults(GetValidationExtensionResults().Concat(_errors ?? Array.Empty<ValidationError>()).ToList());
IEnumerable<ValidationError> GetValidationExtensionResults() =>
_environment.Extensions.All.OfType<IValidationExtension>().SelectMany(validationExtension => validationExtension.PostValidate(_rootToValidate));
}
private void ValidateElement(ActivityUtilities.ChildActivity childActivity, ActivityUtilities.ActivityCallStack parentChain)
{
Activity toValidate = childActivity.Activity;
if (_settings.SingleLevel && !ReferenceEquals(toValidate, _rootToValidate))
{
return;
}
// 0. Open time violations are captured by the CacheMetadata walk.
// 1. Argument validations are done by the CacheMetadata walk.
// 2. Build constraints are done by the CacheMetadata walk.
// 3. Then do policy constraints
if (_settings.HasAdditionalConstraints && childActivity.CanBeExecuted && parentChain.WillExecute)
{
bool suppressGetChildrenViolations = _settings.OnlyUseAdditionalConstraints || _settings.SingleLevel;
Type currentType = toValidate.GetType();
while (currentType != null)
{
if (_settings.AdditionalConstraints.TryGetValue(currentType, out IList<Constraint> policyConstraints))
{
RunConstraints(childActivity, parentChain, policyConstraints, _options, suppressGetChildrenViolations, ref _errors);
}
if (currentType.IsGenericType)
{
Type genericDefinitionType = currentType.GetGenericTypeDefinition();
if (genericDefinitionType != null)
{
if (_settings.AdditionalConstraints.TryGetValue(genericDefinitionType, out IList<Constraint> genericTypePolicyConstraints))
{
RunConstraints(childActivity, parentChain, genericTypePolicyConstraints, _options, suppressGetChildrenViolations, ref _errors);
}
}
}
currentType = currentType.BaseType;
}
}
//4. Validate if the argument expression subtree contains an activity that can induce idle.
if (childActivity.Activity.IsExpressionRoot)
{
if (childActivity.Activity.HasNonEmptySubtree)
{
_expressionRoot = childActivity.Activity;
// Back-compat: In 4.0 we always used ProcessActivityTreeOptions.FullCachingOptions here, and ignored this.options.
// So we need to continue to do that, unless the new 4.5 flag SkipRootConfigurationValidation is passed.
ProcessActivityTreeOptions options = _options.SkipRootConfigurationValidation ? _options : ProcessActivityTreeOptions.FullCachingOptions;
ActivityUtilities.FinishCachingSubtree(childActivity, parentChain, options, ValidateExpressionSubtree);
_expressionRoot = null;
}
else if (childActivity.Activity.InternalCanInduceIdle)
{
Activity activity = childActivity.Activity;
RuntimeArgument runtimeArgument = GetBoundRuntimeArgument(activity);
ValidationError error = new(SR.CanInduceIdleActivityInArgumentExpression(runtimeArgument.Name, activity.Parent.DisplayName, activity.DisplayName), true, runtimeArgument.Name, activity.Parent);
ActivityUtilities.Add(ref _errors, error);
}
}
}
private void ValidateExpressionSubtree(ActivityUtilities.ChildActivity childActivity, ActivityUtilities.ActivityCallStack parentChain)
{
Fx.Assert(_expressionRoot != null, "This callback should be called activities in the expression subtree only.");
if (childActivity.Activity.InternalCanInduceIdle)
{
Activity activity = childActivity.Activity;
Activity expressionRoot = _expressionRoot;
RuntimeArgument runtimeArgument = GetBoundRuntimeArgument(expressionRoot);
ValidationError error = new(SR.CanInduceIdleActivityInArgumentExpression(runtimeArgument.Name, expressionRoot.Parent.DisplayName, activity.DisplayName), true, runtimeArgument.Name, expressionRoot.Parent);
ActivityUtilities.Add(ref _errors, error);
}
}
}
// Iterate through all runtime arguments on the configured activity
// and find the one that binds to expressionActivity.
private static RuntimeArgument GetBoundRuntimeArgument(Activity expressionActivity)
{
Activity configuredActivity = expressionActivity.Parent;
Fx.Assert(configuredActivity != null, "Configured activity should not be null.");
RuntimeArgument boundRuntimeArgument = null;
for (int i = 0; i < configuredActivity.RuntimeArguments.Count; i++)
{
boundRuntimeArgument = configuredActivity.RuntimeArguments[i];
if (ReferenceEquals(boundRuntimeArgument.BoundArgument.Expression, expressionActivity))
{
break;
}
}
Fx.Assert(boundRuntimeArgument != null, "We should always be able to find the runtime argument!");
return boundRuntimeArgument;
}
// This method checks for duplicate evaluation order entries in a collection that is
// sorted in ascendng order of evaluation order values.
internal static void ValidateEvaluationOrder(IList<RuntimeArgument> runtimeArguments, Activity referenceActivity, ref IList<ValidationError> validationErrors)
{
for (int i = 0; i < runtimeArguments.Count - 1; i++)
{
RuntimeArgument argument = runtimeArguments[i];
RuntimeArgument nextArgument = runtimeArguments[i + 1];
if (argument.IsEvaluationOrderSpecified && nextArgument.IsEvaluationOrderSpecified
&& argument.BoundArgument.EvaluationOrder == nextArgument.BoundArgument.EvaluationOrder)
{
ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.DuplicateEvaluationOrderValues(referenceActivity.DisplayName, argument.BoundArgument.EvaluationOrder), false, argument.Name, referenceActivity));
}
}
}
internal enum ExceptionReason
{
InvalidTree,
InvalidNullInputs,
InvalidNonNullInputs,
}
}