internal static string GenerateValidationErrorPrefix(Activity toValidate, ActivityUtilities.ActivityCallStack parentChain, out Activity source)
 {
     bool flag = true;
     string str = "";
     source = toValidate;
     for (int i = 0; i < parentChain.Count; i++)
     {
         ActivityUtilities.ChildActivity activity = parentChain[i];
         if (activity.Activity.MemberOf.Parent != null)
         {
             flag = false;
             break;
         }
     }
     while (source.MemberOf.Parent != null)
     {
         source = source.Parent;
     }
     if (toValidate.MemberOf.Parent != null)
     {
         return System.Activities.SR.ValidationErrorPrefixForHiddenActivity(source);
     }
     if (!flag)
     {
         str = System.Activities.SR.ValidationErrorPrefixForPublicActivityWithHiddenParent(source.Parent, source);
     }
     return str;
 }
 internal ValidationContext(ActivityUtilities.ChildActivity owner, ActivityUtilities.ActivityCallStack parentChain, ProcessActivityTreeOptions options, LocationReferenceEnvironment environment)
 {
     this.owner = owner;
     this.parentChain = parentChain;
     this.options = options;
     this.environment = environment;
 }
Ejemplo n.º 3
0
        void AddBookmark(Bookmark bookmark, BookmarkCallback callback, ActivityInstance owningInstance, BookmarkOptions options)
        {
            if (this.bookmarks == null)
            {
                this.bookmarks = new Dictionary <Bookmark, BookmarkCallbackWrapper>(Bookmark.Comparer);
            }

            bookmark.Scope = this.scope;

            BookmarkCallbackWrapper bookmarkCallbackWrapper = new BookmarkCallbackWrapper(callback, owningInstance, options)
            {
                Bookmark = bookmark
            };

            this.bookmarks.Add(bookmark, bookmarkCallbackWrapper);

            owningInstance.AddBookmark(bookmark, options);

            if (TD.CreateBookmarkIsEnabled())
            {
                TD.CreateBookmark(owningInstance.Activity.GetType().ToString(), owningInstance.Activity.DisplayName, owningInstance.Id, ActivityUtilities.GetTraceString(bookmark), ActivityUtilities.GetTraceString((BookmarkScope)bookmark.Scope));
            }
        }
Ejemplo n.º 4
0
        internal void Validate(Activity owner, ref IList <ValidationError> validationErrors)
        {
            if (this.Expression != null)
            {
                if (this.Expression.Result != null && !this.Expression.Result.IsEmpty)
                {
                    ValidationError validationError = new ValidationError(SR.ResultCannotBeSetOnArgumentExpressions, false, this.RuntimeArgument.Name, owner);
                    ActivityUtilities.Add(ref validationErrors, validationError);
                }

                ActivityWithResult actualExpression = this.Expression;

                if (actualExpression is IExpressionWrapper)
                {
                    actualExpression = ((IExpressionWrapper)actualExpression).InnerExpression;
                }

                switch (this.Direction)
                {
                case ArgumentDirection.In:
                    if (actualExpression.ResultType != this.ArgumentType)
                    {
                        ActivityUtilities.Add(
                            ref validationErrors,
                            new ValidationError(SR.ArgumentValueExpressionTypeMismatch(this.ArgumentType, actualExpression.ResultType), false, this.RuntimeArgument.Name, owner));
                    }
                    break;

                case ArgumentDirection.InOut:
                case ArgumentDirection.Out:
                    Type locationType;
                    if (!ActivityUtilities.IsLocationGenericType(actualExpression.ResultType, out locationType) ||
                        locationType != this.ArgumentType)
                    {
                        Type expectedType = ActivityUtilities.CreateActivityWithResult(ActivityUtilities.CreateLocation(this.ArgumentType));
                        ActivityUtilities.Add(
                            ref validationErrors,
                            new ValidationError(SR.ArgumentLocationExpressionTypeMismatch(expectedType.FullName, actualExpression.GetType().FullName), false, this.RuntimeArgument.Name, owner));
                    }
                    break;
                }
            }
        }
Ejemplo n.º 5
0
 public static Argument Create(Type type, ArgumentDirection direction)
 {
     return(ActivityUtilities.CreateArgument(type, direction));
 }
