Ejemplo n.º 1
0
        Sequence Load(TestXamls xaml)
        {
            var root    = TestHelper.GetActivityFromXamlResource(xaml);
            var results = ActivityValidationServices.Validate(root);

            return((Sequence)root.ImplementationChildren[0]);
        }
Ejemplo n.º 2
0
        public static Activity Resolve(Activity root, string id)
        {
            Activity activity;

            if (root == null)
            {
                throw FxTrace.Exception.ArgumentNull("root");
            }
            if (string.IsNullOrEmpty(id))
            {
                throw FxTrace.Exception.ArgumentNullOrEmpty("id");
            }
            if (!root.IsMetadataCached)
            {
                IList <ValidationError> validationErrors = null;
                ActivityUtilities.CacheRootMetadata(root, new ActivityLocationReferenceEnvironment(), ProcessActivityTreeOptions.FullCachingOptions, null, ref validationErrors);
                ActivityValidationServices.ThrowIfViolationsExist(validationErrors);
            }
            QualifiedId id2 = QualifiedId.Parse(id);

            if (!QualifiedId.TryGetElementFromRoot(root, id2, out activity))
            {
                throw FxTrace.Exception.Argument("id", System.Activities.SR.IdNotFoundInWorkflow(id));
            }
            return(activity);
        }
Ejemplo n.º 3
0
        public static Activity Resolve(Activity root, string id)
        {
            if (root == null)
            {
                throw FxTrace.Exception.ArgumentNull(nameof(root));
            }

            if (string.IsNullOrEmpty(id))
            {
                throw FxTrace.Exception.ArgumentNullOrEmpty(nameof(id));
            }

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

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

                ActivityValidationServices.ThrowIfViolationsExist(validationErrors);
            }

            var parsedId = QualifiedId.Parse(id);

            if (!QualifiedId.TryGetElementFromRoot(root, parsedId, out var result))
            {
                throw FxTrace.Exception.Argument(nameof(id), SR.IdNotFoundInWorkflow(id));
            }

            return(result);
        }
