Exemplo n.º 1
0
        public RuleSetDialog(Activity activity, RuleSet ruleSet)
        {
            if (activity == null)
                throw (new ArgumentNullException("activity"));

            InitializeDialog(ruleSet);

            ITypeProvider typeProvider;
            this.serviceProvider = activity.Site;
            if (this.serviceProvider != null)
            {
                typeProvider = (ITypeProvider)this.serviceProvider.GetService(typeof(ITypeProvider));
                if (typeProvider == null)
                {
                    string message = string.Format(CultureInfo.CurrentCulture, Messages.MissingService, typeof(ITypeProvider).FullName);
                    throw new InvalidOperationException(message);
                }

                WorkflowDesignerLoader loader = this.serviceProvider.GetService(typeof(WorkflowDesignerLoader)) as WorkflowDesignerLoader;
                if (loader != null)
                    loader.Flush();

            }
            else
            {
                // no service provider, so make a TypeProvider that has all loaded Assemblies
                TypeProvider newProvider = new TypeProvider(null);
                foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
                    newProvider.AddAssembly(a);
                typeProvider = newProvider;
            }

            RuleValidation validation = new RuleValidation(activity, typeProvider, false);
            this.ruleParser = new Parser(validation);
        }
Exemplo n.º 2
0
        public RuleSetDialog(Type activityType, ITypeProvider typeProvider, RuleSet ruleSet)
        {
            if (activityType == null)
                throw (new ArgumentNullException("activityType"));

            InitializeDialog(ruleSet);

            RuleValidation validation = new RuleValidation(activityType, typeProvider);
            this.ruleParser = new Parser(validation);
        }
        public RuleConditionDialog(Type activityType, ITypeProvider typeProvider, CodeExpression expression)
        {
            if (activityType == null)
                throw (new ArgumentNullException("activityType"));

            InitializeComponent();

            RuleValidation validation = new RuleValidation(activityType, typeProvider);
            this.ruleParser = new Parser(validation);

            InitializeDialog(expression);
        }
Exemplo n.º 4
0
        public RuleConditionDialog(System.Type activityType, ITypeProvider typeProvider, CodeExpression expression)
        {
            this.ruleExpressionCondition = new RuleExpressionCondition();
            if (activityType == null)
            {
                throw new ArgumentNullException("activityType");
            }
            this.InitializeComponent();
            RuleValidation validation = new RuleValidation(activityType, typeProvider);

            this.ruleParser = new Parser(validation);
            this.InitializeDialog(expression);
        }
Exemplo n.º 5
0
        public RuleSetDialog(Type activityType, RuleSet ruleSet, List <Assembly> references)
        {
            if (activityType == null)
            {
                throw (new ArgumentNullException("activityType"));
            }

            InitializeDialog(ruleSet);

            RuleValidation validation = new RuleValidation(activityType, references);

            this.ruleParser = new Parser(validation);
        }
        public RuleSetDialog(Type activityType, RuleSet ruleSet, string[] assemblyPaths = null)
        {
            if (activityType == null)
            {
                throw (new ArgumentNullException("activityType"));
            }

            InitializeDialog(ruleSet);

            RuleValidation validation = new RuleValidation(activityType);

            this.ruleParser = new Parser(validation, assemblyPaths);
        }
Exemplo n.º 7
0
        public KeyProcess RegisterKeys(ref KeyRegistrar keyRegistrar, RuleSet profile)
        {
            _keyHandlerState = new keyHandlerState()
            {
                current = null, previous = null
            };
            _keyHandlerState.keyRegistrar = keyRegistrar;
            RuleValidation validation = new RuleValidation(typeof(keyHandlerState), null);
            RuleExecution  execution  = new RuleExecution(validation, _keyHandlerState);

            profile.Execute(execution);
            return(Start);
        }