Ejemplo n.º 6
0
        public static void CollectMapping(Activity rootActivity1, Activity rootActivity2, Dictionary <object, SourceLocation> mapping, string path)
        {
            Activity activity = (rootActivity1.RootActivity != null) ? rootActivity1.RootActivity : rootActivity1;

            if (!activity.IsRuntimeReady)
            {
                IList <ValidationError> validationErrors = null;
                ActivityUtilities.CacheRootMetadata(activity, new ActivityLocationReferenceEnvironment(), ProcessActivityTreeOptions.ValidationOptions, null, ref validationErrors);
            }
            Activity activity2 = (rootActivity2.RootActivity != null) ? rootActivity2.RootActivity : rootActivity2;

            if (!activity2.IsRuntimeReady)
            {
                IList <ValidationError> list2 = null;
                ActivityUtilities.CacheRootMetadata(activity2, new ActivityLocationReferenceEnvironment(), ProcessActivityTreeOptions.ValidationOptions, null, ref list2);
            }
            Queue <KeyValuePair <Activity, Activity> > queue = new Queue <KeyValuePair <Activity, Activity> >();

            queue.Enqueue(new KeyValuePair <Activity, Activity>(rootActivity1, rootActivity2));
            System.Collections.Generic.HashSet <Activity> set = new System.Collections.Generic.HashSet <Activity>();
            while (queue.Count > 0)
            {
                SourceLocation location;
                KeyValuePair <Activity, Activity> pair = queue.Dequeue();
                Activity key       = pair.Key;
                Activity activity4 = pair.Value;
                set.Add(key);
                if (TryGetSourceLocation(activity4, path, out location))
                {
                    mapping.Add(key, location);
                }
                else if (!(activity4 is IExpressionContainer) && !(activity4 is IValueSerializableExpression))
                {
                    Debugger.Log(2, "Workflow", "WorkflowDebugger: Does not have corresponding Xaml node for: " + activity4.DisplayName + "\n");
                }
                if ((!(key is IExpressionContainer) && !(activity4 is IExpressionContainer)) && (!(key is IValueSerializableExpression) && !(activity4 is IValueSerializableExpression)))
                {
                    IEnumerator <Activity> enumerator  = WorkflowInspectionServices.GetActivities(key).GetEnumerator();
                    IEnumerator <Activity> enumerator2 = WorkflowInspectionServices.GetActivities(activity4).GetEnumerator();
                    bool flag  = enumerator.MoveNext();
                    bool flag2 = enumerator2.MoveNext();
                    while (flag && flag2)
                    {
                        if (!set.Contains(enumerator.Current))
                        {
                            if (enumerator.Current.GetType() != enumerator2.Current.GetType())
                            {
                                Debugger.Log(2, "Workflow", "Unmatched type: " + enumerator.Current.GetType().FullName + " vs " + enumerator2.Current.GetType().FullName + "\n");
                            }
                            queue.Enqueue(new KeyValuePair <Activity, Activity>(enumerator.Current, enumerator2.Current));
                        }
                        flag  = enumerator.MoveNext();
                        flag2 = enumerator2.MoveNext();
                    }
                    if (flag || flag2)
                    {
                        Debugger.Log(2, "Workflow", "Unmatched number of children\n");
                    }
                }
            }
        }
 private void ValidateElement(ActivityUtilities.ChildActivity childActivity, ActivityUtilities.ActivityCallStack parentChain)
 {
     Activity objA = childActivity.Activity;
     if (!this.settings.SingleLevel || object.ReferenceEquals(objA, this.rootToValidate))
     {
         if (this.settings.HasAdditionalConstraints)
         {
             bool suppressGetChildrenViolations = this.settings.OnlyUseAdditionalConstraints || this.settings.SingleLevel;
             for (Type type = objA.GetType(); type != null; type = type.BaseType)
             {
                 IList<Constraint> list;
                 if (this.settings.AdditionalConstraints.TryGetValue(type, out list))
                 {
                     ActivityValidationServices.RunConstraints(childActivity, parentChain, list, this.options, suppressGetChildrenViolations, ref this.errors);
                 }
                 if (type.IsGenericType)
                 {
                     IList<Constraint> list2;
                     Type genericTypeDefinition = type.GetGenericTypeDefinition();
                     if ((genericTypeDefinition != null) && this.settings.AdditionalConstraints.TryGetValue(genericTypeDefinition, out list2))
                     {
                         ActivityValidationServices.RunConstraints(childActivity, parentChain, list2, this.options, suppressGetChildrenViolations, ref this.errors);
                     }
                 }
             }
         }
         if (childActivity.Activity.IsExpressionRoot)
         {
             if (childActivity.Activity.HasNonEmptySubtree)
             {
                 this.expressionRoot = childActivity.Activity;
                 ActivityUtilities.FinishCachingSubtree(childActivity, parentChain, ProcessActivityTreeOptions.FullCachingOptions, new ActivityUtilities.ProcessActivityCallback(this.ValidateExpressionSubtree));
                 this.expressionRoot = null;
             }
             else if (childActivity.Activity.InternalCanInduceIdle)
             {
                 Activity activity = childActivity.Activity;
                 RuntimeArgument boundRuntimeArgument = ActivityValidationServices.GetBoundRuntimeArgument(activity);
                 ValidationError data = new ValidationError(System.Activities.SR.CanInduceIdleActivityInArgumentExpression(boundRuntimeArgument.Name, activity.Parent.DisplayName, activity.DisplayName), true, boundRuntimeArgument.Name, activity.Parent);
                 ActivityUtilities.Add<ValidationError>(ref this.errors, data);
             }
         }
     }
 }
 internal static List<Activity> GetChildren(ActivityUtilities.ChildActivity root, ActivityUtilities.ActivityCallStack parentChain, ProcessActivityTreeOptions options)
 {
     ActivityUtilities.FinishCachingSubtree(root, parentChain, options);
     List<Activity> list = new List<Activity>();
     foreach (Activity activity in WorkflowInspectionServices.GetActivities(root.Activity))
     {
         list.Add(activity);
     }
     for (int i = 0; i < list.Count; i++)
     {
         foreach (Activity activity2 in WorkflowInspectionServices.GetActivities(list[i]))
         {
             list.Add(activity2);
         }
     }
     return list;
 }
