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

            return((Sequence)root.ImplementationChildren[0]);
        }
Esempio n. 2
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()));
        }
        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);
        }
Esempio n. 4
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()));
        }
Esempio n. 6
0
 public ValidationResults Validate(ValidationSettings settings)
 {
     if (this.workflowService != null)
     {
         return(this.workflowService.Validate(settings));
     }
     else
     {
         return(ActivityValidationServices.Validate(this.activity, settings));
     }
 }
Esempio n. 7
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);
        }
Esempio n. 8
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);
        }
Esempio n. 9
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);
            }
        }
Esempio n. 10
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);
            }
        }
Esempio n. 11
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);
            }
        }
Esempio n. 12
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);
        }
Esempio n. 13
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);
        }
Esempio n. 14
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);
        }
Esempio n. 15
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);
            }
        }
Esempio n. 16
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));
                }
            }
        }
Esempio n. 18
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);
        }