Exemplo n.º 8
0
        public static RuleExpressionInfo Validate(RuleValidation validation, CodeExpression expression, bool isWritten)
        {
            if (validation == null)
            {
                throw new ArgumentNullException("validation");
            }

            // See if we've visited this node before.
            // Always check if written = true
            RuleExpressionInfo resultExprInfo = null;

            if (!isWritten)
            {
                resultExprInfo = validation.ExpressionInfo(expression);
            }
            if (resultExprInfo == null)
            {
                // First time we've seen this node.
                RuleExpressionInternal ruleExpr = GetExpression(expression);
                if (ruleExpr == null)
                {
                    string          message = string.Format(CultureInfo.CurrentCulture, Messages.CodeExpressionNotHandled, expression.GetType().FullName);
                    ValidationError error   = new ValidationError(message, ErrorNumbers.Error_CodeExpressionNotHandled);
                    error.UserData[RuleUserDataKeys.ErrorObject] = expression;

                    if (validation.Errors == null)
                    {
                        string typeName = string.Empty;
                        if ((validation.ThisType != null) && (validation.ThisType.Name != null))
                        {
                            typeName = validation.ThisType.Name;
                        }

                        string exceptionMessage = string.Format(
                            CultureInfo.CurrentCulture, Messages.ErrorsCollectionMissing, typeName);

                        throw new InvalidOperationException(exceptionMessage);
                    }
                    else
                    {
                        validation.Errors.Add(error);
                    }

                    return(null);
                }

                resultExprInfo = validation.ValidateSubexpression(expression, ruleExpr, isWritten);
            }

            return(resultExprInfo);
        }
Exemplo n.º 9
0
        internal static object AdjustTypeWithCast(Type operandType, object operandValue, Type toType)
        {
            // if no conversion required, we are done
            if (operandType == toType)
            {
                return(operandValue);
            }

            if (AdjustValueStandard(operandType, operandValue, toType, out object converted))
            {
                return(converted);
            }

            // handle enumerations (done above?)

            // now it's time for implicit and explicit user defined conversions
            MethodInfo conversion = RuleValidation.FindExplicitConversion(operandType, toType, out ValidationError error);

            if (conversion == null)
            {
                if (error != null)
                {
                    throw new RuleEvaluationException(error.ErrorText);
                }

                throw new RuleEvaluationException(
                          string.Format(CultureInfo.CurrentCulture,
                                        Messages.CastIncompatibleTypes,
                                        RuleDecompiler.DecompileType(operandType),
                                        RuleDecompiler.DecompileType(toType)));
            }

            // now we have a method, need to do the conversion S -> Sx -> Tx -> T
            Type sx = conversion.GetParameters()[0].ParameterType;
            Type tx = conversion.ReturnType;

            if (AdjustValueStandard(operandType, operandValue, sx, out object intermediateResult1))
            {
                // we are happy with the first conversion, so call the user's static method
                object intermediateResult2 = conversion.Invoke(null, new object[] { intermediateResult1 });
                if (AdjustValueStandard(tx, intermediateResult2, toType, out object intermediateResult3))
                {
                    return(intermediateResult3);
                }
            }
            throw new RuleEvaluationException(
                      string.Format(CultureInfo.CurrentCulture,
                                    Messages.CastIncompatibleTypes,
                                    RuleDecompiler.DecompileType(operandType),
                                    RuleDecompiler.DecompileType(toType)));
        }
Exemplo n.º 10
0
        private static SystemWatcher GetSystemWatcherSettings()
        {
            var ruleValidationService             = new RuleValidation();
            var watchedDirectoryValidationService = new WatchedDirectoryValidation();

            var ruleConvertionService             = new RuleConverter(ruleValidationService);
            var watchedDirectoryConvertionService = new WatchedDirectoryConverter(watchedDirectoryValidationService);
            var systemWatcherConvertionService    = new SystemWatcherConverter(ruleConvertionService, watchedDirectoryConvertionService);

            var systemWathcerSection = (SystemWatcherConfigurationSection)
                                       ConfigurationManager.GetSection("systemWatcher");

            return(systemWatcherConvertionService.Convert(systemWathcerSection));
        }
Exemplo n.º 11
0
        public RuleConditionDialog(Activity activity, CodeExpression expression)
        {
            if (activity == null)
            {
                throw (new ArgumentNullException("activity"));
            }

            InitializeComponent();

            ITypeProvider typeProvider;

            serviceProvider = activity.Site;
            if (serviceProvider != null)
            {
                IUIService uisvc = serviceProvider.GetService(typeof(IUIService)) as IUIService;
                if (uisvc != null)
                {
                    this.Font = (Font)uisvc.Styles["DialogFont"];
                }
                typeProvider = (ITypeProvider)serviceProvider.GetService(typeof(ITypeProvider));
                if (typeProvider == null)
                {
                    string message = string.Format(CultureInfo.CurrentCulture, Messages.MissingService, typeof(ITypeProvider).FullName);
                    throw new InvalidOperationException(message);
                }

                WorkflowDesignerLoader loader = serviceProvider.GetService(typeof(WorkflowDesignerLoader)) as WorkflowDesignerLoader;
                if (loader != null)
                {
                    loader.Flush();
                }
            }
            else
            {
                // no service provider, so make a TypeProvider that has all loaded Assemblies
                TypeProvider newProvider = new TypeProvider(null);
                foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
                {
                    newProvider.AddAssembly(a);
                }
                typeProvider = newProvider;
            }

            RuleValidation validation = new RuleValidation(activity, typeProvider, false);

            this.ruleParser = new Parser(validation);

            InitializeDialog(expression);
        }