Ejemplo n.º 9
0
        internal BookmarkScope CreateAndRegisterScope(Guid scopeId, BookmarkScopeHandle scopeHandle)
        {
            if (_bookmarkManagers == null)
            {
                _bookmarkManagers = new Dictionary <BookmarkScope, BookmarkManager>();
            }

            BookmarkScope scope = null;

            if (scopeId == Guid.Empty)
            {
                //
                // This is the very first activity which started the sub-instance
                //
                scope = new BookmarkScope(GetNextTemporaryId());
                _bookmarkManagers.Add(scope, new BookmarkManager(scope, scopeHandle));

                if (TD.CreateBookmarkScopeIsEnabled())
                {
                    TD.CreateBookmarkScope(ActivityUtilities.GetTraceString(scope));
                }

                if (_uninitializedScopes == null)
                {
                    _uninitializedScopes = new List <BookmarkScope>();
                }

                _uninitializedScopes.Add(scope);
            }
            else
            {
                //
                // Try to find one in the existing sub-instances
                //
                foreach (BookmarkScope eachScope in _bookmarkManagers.Keys)
                {
                    if (eachScope.Id.Equals(scopeId))
                    {
                        scope = eachScope;
                        break;
                    }
                }

                //
                // We did not find one, e.g. the first receive will get the correlation id from the
                // correlation channel
                //
                if (scope == null)
                {
                    scope = new BookmarkScope(scopeId);
                    _bookmarkManagers.Add(scope, new BookmarkManager(scope, scopeHandle));

                    if (TD.CreateBookmarkScopeIsEnabled())
                    {
                        TD.CreateBookmarkScope(string.Format(CultureInfo.InvariantCulture, "Id: {0}", ActivityUtilities.GetTraceString(scope)));
                    }
                }

                CreateAssociatedKey(scope);
            }

            return(scope);
        }
Ejemplo n.º 10
0
        internal BookmarkScope CreateAndRegisterScope(Guid scopeId, BookmarkScopeHandle scopeHandle)
        {
            if (this.bookmarkManagers == null)
            {
                this.bookmarkManagers = new Dictionary <BookmarkScope, BookmarkManager>();
            }
            BookmarkScope key = null;

            if (scopeId == Guid.Empty)
            {
                key = new BookmarkScope(this.GetNextTemporaryId());
                this.bookmarkManagers.Add(key, new BookmarkManager(key, scopeHandle));
                if (TD.CreateBookmarkScopeIsEnabled())
                {
                    TD.CreateBookmarkScope(ActivityUtilities.GetTraceString(key));
                }
                if (this.uninitializedScopes == null)
                {
                    this.uninitializedScopes = new List <BookmarkScope>();
                }
                this.uninitializedScopes.Add(key);
                return(key);
            }
            foreach (BookmarkScope scope2 in this.bookmarkManagers.Keys)
            {
                if (scope2.Id.Equals(scopeId))
                {
                    key = scope2;
                    break;
                }
            }
            if (key == null)
            {
                key = new BookmarkScope(scopeId);
                this.bookmarkManagers.Add(key, new BookmarkManager(key, scopeHandle));
                if (TD.CreateBookmarkScopeIsEnabled())
                {
                    TD.CreateBookmarkScope(string.Format(CultureInfo.InvariantCulture, "Id: {0}", new object[] { ActivityUtilities.GetTraceString(key) }));
                }
            }
            this.CreateAssociatedKey(key);
            return(key);
        }
Ejemplo n.º 11
0
            private void ValidateElement(ActivityUtilities.ChildActivity childActivity, ActivityUtilities.ActivityCallStack parentChain)
            {
                Activity toValidate = childActivity.Activity;

                if (!_settings.SingleLevel || object.ReferenceEquals(toValidate, _rootToValidate))
                {
                    // 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)
                        {
                            IList <Constraint> policyConstraints;
                            if (_settings.AdditionalConstraints.TryGetValue(currentType, out policyConstraints))
                            {
                                RunConstraints(childActivity, parentChain, policyConstraints, _options, suppressGetChildrenViolations, ref _errors);
                            }

                            if (currentType.GetTypeInfo().IsGenericType)
                            {
                                Type genericDefinitionType = currentType.GetGenericTypeDefinition();
                                if (genericDefinitionType != null)
                                {
                                    IList <Constraint> genericTypePolicyConstraints;
                                    if (_settings.AdditionalConstraints.TryGetValue(genericDefinitionType, out genericTypePolicyConstraints))
                                    {
                                        RunConstraints(childActivity, parentChain, genericTypePolicyConstraints, _options, suppressGetChildrenViolations, ref _errors);
                                    }
                                }
                            }
                            currentType = currentType.GetTypeInfo().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 Dev10 we always used ProcessActivityTreeOptions.FullCachingOptions here, and ignored this.options.
                            // So we need to continue to do that, unless the new Dev11 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 ValidationError(SR.CanInduceIdleActivityInArgumentExpression(runtimeArgument.Name, activity.Parent.DisplayName, activity.DisplayName), true, runtimeArgument.Name, activity.Parent);
                            ActivityUtilities.Add(ref _errors, error);
                        }
                    }
                }
            }