Ejemplo n.º 4
0
        private void ValidateWorkflowInternal(Activity workflow, string runtimeAssembly, PSWorkflowValidationResults validationResults)
        {
            Tracer.WriteMessage(Facility + "Validating a workflow.");
            _structuredTracer.WorkflowValidationStarted(Guid.Empty);

            ValidationSettings validationSettings = new ValidationSettings
            {
                AdditionalConstraints =
                {
                    { typeof(Activity), new List <Constraint> {
                          ValidateActivitiesConstraint(runtimeAssembly, validationResults)
                      } }
                }
            };

            try
            {
                validationResults.Results = ActivityValidationServices.Validate(workflow, validationSettings);
            }
            catch (Exception e)
            {
                Tracer.TraceException(e);
                ValidationException exception = new ValidationException(Resources.ErrorWhileValidatingWorkflow, e);
                throw exception;
            }

            _structuredTracer.WorkflowValidationFinished(Guid.Empty);
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            Console.WriteLine("\nMySequenceWithError");
            ShowValidationResults(ActivityValidationServices.Validate(
                                      MySequenceWithError()));

            Console.WriteLine("\nMySequenceNoError");
            ShowValidationResults(ActivityValidationServices.Validate(
                                      MySequenceNoError()));

            Console.WriteLine("\nWhileAndWriteLineError");
            ValidationSettings settings = new ValidationSettings();

            settings.AdditionalConstraints.Add(
                typeof(WriteLine), new List <Constraint>
            {
                WhileParentConstraint.GetConstraint()
            });
            ShowValidationResults(ActivityValidationServices.Validate(
                                      WhileAndWriteLine(), settings));

            Console.WriteLine("\nWhileAndWriteLineNoError");
            ShowValidationResults(ActivityValidationServices.Validate(
                                      WhileAndWriteLine()));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Verifies that a workflow activity on an <see cref="ActivityActor"/> is correctly configured according to
        /// the validation logic. This logic can be the <see cref="CodeActivity.CacheMetadata(CodeActivityMetadata)"/>
        /// method of the activities to validate, or build and policy constraints.
        /// </summary>
        /// <param name="toValidate"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public static ValidationResults Validate(ActivityActor toValidate, ValidationSettings settings)
        {
            Contract.Requires <ArgumentNullException>(toValidate != null);
            Contract.Requires <ArgumentNullException>(settings != null);

            return(ActivityValidationServices.Validate(toValidate.CreateActivityInternal(), settings));
        }
        /// <summary>
        /// Verifies that a workflow activity on an <see cref="ActivityActor"/> is correctly configured according to
        /// the validation logic. This logic can be the <see cref="CodeActivity.CacheMetadata(CodeActivityMetadata)"/>
        /// method of the activitie to validate, or build and policy constraints, descriptive message, an error code,
        /// and other information.
        /// </summary>
        /// <param name="toValidate"></param>
        /// <returns></returns>
        public static ValidationResults Validate(ActivityActor toValidate)
        {
            if (toValidate == null)
            {
                throw new ArgumentNullException(nameof(toValidate));
            }

            return(ActivityValidationServices.Validate(toValidate.CreateActivityInternal()));
        }
Ejemplo n.º 8
0
 public ValidationResults Validate(ValidationSettings settings)
 {
     if (this.workflowService != null)
     {
         return(this.workflowService.Validate(settings));
     }
     else
     {
         return(ActivityValidationServices.Validate(this.activity, settings));
     }
 }
Ejemplo n.º 9
0
        static void Main()
        {
            Activity wf1 = new CreateState
            {
                Name = "California"
            };

            ValidationResults results = ActivityValidationServices.Validate(wf1);

            Console.WriteLine("WF1:");
            PrintResults(results);

            Activity wf2 = new CreateCountry
            {
                Name   = "Mexico",
                States =
                {
                    new CreateCity
                    {
                        Name = "Monterrey"
                    }
                }
            };

            results = ActivityValidationServices.Validate(wf2);
            Console.WriteLine("WF2:");
            PrintResults(results);

            Activity wf3 = new CreateCountry
            {
                Name   = "USA",
                States =
                {
                    new CreateState
                    {
                        Name   = "Texas",
                        Cities =
                        {
                            new CreateCity
                            {
                                Name = "Houston"
                            }
                        }
                    }
                }
            };

            results = ActivityValidationServices.Validate(wf3);
            Console.WriteLine("WF3:");
            PrintResults(results);
        }
Ejemplo n.º 10
0
 private void InitializeCore(IDictionary <string, object> workflowArgumentValues, IList <Handle> workflowExecutionProperties)
 {
     if (this.extensions != null)
     {
         this.extensions.Initialize();
         if (this.extensions.HasTrackingParticipant)
         {
             this.HasTrackingParticipant = true;
             this.trackingProvider       = new System.Activities.Tracking.TrackingProvider(this.WorkflowDefinition);
             foreach (TrackingParticipant participant in this.GetExtensions <TrackingParticipant>())
             {
                 this.trackingProvider.AddParticipant(participant);
             }
         }
     }
     else
     {
         this.ValidateWorkflow(null);
     }
     this.WorkflowDefinition.HasBeenAssociatedWithAnInstance = true;
     if (workflowArgumentValues != null)
     {
         IDictionary <string, object> objA = workflowArgumentValues;
         if (object.ReferenceEquals(objA, ActivityUtilities.EmptyParameters))
         {
             objA = null;
         }
         if ((this.WorkflowDefinition.RuntimeArguments.Count > 0) || ((objA != null) && (objA.Count > 0)))
         {
             ActivityValidationServices.ValidateRootInputs(this.WorkflowDefinition, objA);
         }
         this.executor.ScheduleRootActivity(this.WorkflowDefinition, objA, workflowExecutionProperties);
     }
     else
     {
         this.executor.OnDeserialized(this.WorkflowDefinition, this);
     }
     this.executor.Open(this.SynchronizationContext);
     this.controller    = new WorkflowInstanceControl(this, this.executor);
     this.isInitialized = true;
     if ((this.extensions != null) && this.extensions.HasWorkflowInstanceExtensions)
     {
         WorkflowInstanceProxy instance = new WorkflowInstanceProxy(this);
         for (int i = 0; i < this.extensions.WorkflowInstanceExtensions.Count; i++)
         {
             this.extensions.WorkflowInstanceExtensions[i].SetInstance(instance);
         }
     }
 }
Ejemplo n.º 11
0
        static void Main()
        {
            Sequence wf = new Sequence
            {
                Activities =
                {
                    new If
                    {
                        Condition = true
                    },
                    new Pick
                    {
                        Branches =
                        {
                            new PickBranch
                            {
                                Trigger = new WriteLine
                                {
                                    Text = "When this completes..."
                                },
                                Action = new WriteLine
                                {
                                    Text = "... do this."
                                }
                            }
                        }
                    }
                }
            };

            // ValidationSettings enables the host to customize the behavior of ActivityValidationServices.Validate.
            ValidationSettings validationSettings = new ValidationSettings
            {
                // AdditionalConstraints enables the host to add specific validation logic (a constraint) to a specify type of activity in the Workflow.
                AdditionalConstraints =
                {
                    { typeof(If),   new List <Constraint> {
                          ConstraintsLibrary.ConstraintError_IfShouldHaveThenOrElse()
                      } },
                    { typeof(Pick), new List <Constraint> {
                          ConstraintsLibrary.ConstraintWarning_PickHasOneBranch()
                      } }
                }
            };

            ValidationResults results = ActivityValidationServices.Validate(wf, validationSettings);

            PrintResults(results);
        }
Ejemplo n.º 12
0
        public Activity Resolve(string id)
        {
            Fx.Assert(id != null, "id should not be null.");

            Activity activityRoot = null;

            if (this.workflowService != null)
            {
                activityRoot = this.workflowService.GetWorkflowRoot();
            }
            else
            {
                activityRoot = this.activity;
            }

            return(ActivityValidationServices.Resolve(activityRoot, id));
        }
Ejemplo n.º 13
0
        public static bool CanInduceIdle(Activity activity)
        {
            if (activity == null)
            {
                throw FxTrace.Exception.ArgumentNull(nameof(activity));
            }

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

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

                ActivityValidationServices.ThrowIfViolationsExist(validationErrors);
            }

            return(activity.InternalCanInduceIdle);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// 开始执行调试流程
        /// </summary>
        public void Debug()
        {
            //授权检测
            ViewModelLocator.Instance.SplashScreen.DoAuthorizationCheck();

            Activity workflow = ActivityXamlServices.Load(m_xamlPath);

            var result = ActivityValidationServices.Validate(workflow);

            if (result.Errors.Count == 0)
            {
                Messenger.Default.Send(this, "BeginRun");

                m_wfElementToSourceLocationMap = UpdateSourceLocationMappingInDebuggerService();
                m_activityIdToWfElementMap     = BuildActivityIdToWfElementMap(m_wfElementToSourceLocationMap);

                if (m_app != null)
                {
                    m_app.Terminate("");
                }

                m_app = new WorkflowApplication(workflow);
                m_app.OnUnhandledException = WorkflowApplicationOnUnhandledException;
                m_app.Completed            = WorkflowApplicationExecutionCompleted;

                m_simTracker = generateTracker();
                m_app.Extensions.Add(m_simTracker);
                m_app.Extensions.Add(new LogToOutputWindowTextWriter());

                if (workflow is DynamicActivity)
                {
                    var wr = new WorkflowRuntime();
                    wr.RootActivity = workflow;
                    m_app.Extensions.Add(wr);
                }

                m_app.Run();
            }
            else
            {
                // 工作流校验错误,请检查参数配置
                MessageBox.Show(App.Current.MainWindow, ResxIF.GetString("WorkflowCheckError"), ResxIF.GetString("ErrorText"), MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
Ejemplo n.º 15
0
        void InitializeCore(IDictionary <string, object> workflowArgumentValues, IList <Handle> workflowExecutionProperties)
        {
            Fx.Assert(this.WorkflowDefinition.IsRuntimeReady, "EnsureDefinitionReady should have been called");
            Fx.Assert(this.executor != null, "at this point, we better have an executor");

            // Do Argument validation for root activities
            WorkflowDefinition.HasBeenAssociatedWithAnInstance = true;

            if (workflowArgumentValues != null)
            {
                IDictionary <string, object> actualInputs = workflowArgumentValues;

                if (object.ReferenceEquals(actualInputs, ActivityUtilities.EmptyParameters))
                {
                    actualInputs = null;
                }

                if (this.WorkflowDefinition.RuntimeArguments.Count > 0 || (actualInputs != null && actualInputs.Count > 0))
                {
                    ActivityValidationServices.ValidateRootInputs(this.WorkflowDefinition, actualInputs);
                }

                this.executor.ScheduleRootActivity(this.WorkflowDefinition, actualInputs, workflowExecutionProperties);
            }
            else
            {
                this.executor.OnDeserialized(this.WorkflowDefinition, this);
            }

            this.executor.Open(this.SynchronizationContext);
            this.controller    = new WorkflowInstanceControl(this, this.executor);
            this.isInitialized = true;

            if (this.extensions != null && this.extensions.HasWorkflowInstanceExtensions)
            {
                WorkflowInstanceProxy proxy = new WorkflowInstanceProxy(this);

                for (int i = 0; i < this.extensions.WorkflowInstanceExtensions.Count; i++)
                {
                    IWorkflowInstanceExtension extension = this.extensions.WorkflowInstanceExtensions[i];
                    extension.SetInstance(proxy);
                }
            }
        }
Ejemplo n.º 16
0
 void ValidateWorkflow(WorkflowInstanceExtensionManager extensionManager)
 {
     if (!WorkflowDefinition.IsRuntimeReady)
     {
         LocationReferenceEnvironment localEnvironment = this.hostEnvironment;
         if (localEnvironment == null)
         {
             LocationReferenceEnvironment parentEnvironment = null;
             if (extensionManager != null && extensionManager.SymbolResolver != null)
             {
                 parentEnvironment = extensionManager.SymbolResolver.AsLocationReferenceEnvironment();
             }
             localEnvironment = new ActivityLocationReferenceEnvironment(parentEnvironment);
         }
         IList <ValidationError> validationErrors = null;
         ActivityUtilities.CacheRootMetadata(WorkflowDefinition, localEnvironment, ProcessActivityTreeOptions.FullCachingOptions, null, ref validationErrors);
         ActivityValidationServices.ThrowIfViolationsExist(validationErrors);
     }
 }
Ejemplo n.º 17
0
        public static void CacheMetadata(Activity rootActivity, LocationReferenceEnvironment hostEnvironment)
        {
            if (rootActivity == null)
            {
                throw FxTrace.Exception.ArgumentNull("rootActivity");
            }
            if (rootActivity.HasBeenAssociatedWithAnInstance)
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(System.Activities.SR.RootActivityAlreadyAssociatedWithInstance(rootActivity.DisplayName)));
            }
            IList <ValidationError> validationErrors = null;

            if (hostEnvironment == null)
            {
                hostEnvironment = new ActivityLocationReferenceEnvironment();
            }
            ActivityUtilities.CacheRootMetadata(rootActivity, hostEnvironment, ProcessActivityTreeOptions.FullCachingOptions, null, ref validationErrors);
            ActivityValidationServices.ThrowIfViolationsExist(validationErrors);
        }
 public static void CacheRootMetadata(Activity activity, LocationReferenceEnvironment hostEnvironment, ProcessActivityTreeOptions options, ProcessActivityCallback callback, ref IList <ValidationError> validationErrors)
 {
     if (!ShouldShortcut(activity, options))
     {
         lock (activity.ThisLock)
         {
             if (!ShouldShortcut(activity, options))
             {
                 if (activity.HasBeenAssociatedWithAnInstance)
                 {
                     throw FxTrace.Exception.AsError(new InvalidOperationException(System.Activities.SR.RootActivityAlreadyAssociatedWithInstance(activity.DisplayName)));
                 }
                 activity.InitializeAsRoot(hostEnvironment);
                 ProcessActivityTreeCore(new ChildActivity(activity, true), null, options, callback, ref validationErrors);
                 if (!ActivityValidationServices.HasErrors(validationErrors) && options.IsRuntimeReadyOptions)
                 {
                     activity.SetRuntimeReady();
                 }
             }
         }
     }
 }
Ejemplo n.º 19
0
        /// <summary>
        /// 开始执行运行流程
        /// </summary>
        public void Run()
        {
            //授权检测
            ViewModelLocator.Instance.SplashScreen.DoAuthorizationCheck();

            Activity workflow = ActivityXamlServices.Load(m_xamlPath);

            var result = ActivityValidationServices.Validate(workflow);

            if (result.Errors.Count == 0)
            {
                Messenger.Default.Send(this, "BeginRun");

                if (m_app != null)
                {
                    m_app.Terminate("");
                }

                m_app = new WorkflowApplication(workflow);
                m_app.Extensions.Add(new LogToOutputWindowTextWriter());

                if (workflow is DynamicActivity)
                {
                    var wr = new WorkflowRuntime();
                    wr.RootActivity = workflow;
                    m_app.Extensions.Add(wr);
                }

                m_app.OnUnhandledException = WorkflowApplicationOnUnhandledException;
                m_app.Completed            = WorkflowApplicationExecutionCompleted;
                m_app.Run();
            }
            else
            {
                MessageBox.Show(App.Current.MainWindow, "工作流校验错误,请检查参数配置", "错误", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// 开始执行运行流程
        /// </summary>
        public void Run()
        {
            HasException = false;

            Activity workflow = ActivityXamlServices.Load(m_xamlPath);

            var result = ActivityValidationServices.Validate(workflow);

            if (result.Errors.Count == 0)
            {
                Logger.Debug(string.Format("开始执行工作流文件 {0} ……", m_xamlPath), logger);
                Messenger.Default.Send(this, "BeginRun");

                if (m_app != null)
                {
                    m_app.Terminate("");
                }

                m_app = new WorkflowApplication(workflow);
                m_app.Extensions.Add(new LogToOutputWindowTextWriter());

                if (workflow is DynamicActivity)
                {
                    var wr = new WorkflowRuntime();
                    wr.RootActivity = workflow;
                    m_app.Extensions.Add(wr);
                }

                m_app.OnUnhandledException = WorkflowApplicationOnUnhandledException;
                m_app.Completed            = WorkflowApplicationExecutionCompleted;
                m_app.Run();
            }
            else
            {
                AutoCloseMessageBoxService.Show(App.Current.MainWindow, "工作流校验错误,请检查参数配置", "错误", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
Ejemplo n.º 21
0
        private void ValidateWorkflowInternal(Activity workflow, string runtimeAssembly, PSWorkflowValidationResults validationResults)
        {
            PSWorkflowValidator.Tracer.WriteMessage(string.Concat(PSWorkflowValidator.Facility, "Validating a workflow."));
            PSWorkflowValidator._structuredTracer.WorkflowValidationStarted(Guid.Empty);
            ValidationSettings validationSetting = new ValidationSettings();
            List <Constraint>  constraints       = new List <Constraint>();

            constraints.Add(this.ValidateActivitiesConstraint(runtimeAssembly, validationResults));
            validationSetting.AdditionalConstraints.Add(typeof(Activity), constraints);
            ValidationSettings validationSetting1 = validationSetting;

            try
            {
                validationResults.Results = ActivityValidationServices.Validate(workflow, validationSetting1);
            }
            catch (Exception exception1)
            {
                Exception exception = exception1;
                PSWorkflowValidator.Tracer.TraceException(exception);
                new ValidationException(Resources.ErrorWhileValidatingWorkflow, exception);
                throw exception;
            }
            PSWorkflowValidator._structuredTracer.WorkflowValidationFinished(Guid.Empty);
        }
Ejemplo n.º 22
0
        bool TryLoadAndValidateProgram(Stream stream, string originalPath, out Activity program)
        {
            program = null;

            Exception loadException = null;

            try
            {
                program = ActivityXamlServices.Load(stream);
            }
            catch (XmlException xmlException)
            {
                loadException = xmlException;
            }
            catch (XamlException xamlException)
            {
                loadException = xamlException;
            }
            catch (ArgumentException argumentException)
            {
                loadException = argumentException;
            }

            ValidationResults results = null;

            //If this is a Dynamic activity - a XamlException might occur
            try
            {
                results = ActivityValidationServices.Validate(program);
            }
            catch (XamlException xamlException)
            {
                loadException = xamlException;
            }

            if (loadException != null)
            {
                WriteException(loadException, "An error has occured loading the specified file: " + originalPath);
                return(false);
            }


            foreach (ValidationError error in results.Errors)
            {
                this.hostView.ErrorWriter.WriteLine("{0}: {1} Activity: {2}",
                                                    "error",
                                                    error.Message,
                                                    error.Source.DisplayName);
            }

            foreach (ValidationError warning in results.Warnings)
            {
                this.hostView.ErrorWriter.WriteLine("{0}: {1} Activity: {2}",
                                                    "warning",
                                                    warning.Message,
                                                    warning.Source.DisplayName);
            }

            if (results.Errors.Count > 0)
            {
                this.hostView.ErrorWriter.WriteLine("Could not run Workflow: " + originalPath);
                this.hostView.ErrorWriter.WriteLine("There are validation errors");
                return(false);
            }

            return(true);
        }
Ejemplo n.º 23
0
        public static IEnumerable <Activity> GetActivities(Activity activity)
        {
            int iteratorVariable0;

            if (activity == null)
            {
                throw FxTrace.Exception.ArgumentNull("activity");
            }
            if (!activity.IsMetadataCached)
            {
                IList <ValidationError> validationErrors = null;
                ActivityUtilities.CacheRootMetadata(activity, new ActivityLocationReferenceEnvironment(), ProcessActivityTreeOptions.FullCachingOptions, null, ref validationErrors);
                ActivityValidationServices.ThrowIfViolationsExist(validationErrors);
            }
            for (iteratorVariable0 = 0; iteratorVariable0 < activity.RuntimeArguments.Count; iteratorVariable0++)
            {
                RuntimeArgument iteratorVariable1 = activity.RuntimeArguments[iteratorVariable0];
                if ((iteratorVariable1.BoundArgument != null) && (iteratorVariable1.BoundArgument.Expression != null))
                {
                    yield return(iteratorVariable1.BoundArgument.Expression);
                }
            }
            for (iteratorVariable0 = 0; iteratorVariable0 < activity.RuntimeVariables.Count; iteratorVariable0++)
            {
                Variable iteratorVariable2 = activity.RuntimeVariables[iteratorVariable0];
                if (iteratorVariable2.Default != null)
                {
                    yield return(iteratorVariable2.Default);
                }
            }
            for (iteratorVariable0 = 0; iteratorVariable0 < activity.ImplementationVariables.Count; iteratorVariable0++)
            {
                Variable iteratorVariable3 = activity.ImplementationVariables[iteratorVariable0];
                if (iteratorVariable3.Default != null)
                {
                    yield return(iteratorVariable3.Default);
                }
            }
            for (iteratorVariable0 = 0; iteratorVariable0 < activity.Children.Count; iteratorVariable0++)
            {
                yield return(activity.Children[iteratorVariable0]);
            }
            for (iteratorVariable0 = 0; iteratorVariable0 < activity.ImportedChildren.Count; iteratorVariable0++)
            {
                yield return(activity.ImportedChildren[iteratorVariable0]);
            }
            for (iteratorVariable0 = 0; iteratorVariable0 < activity.ImplementationChildren.Count; iteratorVariable0++)
            {
                yield return(activity.ImplementationChildren[iteratorVariable0]);
            }
            for (iteratorVariable0 = 0; iteratorVariable0 < activity.Delegates.Count; iteratorVariable0++)
            {
                ActivityDelegate iteratorVariable4 = activity.Delegates[iteratorVariable0];
                if (iteratorVariable4.Handler != null)
                {
                    yield return(iteratorVariable4.Handler);
                }
            }
            for (iteratorVariable0 = 0; iteratorVariable0 < activity.ImportedDelegates.Count; iteratorVariable0++)
            {
                ActivityDelegate iteratorVariable5 = activity.ImportedDelegates[iteratorVariable0];
                if (iteratorVariable5.Handler != null)
                {
                    yield return(iteratorVariable5.Handler);
                }
            }
            for (iteratorVariable0 = 0; iteratorVariable0 < activity.ImplementationDelegates.Count; iteratorVariable0++)
            {
                ActivityDelegate iteratorVariable6 = activity.ImplementationDelegates[iteratorVariable0];
                if (iteratorVariable6.Handler != null)
                {
                    yield return(iteratorVariable6.Handler);
                }
            }
        }
Ejemplo n.º 24
0
        public static bool ValidateConstraints(TestActivity activity, List <TestConstraintViolation> expectedConstraints, ValidationSettings validatorSettings)
        {
            //Log.TraceInternal("ValidateConstraints: Validating...");

            StringBuilder sb = new StringBuilder();
            bool          hasBuildConstraintError = false;

            ValidationResults validationResults;

            if (validatorSettings != null)
            {
                validationResults = ActivityValidationServices.Validate(activity.ProductActivity, validatorSettings);
            }
            else
            {
                validationResults = ActivityValidationServices.Validate(activity.ProductActivity);
            }

            hasBuildConstraintError = (validationResults.Errors.Count > 0);

            if (expectedConstraints.Count != (validationResults.Errors.Count + validationResults.Warnings.Count))
            {
                sb.AppendLine("expectedConstraintViolations.Count != actualConstraintViolations.Count");
            }

            bool matched = false;

            foreach (TestConstraintViolation expected in expectedConstraints)
            {
                foreach (ValidationError error in validationResults.Errors)
                {
                    if (expected.IsMatching(error))
                    {
                        matched = true;
                        break;
                    }
                }
                if (!matched) // try warnings
                {
                    foreach (ValidationError warning in validationResults.Warnings)
                    {
                        if (expected.IsMatching(warning))
                        {
                            matched = true;
                            break;
                        }
                    }
                }
                if (!matched)
                {
                    sb.AppendLine(String.Format(
                                      "Expected Constraint '{0}' not found in Actual Constraints",
                                      expected));
                }
                matched = false;
            }

            //Log.TraceInternal("Expected Constraints:");
            foreach (TestConstraintViolation expectedConstraint in expectedConstraints)
            {
                //Log.TraceInternal("{0}", expectedConstraint);
            }
            //Log.TraceInternal("Actual Constraints:");
            foreach (ValidationError error in validationResults.Errors)
            {
                //Log.TraceInternal("{0}", TestConstraintViolation.ActualConstraintViolationToString(error));
            }

            foreach (ValidationError warning in validationResults.Warnings)
            {
                //Log.TraceInternal("{0}", TestConstraintViolation.ActualConstraintViolationToString(warning));
            }

            if (sb.Length > 0)
            {
                //Log.TraceInternal("Errors found:");
                //Log.TraceInternal(sb.ToString());
                throw new Exception("FAIL, error while validating in TestWorkflowRuntime.ValidateConstraints");
            }
            //Log.TraceInternal("ValidateConstraints: Validation complete.");

            return(!hasBuildConstraintError);
        }
Ejemplo n.º 25
0
        public static Activity LoadWorkflowActiovityFromXaml(string path, ILogger errorLogger)
        {
            const int    fileBufferSize      = 1024;
            const string ioExceptionPreamble = "Could not read program file due to an IO Exception.";
            FileStream   fileStream          = null;

            try
            {
                fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, fileBufferSize, true);
                Activity program = null;

                Exception loadException = null;

                try
                {
                    ActivityXamlServicesSettings settings = new ActivityXamlServicesSettings
                    {
                        CompileExpressions = true
                    };
                    program = ActivityXamlServices.Load(fileStream, settings);
                }
                catch (XmlException xmlException)
                {
                    loadException = xmlException;
                }
                catch (XamlException xamlException)
                {
                    loadException = xamlException;
                }
                catch (ArgumentException argumentException)
                {
                    loadException = argumentException;
                }

                ValidationResults results = null;

                //If this is a Dynamic activity - a XamlException might occur
                try
                {
                    results = ActivityValidationServices.Validate(program);
                }
                catch (XamlException xamlException)
                {
                    loadException = xamlException;
                }

                if (loadException != null)
                {
                    errorLogger.Log("An error has occured loading the specified file: " + path, LoggerInfoTypes.Error);
                    return(null);
                }


                foreach (ValidationError error in results.Errors)
                {
                    errorLogger.Log(string.Format("{0} Activity: {1}",

                                                  error.Message,
                                                  error.Source.DisplayName), LoggerInfoTypes.Error);
                }

                foreach (ValidationError warning in results.Warnings)
                {
                    errorLogger.Log(string.Format("{0} Activity: {1}",
                                                  warning.Message,
                                                  warning.Source.DisplayName), LoggerInfoTypes.Warning);
                }

                if (results.Errors.Count > 0)
                {
                    errorLogger.Log("Could not run Workflow: " + path, LoggerInfoTypes.Error);
                    errorLogger.Log("There are validation errors", LoggerInfoTypes.Error);
                    return(null);
                }
                return(program);
            }
            catch (FileNotFoundException fileNotFoundException)
            {
                errorLogger.Log("Could not read program file." + fileNotFoundException.Message, LoggerInfoTypes.Error);
                fileStream.Close();
                return(null);
            }
            catch (IOException ioException)
            {
                errorLogger.Log(ioExceptionPreamble + ioException.Message, LoggerInfoTypes.Error);
                fileStream.Close();
                return(null);
            }
        }
Ejemplo n.º 26
0
 public static ValidationResults Validate(this Activity activity)
 {
     return(ActivityValidationServices
            .Validate(activity));
 }
        void Validate(Activity activity, string fileName)
        {
            List <ValidationError> validationErrors = new List <ValidationError>();

            ValidationSettings settings = new ValidationSettings()
            {
                SkipValidatingRootConfiguration = true
            };
            ValidationResults results = null;

            try
            {
                results = ActivityValidationServices.Validate(activity, settings);
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                ValidationError error = new ValidationError(SR.ValidationBuildExtensionExceptionPrefix(typeof(ValidationBuildExtension).Name, activity.DisplayName, e.Message));
                validationErrors.Add(error);
            }

            if (results != null)
            {
                validationErrors.AddRange(results.Errors);
                validationErrors.AddRange(results.Warnings);
            }

            if (validationErrors.Count > 0)
            {
                Dictionary <object, SourceLocation> sourceLocations;

                sourceLocations = GetErrorInformation(activity);

                IDictionary <Activity, Activity> parentChildMappings = GetParentChildRelationships(activity);

                Activity errorSource;
                foreach (ValidationError violation in validationErrors)
                {
                    bool           foundSourceLocation = false;
                    SourceLocation violationLocation   = null;

                    errorSource = violation.Source;

                    if (sourceLocations != null)
                    {
                        if (violation.SourceDetail != null)
                        {
                            foundSourceLocation = sourceLocations.TryGetValue(violation.SourceDetail, out violationLocation);
                        }
                        // SourceLocation points to the erroneous activity
                        // If the errorneous activity does not have SourceLocation attached,
                        // for instance, debugger does not attach SourceLocations for expressions
                        // then the SourceLocation points to the first parent activity in the
                        // parent chain which has SourceLocation attached.

                        while (!foundSourceLocation && errorSource != null)
                        {
                            foundSourceLocation = sourceLocations.TryGetValue(errorSource, out violationLocation);
                            if (!foundSourceLocation)
                            {
                                Activity parent;
                                if (!parentChildMappings.TryGetValue(errorSource, out parent))
                                {
                                    parent = null;
                                }
                                errorSource = parent;
                            }
                        }
                    }

                    this.violations.Add(new Violation(fileName, violation, violationLocation));
                }
            }
        }
        private static void ProcessActivity(ChildActivity childActivity, ref ChildActivity nextActivity, ref Stack <ChildActivity> activitiesRemaining, ActivityCallStack parentChain, ref IList <ValidationError> validationErrors, ProcessActivityTreeOptions options, ProcessActivityCallback callback)
        {
            Activity                element            = childActivity.Activity;
            IList <Constraint>      runtimeConstraints = element.RuntimeConstraints;
            IList <ValidationError> list2 = null;

            if (!element.HasStartedCachingMetadata)
            {
                element.MemberOf.AddMember(element);
                element.InternalCacheMetadata(options.CreateEmptyBindings, ref list2);
                ActivityValidationServices.ValidateArguments(element, element.Parent == null, ref list2);
                ActivityLocationReferenceEnvironment environment  = null;
                ActivityLocationReferenceEnvironment environment2 = new ActivityLocationReferenceEnvironment(element.HostEnvironment)
                {
                    InternalRoot = element
                };
                int nextEnvironmentId = 0;
                ProcessChildren(element, element.Children, ActivityCollectionType.Public, true, ref nextActivity, ref activitiesRemaining, ref list2);
                ProcessChildren(element, element.ImportedChildren, ActivityCollectionType.Imports, true, ref nextActivity, ref activitiesRemaining, ref list2);
                ProcessChildren(element, element.ImplementationChildren, ActivityCollectionType.Implementation, !options.SkipPrivateChildren, ref nextActivity, ref activitiesRemaining, ref list2);
                ProcessArguments(element, element.RuntimeArguments, true, ref environment2, ref nextEnvironmentId, ref nextActivity, ref activitiesRemaining, ref list2);
                ProcessVariables(element, element.RuntimeVariables, ActivityCollectionType.Public, true, ref environment, ref nextEnvironmentId, ref nextActivity, ref activitiesRemaining, ref list2);
                ProcessVariables(element, element.ImplementationVariables, ActivityCollectionType.Implementation, !options.SkipPrivateChildren, ref environment2, ref nextEnvironmentId, ref nextActivity, ref activitiesRemaining, ref list2);
                if (element.HandlerOf != null)
                {
                    for (int i = 0; i < element.HandlerOf.RuntimeDelegateArguments.Count; i++)
                    {
                        RuntimeDelegateArgument argument      = element.HandlerOf.RuntimeDelegateArguments[i];
                        DelegateArgument        boundArgument = argument.BoundArgument;
                        if ((boundArgument != null) && boundArgument.InitializeRelationship(element, ref list2))
                        {
                            boundArgument.Id = nextEnvironmentId;
                            nextEnvironmentId++;
                        }
                    }
                }
                if (environment == null)
                {
                    element.PublicEnvironment = new ActivityLocationReferenceEnvironment(element.GetParentEnvironment());
                }
                else
                {
                    if (environment.Parent == null)
                    {
                        environment.InternalRoot = element;
                    }
                    element.PublicEnvironment = environment;
                }
                element.ImplementationEnvironment = environment2;
                ProcessDelegates(element, element.Delegates, ActivityCollectionType.Public, true, ref nextActivity, ref activitiesRemaining, ref list2);
                ProcessDelegates(element, element.ImportedDelegates, ActivityCollectionType.Imports, true, ref nextActivity, ref activitiesRemaining, ref list2);
                ProcessDelegates(element, element.ImplementationDelegates, ActivityCollectionType.Implementation, !options.SkipPrivateChildren, ref nextActivity, ref activitiesRemaining, ref list2);
                if (callback != null)
                {
                    callback(childActivity, parentChain);
                }
                if (list2 != null)
                {
                    Activity activity2;
                    if (validationErrors == null)
                    {
                        validationErrors = new List <ValidationError>();
                    }
                    string str = ActivityValidationServices.GenerateValidationErrorPrefix(childActivity.Activity, parentChain, out activity2);
                    for (int j = 0; j < list2.Count; j++)
                    {
                        ValidationError item = list2[j];
                        item.Source = activity2;
                        item.Id     = activity2.Id;
                        if (!string.IsNullOrEmpty(str))
                        {
                            item.Message = str + item.Message;
                        }
                        validationErrors.Add(item);
                    }
                    list2 = null;
                }
                if (options.StoreTempViolations && (validationErrors != null))
                {
                    childActivity.Activity.SetTempValidationErrorCollection(validationErrors);
                    validationErrors = null;
                }
            }
            else
            {
                SetupForProcessing(element.Children, true, ref nextActivity, ref activitiesRemaining);
                SetupForProcessing(element.ImportedChildren, false, ref nextActivity, ref activitiesRemaining);
                SetupForProcessing(element.RuntimeArguments, ref nextActivity, ref activitiesRemaining);
                SetupForProcessing(element.RuntimeVariables, ref nextActivity, ref activitiesRemaining);
                SetupForProcessing(element.Delegates, true, ref nextActivity, ref activitiesRemaining);
                SetupForProcessing(element.ImportedDelegates, false, ref nextActivity, ref activitiesRemaining);
                if (!options.SkipPrivateChildren)
                {
                    SetupForProcessing(element.ImplementationChildren, true, ref nextActivity, ref activitiesRemaining);
                    SetupForProcessing(element.ImplementationDelegates, true, ref nextActivity, ref activitiesRemaining);
                    SetupForProcessing(element.ImplementationVariables, ref nextActivity, ref activitiesRemaining);
                }
                if ((callback != null) && !options.OnlyCallCallbackForDeclarations)
                {
                    callback(childActivity, parentChain);
                }
                if (childActivity.Activity.HasTempViolations && !options.StoreTempViolations)
                {
                    childActivity.Activity.TransferTempValidationErrors(ref validationErrors);
                }
            }
            if ((!options.SkipConstraints && parentChain.WillExecute) && (childActivity.CanBeExecuted && (runtimeConstraints.Count > 0)))
            {
                ActivityValidationServices.RunConstraints(childActivity, parentChain, runtimeConstraints, options, false, ref validationErrors);
            }
        }
Ejemplo n.º 29
0
        public static IEnumerable <Activity> GetActivities(Activity activity)
        {
            if (activity == null)
            {
                throw FxTrace.Exception.ArgumentNull(nameof(activity));
            }

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

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

                ActivityValidationServices.ThrowIfViolationsExist(validationErrors);
            }

            var i = 0;

            for (; i < activity.RuntimeArguments.Count; i++)
            {
                var 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++)
            {
                var variable = activity.RuntimeVariables[i];

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

            for (i = 0; i < activity.ImplementationVariables.Count; i++)
            {
                var 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++)
            {
                var activityDelegate = activity.Delegates[i];

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

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

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

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

                if (activityDelegate.Handler != null)
                {
                    yield return(activityDelegate.Handler);
                }
            }
        }
Ejemplo n.º 30
0
        static void Main(string[] args)
        {
            //Create a WF with configuration errors
            Sequence wf = new Sequence()
            {
                Activities =
                {
                    new Sequence
                    {
                        DisplayName = "Sequence1"
                    },
                    new If
                    {
                        DisplayName = "If",
                        Condition   = new InArgument <bool>(true)
                    },
                    new Switch <bool>
                    {
                        DisplayName = "Switch1",
                        Expression  = new InArgument <bool>(true),
                        Default     = new WriteLine()
                    },
                    new ForEach <int>
                    {
                        DisplayName = "ForEach2",
                        Values      = new InArgument <IEnumerable <int> >((env) => new int[] {         1, 2, 3 })
                    },
                    new Parallel
                    {
                        DisplayName = "Parallel1"
                    },
                    new ParallelForEach <int>
                    {
                        DisplayName = "ParallelForEach1",
                        Values      = new InArgument <IEnumerable <int> >((env) => new int[] {         1, 2, 3 })
                    },
                    new Pick
                    {
                        DisplayName = "Pick1",
                        Branches    =
                        {
                            new PickBranch
                            {
                                Action = new WriteLine()
                            }
                        }
                    },
                    new Pick
                    {
                        DisplayName = "Pick2"
                    },
                    new WriteLine
                    {
                        DisplayName = "Wr"
                    }
                }
            };

            //Create an instance of Validation Settings.
            ValidationSettings settings = new ValidationSettings()
            {
                //Create value pairs constraints and activity types. We are providing a list of constraints that you want to apply on a specify activity type
                AdditionalConstraints =
                {
                    { typeof(Activity),      new List <Constraint> {
                          ConstraintLibrary.ActivityDisplayNameIsNotSetWarning()
                      } },
                    { typeof(ForEach <int>), new List <Constraint> {
                          ConstraintLibrary.ForEachPropertyMustBeSetError <int>()
                      } },
                    { typeof(WriteLine),     new List <Constraint> {
                          ConstraintLibrary.WriteLineHasNoTextWarning()
                      } },
                    { typeof(Pick),          new List <Constraint> {
                          ConstraintLibrary.PickHasNoBranchesWarning(), ConstraintLibrary.PickHasOneBranchWarning()
                      } },
                    { typeof(Parallel),      new List <Constraint> {
                          ConstraintLibrary.ParallelHasNoBranchesWarning()
                      } },
                    { typeof(Switch <bool>), new List <Constraint> {
                          ConstraintLibrary.SwitchHasDefaultButNoCasesWarning <bool>(), ConstraintLibrary.SwitchHasNoCasesOrDefaultWarning <bool>()
                      } },
                    { typeof(If),            new List <Constraint> {
                          ConstraintLibrary.IfShouldHaveThenOrElseError()
                      } },
                    { typeof(Sequence),      new List <Constraint> {
                          ConstraintLibrary.SequenceIsEmptyWarning()
                      } }
                }
            };

            //Call the Validate method with the workflow you want to validate, and the settings you want to use.
            ValidationResults results = ActivityValidationServices.Validate(wf, settings);

            //Print the validation errors and warning that were generated my ActivityValidationServices.Validate.
            PrintResults(results);
        }