Exemplo n.º 12
0
        public MSRuleSetExecutionResult ExecuteRuleSet(System.Workflow.Activities.Rules.RuleSet ruleSet, bool translatedRule)
        {
            MSRuleSetExecutionResult ruleSetExecutionResult = null;

            if (translatedRule)
            {
                ruleSetExecutionResult = new MSRuleSetExecutionResult(_msRuleSetTranslationResult);
            }
            else
            {
                ruleSetExecutionResult = new MSRuleSetExecutionResult();
            }

            RuleValidation rv = new RuleValidation(typeof(T), null);

            ruleSet.Validate(rv);

            ValidationErrorCollection errors = rv.Errors;

            if (errors.Count > 0)
            {
                ruleSetExecutionResult.AddRuleSetValidationErrors(errors);
            }
            else
            {
                try
                {
                    ExecuteRuleSet(ruleSet, rv, ref ruleSetExecutionResult);
                }
                catch (RuleException rex)
                {
                    _log.Error("RuleSet Name:  " + ruleSet.Name + "threw a Rule Exception during its execution.  ", rex);
                    ruleSetExecutionResult.AddExecutionError(Guid.Empty.ToString(), ruleSet.Name, rex);
                }
                catch (TargetInvocationException tex)
                {
                    _log.Error("RuleSetName:  " + ruleSet.Name +
                               ", threw a Target Invocation Exception which means that the Wrapper object itself probably threw an error, maybe the rule is targeting a property that is null or not a valid value for comparison", tex);
                    ruleSetExecutionResult.AddExecutionError(Guid.Empty.ToString(), ruleSet.Name, tex);
                }
                catch (Exception ex)
                {
                    _log.Error("RuleSetName:  " + ruleSet.Name + "Unhandled exception during execution of", ex);
                    ruleSetExecutionResult.AddExecutionError(Guid.Empty.ToString(), ruleSet.Name, ex);
                }
            }

            return(ruleSetExecutionResult);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Execute a RuleSet definition read from
        /// a file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void codeExecuteRuleSet_ExecuteCode(
            object sender, EventArgs e)
        {
            //get a stream from the embedded .rules resource
            Assembly assembly = Assembly.GetAssembly(typeof(SellItemWorkflow));
            Stream   stream   = assembly.GetManifestResourceStream(
                "SharedWorkflows.SellItemMethods2Workflow.rules");

            //get a stream from an externally saved .rules file
            //Stream stream
            //    = new FileStream(@"SerializedSellItem.rules",
            //        FileMode.Open, FileAccess.Read, FileShare.Read);

            using (XmlReader xmlReader = XmlReader.Create(
                       new StreamReader(stream)))
            {
                WorkflowMarkupSerializer markupSerializer
                    = new WorkflowMarkupSerializer();
                //deserialize the rule definitions
                RuleDefinitions ruleDefinitions
                    = markupSerializer.Deserialize(xmlReader) as RuleDefinitions;
                if (ruleDefinitions != null)
                {
                    if (ruleDefinitions.RuleSets.Contains("CalculateItemTotals"))
                    {
                        RuleSet rs
                            = ruleDefinitions.RuleSets["CalculateItemTotals"];
                        //validate and execute the RuleSet against this
                        //workflow instance
                        RuleValidation validation = new RuleValidation(
                            typeof(SellItemSerializedWorkflow), null);
                        if (rs.Validate(validation))
                        {
                            RuleExecution execution
                                = new RuleExecution(validation, this);
                            rs.Execute(execution);
                        }
                        else
                        {
                            foreach (ValidationError error in validation.Errors)
                            {
                                Console.WriteLine(error.ErrorText);
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 14
0
        protected override void Execute(CodeActivityContext context)
        {
            if (RulesFilePath == null || RuleSetName == null)
            {
                throw new InvalidOperationException("Rules File path and RuleSet Name need to be configured");
            }

            if (!File.Exists(RulesFilePath))
            {
                throw new InvalidOperationException("Rules File " + RulesFilePath + " did not exist");
            }

            // Get the RuleSet from the .rules file
            WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
            XmlTextReader            reader     = new XmlTextReader(RulesFilePath);
            RuleDefinitions          rules      = serializer.Deserialize(reader) as RuleDefinitions;
            RuleSet ruleSet = rules.RuleSets[RuleSetName];

            if (ruleSet == null)
            {
                throw new InvalidOperationException("RuleSet " + RuleSetName + " not found in " + RulesFilePath);
            }

            // Validate before running
            Type           targetType = this.TargetObject.Get(context).GetType();
            RuleValidation validation = new RuleValidation(targetType, null);

            if (!ruleSet.Validate(validation))
            {
                // Set the ValidationErrors OutArgument
                this.ValidationErrors.Set(context, validation.Errors);

                // Throw exception
                throw new ValidationException(string.Format("The ruleset is not valid. {0} validation errors found (check the ValidationErrors property for more information).", validation.Errors.Count));
            }

            // Execute the ruleset
            object     evaluatedTarget = this.TargetObject.Get(context);
            RuleEngine engine          = new RuleEngine(ruleSet, validation);

            engine.Execute(evaluatedTarget);

            // Update the Result object
            this.ResultObject.Set(context, evaluatedTarget);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Get Validation
        /// </summary>
        /// <param name="ruleSet"></param>
        /// <returns></returns>
        public static RuleValidation GetValidation(RuleSet ruleSet)
        {
            if (ruleSet == null)
            {
                throw new InvalidOperationException(Properties.Resources.ruleSetCannotBeNull);
            }

            List <System.Reflection.Assembly> assemblies = new List <System.Reflection.Assembly>
            {
                typeof(Enrollment.Parameters.Expansions.SelectExpandDefinitionParameters).Assembly,
                //typeof(Forms.View.ViewBase).Assembly,
                //typeof(LogicBuilder.Forms.Parameters.InputFormParameters).Assembly,
                typeof(Domain.BaseModelClass).Assembly,
                typeof(LogicBuilder.RulesDirector.DirectorBase).Assembly,
                typeof(string).Assembly
            };

            RuleValidation ruleValidation = new RuleValidation(typeof(FlowActivity), assemblies);

            if (!ruleSet.Validate(ruleValidation))
            {
                List <string> errors = ruleValidation.Errors.Aggregate
                                       (
                    new List <string>
                {
                    string.Format
                    (
                        CultureInfo.CurrentCulture,
                        Properties.Resources.invalidRulesetFormat,
                        ruleSet.Name
                    )
                },
                    (list, next) =>
                {
                    list.Add(next.ErrorText);
                    return(list);
                }
                                       );

                throw new ArgumentException(string.Join(Environment.NewLine, errors));
            }

            return(ruleValidation);
        }
Exemplo n.º 16
0
        internal static bool ValidateRuleSet(RuleSet ruleSetToValidate, Type targetType, bool promptForContinue)
        {
            if (ruleSetToValidate == null)
            {
                MessageBox.Show("No RuleSet selected.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            if (targetType == null)
            {
                MessageBox.Show("No Type is associated with the RuleSet.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            RuleValidation ruleValidation = new RuleValidation(targetType, null);

            ruleSetToValidate.Validate(ruleValidation);
            if (ruleValidation.Errors.Count == 0)
            {
                return(true);
            }
            else
            {
                ValidationErrorsForm validationDialog = new ValidationErrorsForm();
                validationDialog.SetValidationErrors(ruleValidation.Errors);
                validationDialog.PromptForContinue = promptForContinue;
                validationDialog.ErrorText         = "The RuleSet failed validation.  Ensure that the selected Type has the public members referenced by this RuleSet.  Note that false errors may occur if you are referencing different copies of an assembly with the same strong name.";
                if (promptForContinue)
                {
                    validationDialog.ErrorText += "  Select Continue to proceed or Cancel to return.";
                }

                validationDialog.ShowDialog();

                if (!promptForContinue)
                {
                    return(false);
                }
                else
                {
                    return(validationDialog.ContinueWithChange);
                }
            }
        }
Exemplo n.º 17
0
        public RuleConditionDialog(Activity activity, CodeExpression expression)
        {
            ITypeProvider provider;

            this.ruleExpressionCondition = new RuleExpressionCondition();
            if (activity == null)
            {
                throw new ArgumentNullException("activity");
            }
            this.InitializeComponent();
            this.serviceProvider = activity.Site;
            if (this.serviceProvider != null)
            {
                IUIService service = this.serviceProvider.GetService(typeof(IUIService)) as IUIService;
                if (service != null)
                {
                    this.Font = (Font)service.Styles["DialogFont"];
                }
                provider = (ITypeProvider)this.serviceProvider.GetService(typeof(ITypeProvider));
                if (provider == null)
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.MissingService, new object[] { typeof(ITypeProvider).FullName }));
                }
                WorkflowDesignerLoader loader = this.serviceProvider.GetService(typeof(WorkflowDesignerLoader)) as WorkflowDesignerLoader;
                if (loader != null)
                {
                    loader.Flush();
                }
            }
            else
            {
                TypeProvider provider2 = new TypeProvider(null);
                foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
                {
                    provider2.AddAssembly(assembly);
                }
                provider = provider2;
            }
            RuleValidation validation = new RuleValidation(activity, provider, false);

            this.ruleParser = new Parser(validation);
            this.InitializeDialog(expression);
        }
Exemplo n.º 18
0
        public RuleEngine(RuleSet ruleSet, RuleValidation validation)
        {
            // now validate it
            if (!ruleSet.Validate(validation))
            {
                string message = string.Format(CultureInfo.CurrentCulture, Messages.RuleSetValidationFailed, ruleSet.name);
                throw new RuleSetValidationException(message, validation.Errors);
            }

            this.name       = ruleSet.Name;
            this.validation = validation;
            Tracer tracer = null;

            if (WorkflowActivityTrace.Rules.Switch.ShouldTrace(TraceEventType.Information))
            {
                tracer = new Tracer(ruleSet.Name);
            }
            this.analyzedRules = Executor.Preprocess(ruleSet.ChainingBehavior, ruleSet.Rules, validation, tracer);
        }
Exemplo n.º 19
0
        public override bool Validate(RuleValidation validator)
        {
            if (validator == null)
            {
                throw new ArgumentNullException("validator");
            }

            if (codeDomStatement == null)
            {
                ValidationError error = new ValidationError(Messages.NullStatement, ErrorNumbers.Error_ParameterNotSet);
                error.UserData[RuleUserDataKeys.ErrorObject] = this;
                validator.AddError(error);
                return(false);
            }
            else
            {
                return(CodeDomStatementWalker.Validate(validator, codeDomStatement));
            }
        }
Exemplo n.º 20
0
        private void ValidateExpression(RuleValidation validation, CodeExpression expression, string propertyName)
        {
            ValidationError error;

            if (expression == null)
            {
                error = new ValidationError(propertyName + " cannot be null", 123);
                validation.Errors.Add(error);
            }
            else
            {
                RuleExpressionInfo result = ValidateExpression(validation, expression, false);
                if ((result == null) || (result.ExpressionType != typeof(bool)))
                {
                    error = new ValidationError(propertyName + " must return boolean result", 123);
                    validation.Errors.Add(error);
                }
            }
        }
Exemplo n.º 21
0
        public RuleSetDialog(Activity activity, RuleSet ruleSet)
        {
            if (activity == null)
            {
                throw (new ArgumentNullException("activity"));
            }

            InitializeDialog(ruleSet);

            ITypeProvider typeProvider;

            this.serviceProvider = activity.Site;
            if (this.serviceProvider != null)
            {
                typeProvider = (ITypeProvider)this.serviceProvider.GetService(typeof(ITypeProvider));
                if (typeProvider == null)
                {
                    string message = string.Format(CultureInfo.CurrentCulture, Messages.MissingService, typeof(ITypeProvider).FullName);
                    throw new InvalidOperationException(message);
                }

                WorkflowDesignerLoader loader = this.serviceProvider.GetService(typeof(WorkflowDesignerLoader)) as WorkflowDesignerLoader;
                if (loader != null)
                {
                    loader.Flush();
                }
            }
            else
            {
                // no service provider, so make a TypeProvider that has all loaded Assemblies
                TypeProvider newProvider = new TypeProvider(null);
                foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
                {
                    newProvider.AddAssembly(a);
                }
                typeProvider = newProvider;
            }

            RuleValidation validation = new RuleValidation(activity, typeProvider, false);

            this.ruleParser = new Parser(validation);
        }
Exemplo n.º 22
0
        private ValidationErrorCollection ApplyRuleSet(T target,
                                                       String path, String setName)
        {
            ValidationErrorCollection errors = null;

            WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();

            RuleSet rs = null;

            if (File.Exists(path))
            {
                using (XmlTextReader reader = new XmlTextReader(path))
                {
                    RuleDefinitions rules =
                        serializer.Deserialize(reader) as RuleDefinitions;
                    if (rules != null && rules.RuleSets.Contains(setName))
                    {
                        rs = rules.RuleSets[setName];
                    }
                }
            }

            if (rs == null)
            {
                throw new ArgumentException(String.Format(
                                                "Unable to retrieve RuleSet {0} from {1}", setName, path));
            }

            RuleValidation val = new RuleValidation(target.GetType(), null);

            if (!rs.Validate(val))
            {
                errors = val.Errors;
                return(errors);
            }

            RuleEngine rulesEngine = new RuleEngine(rs, val);

            rulesEngine.Execute(target);
            return(errors);
        }
Exemplo n.º 23
0
        public void ExecuteRuleSet(RulesetRequest request)
        {
            //if (request == null || string.IsNullOrEmpty(request.Name) || request.Entity == null) return;

            var cacheKey = string.Format("Rules_{0}", request.Name);

            var ruleSet = _cacheStorage.Retrieve(cacheKey, () =>
            {
                var extRuleService = new ExternalRuleSetService();

                return(extRuleService.GetRuleSet(new RuleSetInfo {
                    Name = request.Name
                }));
            });

            if (ruleSet == null)
            {
                throw new ApplicationException("Could not retrieve rule set for rule name: " + request.Name);
            }

            var entity         = request.GetEntity();
            var ruleValidation = new RuleValidation(entity.GetType(), null);

            if (ruleSet.Validate(ruleValidation))
            {
                var ruleExecution = new RuleExecution(ruleValidation, entity);

                ruleSet.Execute(ruleExecution);
            }
            else
            {
                var sb = new StringBuilder();

                foreach (var error in ruleValidation.Errors)
                {
                    sb.AppendLine(string.Format("{0}:{1}", error.ErrorNumber, error.ErrorText));
                }

                throw new ApplicationException(sb.ToString());
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Validates the rule set against the Activity Type
        /// </summary>
        /// <param name="type"></param>
        /// <param name="ruleSet"></param>
        /// <returns></returns>
        internal static List <string> ValidateRuleSet(Type type, RuleSet ruleSet, List <Assembly> referenceAssemblies)
        {
            List <string>  validationErrors = new List <string>();
            RuleValidation ruleValidation;

            if (type == null)
            {
                throw new InvalidOperationException(Resources.typeCannotBeNull);
            }

            if (ruleSet == null)
            {
                throw new InvalidOperationException(Resources.ruleSetCannotBeNull);
            }

            ruleValidation = new RuleValidation(type, referenceAssemblies);

            if (ruleValidation == null)
            {
                validationErrors.Add(string.Format(CultureInfo.CurrentCulture, Resources.cannotValidateRuleSetFormat, ruleSet.Name));
                return(validationErrors);
            }

            try
            {
                if (!ruleSet.Validate(ruleValidation))
                {
                    foreach (ValidationError validationError in ruleValidation.Errors)
                    {
                        validationErrors.Add(validationError.ErrorText);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ToolkitException(ex.Message, ex);
            }

            return(validationErrors);
        }
        public override ICollection <string> GetSideEffects(RuleValidation validation)
        {
            RuleAnalysis analysis = new RuleAnalysis(validation, true);

            if (_applicationID != null)
            {
                RuleExpressionWalker.AnalyzeUsage(analysis, _applicationID, true, false, null);
            }
            if (_typeID != null)
            {
                RuleExpressionWalker.AnalyzeUsage(analysis, _typeID, true, false, null);
            }

            if (_result != null)
            {
                RuleExpressionWalker.AnalyzeUsage(analysis, _result, true, false, null);
            }

            if (_ruleID != null)
            {
                RuleExpressionWalker.AnalyzeUsage(analysis, _ruleID, true, false, null);
            }

            if (_ruleName != null)
            {
                RuleExpressionWalker.AnalyzeUsage(analysis, _ruleName, true, false, null);
            }

            if (_createDate != null)
            {
                RuleExpressionWalker.AnalyzeUsage(analysis, _createDate, true, false, null);
            }

            if (_referenceID != null)
            {
                RuleExpressionWalker.AnalyzeUsage(analysis, _referenceID, true, false, null);
            }

            return(analysis.GetSymbols());
        }
Exemplo n.º 26
0
        /// <summary>
        /// Get Validation
        /// </summary>
        /// <param name="ruleSet"></param>
        /// <returns></returns>
        public static RuleValidation GetValidation(RuleSet ruleSet)
        {
            if (ruleSet == null)
            {
                throw new InvalidOperationException(Properties.Resources.ruleSetCannotBeNull);
            }

            RuleValidation ruleValidation = new RuleValidation(typeof(FlowActivity), assemblies);

            if (!ruleSet.Validate(ruleValidation))
            {
                throw new ArgumentException
                      (
                          string.Join
                          (
                              Environment.NewLine,
                              ruleValidation.Errors.Aggregate
                              (
                                  new List <string>
                {
                    string.Format
                    (
                        CultureInfo.CurrentCulture,
                        Properties.Resources.invalidRulesetFormat,
                        ruleSet.Name
                    )
                },
                                  (list, next) =>
                {
                    list.Add(next.ErrorText);
                    return(list);
                }
                              )
                          )
                      );
            }

            return(ruleValidation);
        }
Exemplo n.º 27
0
        protected override TResult Execute(CodeActivityContext context)
        {
            // validate before running
            Type           targetType = this.Input.Get(context).GetType();
            RuleValidation validation = new RuleValidation(targetType, null);

            if (!this.RuleSet.Validate(validation))
            {
                // set the validation error out argument
                this.ValidationErrors.Set(context, validation.Errors);

                // throw a validation exception
                throw new ValidationException(string.Format("The ruleset is not valid. {0} validation errors found (check the ValidationErrors property for more information).", validation.Errors.Count));
            }

            // execute the ruleset
            TResult    evaluatedTarget = this.Input.Get(context);
            RuleEngine engine          = new RuleEngine(this.RuleSet, validation);

            engine.Execute(evaluatedTarget);
            return(evaluatedTarget);
        }
        public RuleConditionDialog(Activity activity, CodeExpression expression)
        {
            if (activity == null)
                throw (new ArgumentNullException("activity"));

            InitializeComponent();

            ITypeProvider typeProvider;
            serviceProvider = activity.Site;
            if (serviceProvider != null)
            {
                IUIService uisvc = serviceProvider.GetService(typeof(IUIService)) as IUIService;
                if (uisvc != null)
                    this.Font = (Font)uisvc.Styles["DialogFont"];
                typeProvider = (ITypeProvider)serviceProvider.GetService(typeof(ITypeProvider));
                if (typeProvider == null)
                {
                    string message = string.Format(CultureInfo.CurrentCulture, Messages.MissingService, typeof(ITypeProvider).FullName);
                    throw new InvalidOperationException(message);
                }

                WorkflowDesignerLoader loader = serviceProvider.GetService(typeof(WorkflowDesignerLoader)) as WorkflowDesignerLoader;
                if (loader != null)
                    loader.Flush();
            }
            else
            {
                // no service provider, so make a TypeProvider that has all loaded Assemblies
                TypeProvider newProvider = new TypeProvider(null);
                foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
                    newProvider.AddAssembly(a);
                typeProvider = newProvider;
            }

            RuleValidation validation = new RuleValidation(activity, typeProvider, false);
            this.ruleParser = new Parser(validation);

            InitializeDialog(expression);
        }
Exemplo n.º 29
0
        public override bool Validate(RuleValidation validator)
        {
            ValidationError error;

            if (_message == null)
            {
                error = new ValidationError("Message cannot be null", 123);
                validator.Errors.Add(error);
                return(false);
            }
            else
            {
                RuleExpressionInfo result = RuleExpressionWalker.Validate(validator, _message, false);
                if ((result == null) || (result.ExpressionType != typeof(string)))
                {
                    error = new ValidationError("Message must return string result", 123);
                    validator.Errors.Add(error);
                    return(false);
                }
            }
            return(validator.Errors.Count == 0);
        }
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext context)
        {
            string sFullURL = this.SourceSiteURL + @"/" + this.DocumentLibrary + @"/" + this.RuleSetName + ".ruleset";
            WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
            XmlUrlResolver           resolver   = new XmlUrlResolver();

            System.Net.NetworkCredential myCredentials = new System.Net.NetworkCredential("Administrator", "password", "Mossb2tr");
            resolver.Credentials = myCredentials;
            XmlReaderSettings settings = new XmlReaderSettings();

            settings.XmlResolver = resolver;
            XmlReader reader  = XmlReader.Create(sFullURL, settings);
            RuleSet   ruleSet = (RuleSet)serializer.Deserialize(reader);

            reader.Close();
            Activity       targetActivity = Utility.GetRootWorkflow(this.Parent);
            RuleValidation validation     = new RuleValidation(targetActivity.GetType(), null);
            RuleExecution  execution      = new RuleExecution(validation, targetActivity, context);

            ruleSet.Execute(execution);
            return(ActivityExecutionStatus.Closed);
        }
Exemplo n.º 31
0
        public RuleExecution(RuleValidation validation, object thisObject)
        {
            if (validation == null)
            {
                throw new ArgumentNullException("validation");
            }
            if (thisObject == null)
            {
                throw new ArgumentNullException("thisObject");
            }
            if (validation.ThisType != thisObject.GetType())
            {
                throw new InvalidOperationException(
                          string.Format(CultureInfo.CurrentCulture, Messages.ValidationMismatch,
                                        RuleDecompiler.DecompileType(validation.ThisType),
                                        RuleDecompiler.DecompileType(thisObject.GetType())));
            }

            this.validation = validation;
            //this.activity = thisObject as Activity;
            this.thisObject        = thisObject;
            this.thisLiteralResult = new RuleLiteralResult(thisObject);
        }
Exemplo n.º 32
0
        public bool Validate(RuleValidation validation)
        {
            if (validation == null)
            {
                throw new ArgumentNullException("validation");
            }

            // Validate each rule.
            Dictionary <string, object> ruleNames = new Dictionary <string, object>();

            foreach (Rule r in rules)
            {
                if (!string.IsNullOrEmpty(r.Name))  // invalid names caught when validating the rule
                {
                    if (ruleNames.ContainsKey(r.Name))
                    {
                        // Duplicate rule name found.
                        ValidationError error = new ValidationError(Messages.Error_DuplicateRuleName, ErrorNumbers.Error_DuplicateConditions);
                        error.UserData[RuleUserDataKeys.ErrorObject] = r;
                        validation.AddError(error);
                    }
                    else
                    {
                        ruleNames.Add(r.Name, null);
                    }
                }

                r.Validate(validation);
            }

            if (validation.Errors == null || validation.Errors.Count == 0)
            {
                return(true);
            }

            return(false);
        }
Exemplo n.º 33
0
        public RuleSetDialog(Activity activity, System.Workflow.Activities.Rules.RuleSet ruleSet)
        {
            ITypeProvider service;

            this.sortOrder = new bool[4];
            if (activity == null)
            {
                throw new ArgumentNullException("activity");
            }
            this.InitializeDialog(ruleSet);
            this.serviceProvider = activity.Site;
            if (this.serviceProvider != null)
            {
                service = (ITypeProvider)this.serviceProvider.GetService(typeof(ITypeProvider));
                if (service == null)
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.MissingService, new object[] { typeof(ITypeProvider).FullName }));
                }
                WorkflowDesignerLoader loader = this.serviceProvider.GetService(typeof(WorkflowDesignerLoader)) as WorkflowDesignerLoader;
                if (loader != null)
                {
                    loader.Flush();
                }
            }
            else
            {
                TypeProvider provider2 = new TypeProvider(null);
                foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
                {
                    provider2.AddAssembly(assembly);
                }
                service = provider2;
            }
            RuleValidation validation = new RuleValidation(activity, service, false);

            this.ruleParser = new Parser(validation);
        }
Exemplo n.º 34
0
        /// <summary>
        /// we could also do here alot of custom things say if we wanted to try to resolve the problem by providing a default
        /// or whatever we have many options here...
        /// </summary>
        /// <param name="validation"></param>
        /// <param name="expression"></param>
        /// <param name="propertyName"></param>
        private void ValidateExpression(RuleValidation validation, CodeExpression expression, string propertyName)
        {
            ValidationError error;

            if (expression == null)
            {
                error = new ValidationError(propertyName + " cannot be null", 123);
                validation.Errors.Add(error);
            }
            // here would could make sure that the value is not null if we want
            //or perhaps we could verify that the result is a particular type, we have
            //lots of options here to do whatever granular custom validation that we want.
            else
            {
                //do not remove this line very important, will not execute w/o it
                RuleExpressionInfo result = ValidateExpression(validation, expression, false);

                //if (result == null)
                //{
                //    error = new ValidationError(propertyName + " cannot be null value ", 123);
                //    validation.Errors.Add(error);
                //}
            }
        }