Ejemplo n.º 12
0
        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 Dictionary <string, object>(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 ValidationContext(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 ValidationError(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)
                    {
                        object resultValidationErrors;
                        if (results.TryGetValue(Constraint.ValidationErrorListArgumentName, out resultValidationErrors))
                        {
                            IList <ValidationError> validationErrorList = (IList <ValidationError>)resultValidationErrors;

                            if (validationErrorList.Count > 0)
                            {
                                if (validationErrors == null)
                                {
                                    validationErrors = new List <ValidationError>();
                                }

                                Activity source;
                                string   prefix = ActivityValidationServices.GenerateValidationErrorPrefix(childActivity.Activity, parentChain, options, out 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);
                    }
                }
            }
        }
Ejemplo n.º 13
0
        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.
                            object inputArgumentValue = null;
                            if (inputs.TryGetValue(key, out 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)
                    {
                        if (unusedArguments == null)
                        {
                            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 CoreWf.Internals.FxTrace.Exception.Argument(parameterName, exceptionString);
                }
            }
        }
Ejemplo n.º 14
0
 public override void TraceScheduled()
 {
     if (TD.ScheduleBookmarkWorkItemIsEnabled())
     {
         TD.ScheduleBookmarkWorkItem(this.ActivityInstance.Activity.GetType().ToString(), this.ActivityInstance.Activity.DisplayName, this.ActivityInstance.Id, ActivityUtilities.GetTraceString(this.bookmark), ActivityUtilities.GetTraceString(this.bookmark.Scope));
     }
 }
Ejemplo n.º 15
0
        private static void CollectMapping(Activity rootActivity1, Activity rootActivity2, Dictionary <object, SourceLocation> mapping, string path, byte[] checksum, bool requirePrepareForRuntime)
        {
            // For x:Class, the rootActivity here may not be the real root, but it's the first child
            // of the x:Class activity.
            var realRoot1 = (rootActivity1.RootActivity != null) ? rootActivity1.RootActivity : rootActivity1;

            if ((requirePrepareForRuntime && !realRoot1.IsRuntimeReady) || (!requirePrepareForRuntime && !realRoot1.IsMetadataFullyCached))
            {
                IList <ValidationError> validationErrors = null;
                ActivityUtilities.CacheRootMetadata(realRoot1, new ActivityLocationReferenceEnvironment(), ProcessActivityTreeOptions.ValidationOptions, null, ref validationErrors);
            }

            // Similarly for rootActivity2.
            var realRoot2 = (rootActivity2.RootActivity != null) ? rootActivity2.RootActivity : rootActivity2;

            if (rootActivity1 != rootActivity2 && (requirePrepareForRuntime && !realRoot2.IsRuntimeReady) || (!requirePrepareForRuntime && !realRoot2.IsMetadataFullyCached))
            {
                IList <ValidationError> validationErrors = null;
                ActivityUtilities.CacheRootMetadata(realRoot2, new ActivityLocationReferenceEnvironment(), ProcessActivityTreeOptions.ValidationOptions, null, ref validationErrors);
            }

            var pairsRemaining = new Queue <KeyValuePair <Activity, Activity> >();

            pairsRemaining.Enqueue(new KeyValuePair <Activity, Activity>(rootActivity1, rootActivity2));
            KeyValuePair <Activity, Activity> currentPair;
            var visited = new HashSet <Activity>();

            while (pairsRemaining.Count > 0)
            {
                currentPair = pairsRemaining.Dequeue();
                var activity1 = currentPair.Key;
                var activity2 = currentPair.Value;

                visited.Add(activity1);

                SourceLocation sourceLocation;
                if (TryGetSourceLocation(activity2, path, checksum, out sourceLocation))
                {
                    mapping.Add(activity1, sourceLocation);
                }
                else if (!((activity2 is IExpressionContainer) || (activity2 is IValueSerializableExpression))) // Expression is known not to have source location.
                {
                    //Some activities may not have corresponding Xaml node, e.g. ActivityFaultedOutput.
                    Trace.WriteLine("WorkflowDebugger: Does not have corresponding Xaml node for: " + activity2.DisplayName + "\n");
                }

                // This to avoid comparing any value expression with DesignTimeValueExpression (in
                // designer case).
                if (!((activity1 is IExpressionContainer) || (activity2 is IExpressionContainer) ||
                      (activity1 is IValueSerializableExpression) || (activity2 is IValueSerializableExpression)))
                {
                    var enumerator1  = WorkflowInspectionServices.GetActivities(activity1).GetEnumerator();
                    var enumerator2  = WorkflowInspectionServices.GetActivities(activity2).GetEnumerator();
                    var hasNextItem1 = enumerator1.MoveNext();
                    var hasNextItem2 = enumerator2.MoveNext();
                    while (hasNextItem1 && hasNextItem2)
                    {
                        if (!visited.Contains(enumerator1.Current))  // avoid adding the same activity (e.g. some default implementation).
                        {
                            if (enumerator1.Current.GetType() != enumerator2.Current.GetType())
                            {
                                // Give debugger log instead of just asserting; to help user find
                                // out mismatch problem.
                                Trace.WriteLine(
                                    "Unmatched type: " + enumerator1.Current.GetType().FullName +
                                    " vs " + enumerator2.Current.GetType().FullName + "\n");
                            }
                            pairsRemaining.Enqueue(new KeyValuePair <Activity, Activity>(enumerator1.Current, enumerator2.Current));
                        }
                        hasNextItem1 = enumerator1.MoveNext();
                        hasNextItem2 = enumerator2.MoveNext();
                    }

                    // If enumerators do not finish at the same time, then they have unmatched
                    // number of activities. Give debugger log instead of just asserting; to help
                    // user find out mismatch problem.
                    if (hasNextItem1 || hasNextItem2)
                    {
                        Trace.WriteLine("Unmatched number of children\n");
                    }
                }
            }
        }
Ejemplo n.º 16
0
        public static IEnumerable <Activity> GetActivities(Activity activity)
        {
            if (activity == null)
            {
                throw CoreWf.Internals.FxTrace.Exception.ArgumentNull("activity");
            }

            if (!activity.IsMetadataCached)
            {
                IList <ValidationError> validationErrors = null;

                ActivityUtilities.CacheRootMetadata(activity, new ActivityLocationReferenceEnvironment(), ProcessActivityTreeOptions.FullCachingOptions, null, ref validationErrors);

                ActivityValidationServices.ThrowIfViolationsExist(validationErrors);
            }

            int i = 0;

            for (; i < activity.RuntimeArguments.Count; i++)
            {
                RuntimeArgument argument = activity.RuntimeArguments[i];

                if (argument.BoundArgument != null && argument.BoundArgument.Expression != null)
                {
                    yield return(argument.BoundArgument.Expression);
                }
            }

            for (i = 0; i < activity.RuntimeVariables.Count; i++)
            {
                Variable variable = activity.RuntimeVariables[i];

                if (variable.Default != null)
                {
                    yield return(variable.Default);
                }
            }

            for (i = 0; i < activity.ImplementationVariables.Count; i++)
            {
                Variable variable = activity.ImplementationVariables[i];

                if (variable.Default != null)
                {
                    yield return(variable.Default);
                }
            }

            for (i = 0; i < activity.Children.Count; i++)
            {
                yield return(activity.Children[i]);
            }

            for (i = 0; i < activity.ImportedChildren.Count; i++)
            {
                yield return(activity.ImportedChildren[i]);
            }

            for (i = 0; i < activity.ImplementationChildren.Count; i++)
            {
                yield return(activity.ImplementationChildren[i]);
            }

            for (i = 0; i < activity.Delegates.Count; i++)
            {
                ActivityDelegate activityDelegate = activity.Delegates[i];

                if (activityDelegate.Handler != null)
                {
                    yield return(activityDelegate.Handler);
                }
            }

            for (i = 0; i < activity.ImportedDelegates.Count; i++)
            {
                ActivityDelegate activityDelegate = activity.ImportedDelegates[i];

                if (activityDelegate.Handler != null)
                {
                    yield return(activityDelegate.Handler);
                }
            }

            for (i = 0; i < activity.ImplementationDelegates.Count; i++)
            {
                ActivityDelegate activityDelegate = activity.ImplementationDelegates[i];

                if (activityDelegate.Handler != null)
                {
                    yield return(activityDelegate.Handler);
                }
            }
        }
        internal void CreateArgument(LocationReference sourceReference, ArgumentDirection accessDirection, bool useLocationReferenceValue = false)
        {
            ActivityWithResult expression = ActivityUtilities.CreateLocationAccessExpression(sourceReference, accessDirection != ArgumentDirection.In, useLocationReferenceValue);

            AddGeneratedArgument(sourceReference.Type, accessDirection, expression);
        }
Ejemplo n.º 18
0
        public static void ValidateArguments(Activity activity, OverloadGroupEquivalenceInfo equivalenceInfo, Dictionary <string, List <RuntimeArgument> > overloadGroups, List <RuntimeArgument> requiredArgumentsNotInOverloadGroups, IDictionary <string, object> inputs, ref IList <ValidationError> validationErrors)
        {
            if (!requiredArgumentsNotInOverloadGroups.IsNullOrEmpty())
            {
                // 1. Check if there are any Required arguments (outside overload groups) that were not specified.
                foreach (RuntimeArgument argument in requiredArgumentsNotInOverloadGroups)
                {
                    if (CheckIfArgumentIsNotBound(argument, inputs))
                    {
                        ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.RequiredArgumentValueNotSupplied(argument.Name), false, argument.Name, activity));
                    }
                }
            }

            if (!overloadGroups.IsNullOrEmpty())
            {
                //1. Check to see if any of the overload groups are configured.
                // An overload group is considered to be completely configured if all it's required arguments
                // are non-null. If an overload group does not have any required arguments then the group is
                // considered configured if any of the optional arguments are configured.
                Dictionary <string, bool> configurationResults = new Dictionary <string, bool>();
                string configuredGroupName = string.Empty;
                int    configuredCount     = 0;
                int    overloadGroupsWithNoRequiredArgs = 0;

                foreach (KeyValuePair <string, List <RuntimeArgument> > entry in overloadGroups)
                {
                    string groupName = entry.Key;
                    configurationResults.Add(groupName, false);
                    IEnumerable <RuntimeArgument> requiredArguments = entry.Value.Where((a) => a.IsRequired);

                    if (requiredArguments.Count() > 0)
                    {
                        if (requiredArguments.All(localArgument => CheckIfArgumentIsBound(localArgument, inputs)))
                        {
                            configurationResults[groupName] = true;
                            configuredGroupName             = groupName;
                            configuredCount++;
                        }
                    }
                    else
                    {
                        overloadGroupsWithNoRequiredArgs++;
                        IEnumerable <RuntimeArgument> optionalArguments = entry.Value.Where((a) => !a.IsRequired);
                        if (optionalArguments.Any(localArgument => CheckIfArgumentIsBound(localArgument, inputs)))
                        {
                            configurationResults[groupName] = true;
                            configuredGroupName             = groupName;
                            configuredCount++;
                        }
                    }
                }

                //2. It's an error if none of the groups are configured unless there
                // is atleast one overload group with no required arguments in it.
                if (configuredCount == 0)
                {
                    if (overloadGroupsWithNoRequiredArgs == 0)
                    {
                        ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.NoOverloadGroupsAreConfigured, false, activity));
                    }
                }
                //3. If only one overload group was configured, ensure none of the disjoint/overlapping groups have any
                // required or optional activity arguments set.
                else if (configuredCount == 1)
                {
                    HashSet <RuntimeArgument>   configuredOverloadSet  = new HashSet <RuntimeArgument>(overloadGroups[configuredGroupName]);
                    Predicate <RuntimeArgument> checkIfArgumentIsBound = new Predicate <RuntimeArgument>(localArgument => CheckIfArgumentIsBound(localArgument, inputs));

                    List <string> disjointGroups = null;
                    if (!equivalenceInfo.DisjointGroupsDictionary.IsNullOrEmpty())
                    {
                        equivalenceInfo.DisjointGroupsDictionary.TryGetValue(configuredGroupName, out disjointGroups);
                    }

                    List <string> overlappingGroups = null;
                    if (!equivalenceInfo.OverlappingGroupsDictionary.IsNullOrEmpty())
                    {
                        equivalenceInfo.OverlappingGroupsDictionary.TryGetValue(configuredGroupName, out overlappingGroups);
                    }

                    // Iterate over the groups that may not be completely configured.
                    foreach (string groupName in configurationResults.Keys.Where((k) => configurationResults[k] == false))
                    {
                        // Check if the partially configured group name is in the disjoint groups list.
                        // If so, find all configured arguments.
                        if (disjointGroups != null && disjointGroups.Contains(groupName))
                        {
                            foreach (RuntimeArgument configuredArgument in overloadGroups[groupName].FindAll(checkIfArgumentIsBound))
                            {
                                ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.ExtraOverloadGroupPropertiesConfigured(configuredGroupName,
                                                                                                                                          configuredArgument.Name, groupName), false, activity));
                            }
                        }
                        else if (overlappingGroups != null && overlappingGroups.Contains(groupName))
                        {
                            // Find all arguments of the Overlapping group that are not in the configuredOverloadSet.
                            HashSet <RuntimeArgument>     overloadGroupSet = new HashSet <RuntimeArgument>(overloadGroups[groupName]);
                            IEnumerable <RuntimeArgument> intersectSet     = overloadGroupSet.Intersect(configuredOverloadSet);
                            List <RuntimeArgument>        exceptList       = overloadGroupSet.Except(intersectSet).ToList();

                            foreach (RuntimeArgument configuredArgument in exceptList.FindAll(checkIfArgumentIsBound))
                            {
                                ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.ExtraOverloadGroupPropertiesConfigured(configuredGroupName,
                                                                                                                                          configuredArgument.Name, groupName), false, activity));
                            }
                        }
                    }
                }
                //4. If more than one overload group is configured, generate an error.
                else
                {
                    IEnumerable <string> configuredGroups = configurationResults.Keys.Where((k) => configurationResults[k]).OrderBy((k) => k, StringComparer.Ordinal);
                    ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.MultipleOverloadGroupsConfigured(configuredGroups.AsCommaSeparatedValues()), false, activity));
                }
            }
        }
 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 activity = childActivity.Activity;
         LocationReferenceEnvironment parentEnvironment = activity.GetParentEnvironment();
         Dictionary<string, object> inputs = new Dictionary<string, object>(2);
         for (int i = 0; i < constraints.Count; i++)
         {
             Constraint workflow = constraints[i];
             if (workflow != null)
             {
                 object obj2;
                 inputs["ToValidate"] = activity;
                 ValidationContext context = new ValidationContext(childActivity, parentChain, options, parentEnvironment);
                 inputs["ToValidateContext"] = context;
                 IDictionary<string, object> dictionary2 = null;
                 try
                 {
                     dictionary2 = WorkflowInvoker.Invoke(workflow, inputs);
                 }
                 catch (Exception exception)
                 {
                     if (Fx.IsFatal(exception))
                     {
                         throw;
                     }
                     ValidationError data = new ValidationError(System.Activities.SR.InternalConstraintException(workflow.DisplayName, activity.GetType().FullName, activity.DisplayName, exception.ToString()), false) {
                         Source = activity,
                         Id = activity.Id
                     };
                     ActivityUtilities.Add<ValidationError>(ref validationErrors, data);
                 }
                 if ((dictionary2 != null) && dictionary2.TryGetValue("ViolationList", out obj2))
                 {
                     IList<ValidationError> list = (IList<ValidationError>) obj2;
                     if (list.Count > 0)
                     {
                         Activity activity2;
                         if (validationErrors == null)
                         {
                             validationErrors = new List<ValidationError>();
                         }
                         string str = GenerateValidationErrorPrefix(childActivity.Activity, parentChain, out activity2);
                         for (int j = 0; j < list.Count; j++)
                         {
                             ValidationError item = list[j];
                             item.Source = activity2;
                             item.Id = activity2.Id;
                             if (!string.IsNullOrEmpty(str))
                             {
                                 item.Message = str + item.Message;
                             }
                             validationErrors.Add(item);
                         }
                     }
                 }
                 if (!suppressGetChildrenViolations)
                 {
                     context.AddGetChildrenErrors(ref validationErrors);
                 }
             }
         }
     }
 }
 public override void TraceStarting()
 {
     if (TD.StartBookmarkWorkItemIsEnabled())
     {
         TD.StartBookmarkWorkItem(this.ActivityInstance.Activity.GetType().ToString(), this.ActivityInstance.Activity.DisplayName, this.ActivityInstance.Id, ActivityUtilities.GetTraceString(Bookmark.AsyncOperationCompletionBookmark), ActivityUtilities.GetTraceString(Bookmark.AsyncOperationCompletionBookmark.Scope));
     }
 }
 private void ValidateExpressionSubtree(ActivityUtilities.ChildActivity childActivity, ActivityUtilities.ActivityCallStack parentChain)
 {
     if (childActivity.Activity.InternalCanInduceIdle)
     {
         Activity activity = childActivity.Activity;
         Activity expressionRoot = this.expressionRoot;
         RuntimeArgument boundRuntimeArgument = ActivityValidationServices.GetBoundRuntimeArgument(expressionRoot);
         ValidationError data = new ValidationError(System.Activities.SR.CanInduceIdleActivityInArgumentExpression(boundRuntimeArgument.Name, expressionRoot.Parent.DisplayName, activity.DisplayName), true, boundRuntimeArgument.Name, expressionRoot.Parent);
         ActivityUtilities.Add<ValidationError>(ref this.errors, data);
     }
 }
Ejemplo n.º 22
0
        internal void SetupBinding(Activity owningElement, bool createEmptyBinding)
        {
            if (this.bindingProperty != null)
            {
                Argument argument = (Argument)this.bindingProperty.GetValue(this.bindingPropertyOwner);

                if (argument == null)
                {
                    Fx.Assert(this.bindingProperty.PropertyType.IsGenericType, "We only support arguments that are generic types in our reflection walk.");

                    argument = (Argument)Activator.CreateInstance(this.bindingProperty.PropertyType);
                    argument.WasDesignTimeNull = true;

                    if (createEmptyBinding && !this.bindingProperty.IsReadOnly)
                    {
                        this.bindingProperty.SetValue(this.bindingPropertyOwner, argument);
                    }
                }

                Argument.Bind(argument, this);
            }
            else if (!this.IsBound)
            {
                PropertyInfo targetProperty = null;
                foreach (var property in owningElement.GetType().GetProperties())
                {
                    if (property.Name == this.Name && property.PropertyType.GetTypeInfo().IsGenericType)
                    {
                        ArgumentDirection direction;
                        Type argumentType;
                        if (ActivityUtilities.TryGetArgumentDirectionAndType(property.PropertyType, out direction, out argumentType))
                        {
                            if (this.Type == argumentType && this.Direction == direction)
                            {
                                targetProperty = property;
                                break;
                            }
                        }
                    }
                }

                Argument argument = null;

                if (targetProperty != null)
                {
                    argument = (Argument)targetProperty.GetValue(owningElement);
                }

                if (argument == null)
                {
                    if (targetProperty != null)
                    {
                        if (targetProperty.PropertyType.GetTypeInfo().IsGenericType)
                        {
                            argument = (Argument)Activator.CreateInstance(targetProperty.PropertyType);
                        }
                        else
                        {
                            argument = ActivityUtilities.CreateArgument(this.Type, this.Direction);
                        }
                    }
                    else
                    {
                        argument = ActivityUtilities.CreateArgument(this.Type, this.Direction);
                    }

                    argument.WasDesignTimeNull = true;

                    if (targetProperty != null && createEmptyBinding && targetProperty.CanWrite)
                    {
                        targetProperty.SetValue(owningElement, argument);
                    }
                }

                Argument.Bind(argument, this);
            }

            Fx.Assert(this.IsBound, "We should always be bound when exiting this method.");
        }
Ejemplo n.º 23
0
 public static Variable Create(string name, Type type, VariableModifiers modifiers)
 {
     return(ActivityUtilities.CreateVariable(name, type, modifiers));
 }
        public static void ValidateArguments(Activity activity, OverloadGroupEquivalenceInfo equivalenceInfo, Dictionary <string, List <RuntimeArgument> > overloadGroups, List <RuntimeArgument> requiredArgumentsNotInOverloadGroups, IDictionary <string, object> inputs, ref IList <ValidationError> validationErrors)
        {
            Func <RuntimeArgument, bool> func3      = null;
            Func <RuntimeArgument, bool> func4      = null;
            Predicate <RuntimeArgument>  predicate2 = null;

            if (!requiredArgumentsNotInOverloadGroups.IsNullOrEmpty())
            {
                foreach (RuntimeArgument argument in requiredArgumentsNotInOverloadGroups)
                {
                    if (CheckIfArgumentIsNotBound(argument, inputs))
                    {
                        ActivityUtilities.Add <ValidationError>(ref validationErrors, new ValidationError(System.Activities.SR.RequiredArgumentValueNotSupplied(argument.Name), false, argument.Name, activity));
                    }
                }
            }
            if (!overloadGroups.IsNullOrEmpty())
            {
                Func <string, bool>       func  = null;
                Func <string, bool>       func2 = null;
                Dictionary <string, bool> configurationResults = new Dictionary <string, bool>();
                string key  = string.Empty;
                int    num  = 0;
                int    num2 = 0;
                foreach (KeyValuePair <string, List <RuntimeArgument> > pair in overloadGroups)
                {
                    string str2 = pair.Key;
                    configurationResults.Add(str2, false);
                    IEnumerable <RuntimeArgument> source = from a in pair.Value
                                                           where a.IsRequired
                                                           select a;
                    if (source.Count <RuntimeArgument>() > 0)
                    {
                        if (func3 == null)
                        {
                            func3 = localArgument => CheckIfArgumentIsBound(localArgument, inputs);
                        }
                        if (source.All <RuntimeArgument>(func3))
                        {
                            configurationResults[str2] = true;
                            key = str2;
                            num++;
                        }
                    }
                    else
                    {
                        num2++;
                        if (func4 == null)
                        {
                            func4 = localArgument => CheckIfArgumentIsBound(localArgument, inputs);
                        }
                        if ((from a in pair.Value
                             where !a.IsRequired
                             select a).Any <RuntimeArgument>(func4))
                        {
                            configurationResults[str2] = true;
                            key = str2;
                            num++;
                        }
                    }
                }
                switch (num)
                {
                case 0:
                    if (num2 == 0)
                    {
                        ActivityUtilities.Add <ValidationError>(ref validationErrors, new ValidationError(System.Activities.SR.NoOverloadGroupsAreConfigured, false, activity));
                        return;
                    }
                    return;

                case 1:
                {
                    HashSet <RuntimeArgument> second = new HashSet <RuntimeArgument>(overloadGroups[key]);
                    if (predicate2 == null)
                    {
                        predicate2 = localArgument => CheckIfArgumentIsBound(localArgument, inputs);
                    }
                    Predicate <RuntimeArgument> match = predicate2;
                    List <string> list = null;
                    if (!equivalenceInfo.DisjointGroupsDictionary.IsNullOrEmpty())
                    {
                        equivalenceInfo.DisjointGroupsDictionary.TryGetValue(key, out list);
                    }
                    List <string> list2 = null;
                    if (!equivalenceInfo.OverlappingGroupsDictionary.IsNullOrEmpty())
                    {
                        equivalenceInfo.OverlappingGroupsDictionary.TryGetValue(key, out list2);
                    }
                    if (func == null)
                    {
                        func = k => !configurationResults[k];
                    }
                    foreach (string str3 in configurationResults.Keys.Where <string>(func))
                    {
                        if ((list != null) && list.Contains(str3))
                        {
                            foreach (RuntimeArgument argument2 in overloadGroups[str3].FindAll(match))
                            {
                                ActivityUtilities.Add <ValidationError>(ref validationErrors, new ValidationError(System.Activities.SR.ExtraOverloadGroupPropertiesConfigured(key, argument2.Name, str3), false, activity));
                            }
                        }
                        else if ((list2 != null) && list2.Contains(str3))
                        {
                            HashSet <RuntimeArgument>     first       = new HashSet <RuntimeArgument>(overloadGroups[str3]);
                            IEnumerable <RuntimeArgument> enumerable3 = first.Intersect <RuntimeArgument>(second);
                            foreach (RuntimeArgument argument3 in first.Except <RuntimeArgument>(enumerable3).ToList <RuntimeArgument>().FindAll(match))
                            {
                                ActivityUtilities.Add <ValidationError>(ref validationErrors, new ValidationError(System.Activities.SR.ExtraOverloadGroupPropertiesConfigured(key, argument3.Name, str3), false, activity));
                            }
                        }
                    }
                    return;
                }
                }
                if (func2 == null)
                {
                    func2 = k => configurationResults[k];
                }
                IEnumerable <string> c = configurationResults.Keys.Where <string>(func2).OrderBy <string, string>(k => k, StringComparer.Ordinal);
                ActivityUtilities.Add <ValidationError>(ref validationErrors, new ValidationError(System.Activities.SR.MultipleOverloadGroupsConfigured(c.AsCommaSeparatedValues()), false, activity));
            }
        }