public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object valueToConvert)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     string key = valueToConvert as string;
     if ((key == null) || (key.TrimEnd(new char[0]).Length == 0))
     {
         key = string.Empty;
     }
     ISite serviceProvider = PropertyDescriptorUtils.GetSite(context, context.Instance);
     if (serviceProvider == null)
     {
         throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.MissingService, new object[] { typeof(ISite).FullName }));
     }
     RuleSetCollection ruleSets = null;
     RuleDefinitions definitions = ConditionHelper.Load_Rules_DT(serviceProvider, Helpers.GetRootActivity(serviceProvider.Component as Activity));
     if (definitions != null)
     {
         ruleSets = definitions.RuleSets;
     }
     if (((ruleSets != null) && (key.Length != 0)) && !ruleSets.Contains(key))
     {
         RuleSet item = new RuleSet {
             Name = key
         };
         ruleSets.Add(item);
         ConditionHelper.Flush_Rules_DT(serviceProvider, Helpers.GetRootActivity(serviceProvider.Component as Activity));
     }
     return new RuleSetReference { RuleSetName = key };
 }
 public RulesDomModel(RuleSet parentRuleSet)
 {
     ParentRuleSet = parentRuleSet;
     Then = new List<CodeStatement>();
     Else = new List<CodeStatement>();
     Comments = new List<CodeCommentStatement>();
 }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            // verifiy that TargetObject property has been configured
            object input = ModelItem.Properties["Input"].ComputedValue;
            if (input == null)
            {
                System.Windows.MessageBox.Show("Input argument needs to be configured before adding the rules");
                return;
            }

            // verify that target object is correctly configured
            InArgument arg = input as InArgument;
            if (arg == null)
            {
                System.Windows.MessageBox.Show("Invalid value for Input argument");
                return;
            }

            // open the ruleset editor
            Type inputType = arg.ArgumentType;
            RuleSet ruleSet = ModelItem.Properties["RuleSet"].ComputedValue as RuleSet;
            if (ruleSet == null)
                ruleSet = new RuleSet();

            // popup the dialog for editing the rules
            RuleSetDialog ruleSetDialog = new RuleSetDialog(inputType, null, ruleSet);
            DialogResult result = ruleSetDialog.ShowDialog();

            // update the model item
            if (result == DialogResult.OK) //check if they cancelled
            {
                ModelItem.Properties["RuleSet"].SetValue(ruleSetDialog.RuleSet);
            }
        }
Beispiel #4
0
        public RoutingTable()
        {
            this.randomNumberGenerator = new Random();
            this.manager = new XPathMessageContext();

            this.ruleSet = GetRuleSetFromFile(ConfigurationManager.AppSettings["SelectDestinationRuleSetName"], ConfigurationManager.AppSettings["SelectDestinationRulesFile"]);
            this.ruleEngine = new RuleEngine(ruleSet, typeof(RoutingTable));
        }
 public AddedRuleSetAction(RuleSet addedRuleSetDefinition)
 {
     if (addedRuleSetDefinition == null)
     {
         throw new ArgumentNullException("addedRuleSetDefinition");
     }
     this.ruleset = addedRuleSetDefinition;
 }
Beispiel #6
0
 public void Save(RuleSet ruleset, string filename)
 {
     using (XmlTextWriter writer = new XmlTextWriter(filename, null))
     {
         WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
         serializer.Serialize(writer, ruleset);
     }
 }
 public RemovedRuleSetAction(RuleSet removedRuleSetDefinition)
 {
     if (removedRuleSetDefinition == null)
     {
         throw new ArgumentNullException("removedRuleSetDefinition");
     }
     this.ruleset = removedRuleSetDefinition;
 }
Beispiel #8
0
        private void ExecuteRuleSet(System.Workflow.Activities.Rules.RuleSet ruleSet,
                                    RuleValidation rv,
                                    ref MSRuleSetExecutionResult ruleSetExecutionResult)
        {
            RuleExecution re = new RuleExecution(rv, _instanceOfObject);

            ruleSet.Execute(re);
            ruleSetExecutionResult.AddExecutionResult(ruleSet.Name, re);
        }
Beispiel #9
0
 public static RuleSet Deserialize(this RuleSetContract contract)
 {
     RuleSet ruleSet = new RuleSet {
         ChainingBehavior = (RuleChainingBehavior)Enum.Parse(typeof(RuleChainingBehavior), contract.Chaining),
     };
     foreach (RuleContract rule in contract.Rules) {
         ruleSet.Rules.Add(rule.Deserialize());
     }
     return ruleSet;
 }
Beispiel #10
0
        public static void DesignRule(System.Workflow.ComponentModel.Activity activity, bool UseProvider)
        {
            RuleSet ruleSet = null;
            //MessageBox.Show(activity.UserData[0].ToString());
            //MessageBox.Show(activity.GetType().ToString());
            string ruleName = activity.UserData[0].ToString();

            //load ruleset
            try
            {
                ruleSet = RuleSetManagerFactory.CreateRuleSetManager(RuleDesigner.RemotingUrl).getRuleSetDesign("", "", ruleName);
            }
            catch (Exception e)
            {
                MessageBox.Show("Error deserializing file: " + ruleName + e.Message);
            }

            if (ruleSet == null)
            {
                MessageBox.Show("RuleSet is null");
                ruleSet = new RuleSet(ruleName);
            }

            RuleSetDialog ruleSetDialog = null;
            if (UseProvider)
            {
                TypeProvider provider = new TypeProvider(null);
                AssemblyName[] ass = activity.GetType().Assembly.GetReferencedAssemblies();
                provider.AddAssembly(activity.GetType().Assembly);
                FillWithAssemblies(provider, ass);
                ruleSetDialog = new RuleSetDialog(activity.GetType(), provider, ruleSet);
            }
            else
            {
                ruleSetDialog = new RuleSetDialog(activity, ruleSet);
            }

            var result = ruleSetDialog.ShowDialog();

            // Only update the .rules file if the OK is pressed 
            if (result == DialogResult.OK)
            {
                ruleSet = ruleSetDialog.RuleSet;
                try
                {
                    Console.WriteLine(ruleName);
                    RuleSetManagerFactory.CreateRuleSetManager(RuleDesigner.RemotingUrl).saveRuleSetDesign("", "", ruleName, ruleSet);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
            }
        }
Beispiel #11
0
        public RuleSetDialog(System.Type activityType, ITypeProvider typeProvider, System.Workflow.Activities.Rules.RuleSet ruleSet)
        {
            this.sortOrder = new bool[4];
            if (activityType == null)
            {
                throw new ArgumentNullException("activityType");
            }
            this.InitializeDialog(ruleSet);
            RuleValidation validation = new RuleValidation(activityType, typeProvider);

            this.ruleParser = new Parser(validation);
        }
        public MSRuleSetTranslationResult(System.Workflow.Activities.Rules.RuleSet dotNetRuleSet,
                                          RuleSetDefinition.RuleSetDefinitions ruleSetDefinitionsAfterTranslation, CodeDomObject codeDomObject,
                                          Dictionary <Guid, TranslationValidationResult> rulesTranslationErrors)
        {
            _dotNetRuleSet = dotNetRuleSet;
            _ruleDefinitionsAfterTranslation = ruleSetDefinitionsAfterTranslation;
            _referenceToCodeDomObject        = codeDomObject;
            _rulesTranslationErrors          = rulesTranslationErrors;

            LoadRuleGuidToRuleName();
            LoadLastModifiedOrCreatedDictionary();
            RemoveRulesNotTranslatedToDotNetRuleSet(rulesTranslationErrors.Keys.ToList());
        }
Beispiel #13
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);
        }
 internal RuleEngine(RuleSet ruleSet, RuleValidation validation, ActivityExecutionContext executionContext)
 {
     if (!ruleSet.Validate(validation))
     {
         throw new RuleSetValidationException(string.Format(CultureInfo.CurrentCulture, Messages.RuleSetValidationFailed, new object[] { ruleSet.name }), validation.Errors);
     }
     this.name = ruleSet.Name;
     this.validation = validation;
     Tracer tracer = null;
     if (WorkflowActivityTrace.Rules.Switch.ShouldTrace(TraceEventType.Information))
     {
         tracer = new Tracer(ruleSet.Name, executionContext);
     }
     this.analyzedRules = Executor.Preprocess(ruleSet.ChainingBehavior, ruleSet.Rules, validation, tracer);
 }
Beispiel #15
0
        public string CompileRuleset(RuleSet ruleset, List<RuleObject> rulesObject)
        {
            Rule rule = ruleset.Rules.ElementAt(0).Clone();
            RuleStatementAction action = (RuleStatementAction)rule.
                ThenActions.ElementAt(0).Clone();

            ruleset.Rules.Clear();

            foreach (RuleObject ruleObj in rulesObject)
            {
                Rule thisRule = SetUpRule(rule, action, ruleObj);
                ruleset.Rules.Add(thisRule);
            }

            RulesetDetails rulesetDetails = new RulesetDetails();
            return SerializeRuleSet(ruleset);
        }
 public UpdatedRuleSetAction(RuleSet originalRuleSetDefinition, RuleSet updatedRuleSetDefinition)
 {
     if (originalRuleSetDefinition == null)
     {
         throw new ArgumentNullException("originalRuleSetDefinition");
     }
     if (updatedRuleSetDefinition == null)
     {
         throw new ArgumentNullException("updatedRuleSetDefinition");
     }
     if (originalRuleSetDefinition.Name != updatedRuleSetDefinition.Name)
     {
         throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Messages.ConditionNameNotIdentical, new object[] { originalRuleSetDefinition.Name, updatedRuleSetDefinition.Name }));
     }
     this.original = originalRuleSetDefinition;
     this.updated = updatedRuleSetDefinition;
 }
Beispiel #17
0
 private void InitializeDialog(System.Workflow.Activities.Rules.RuleSet ruleSet)
 {
     this.InitializeComponent();
     this.conditionTextBox.PopulateAutoCompleteList += new EventHandler <AutoCompletionEventArgs>(this.PopulateAutoCompleteList);
     this.thenTextBox.PopulateAutoCompleteList      += new EventHandler <AutoCompletionEventArgs>(this.PopulateAutoCompleteList);
     this.elseTextBox.PopulateAutoCompleteList      += new EventHandler <AutoCompletionEventArgs>(this.PopulateAutoCompleteList);
     this.conditionTextBox.PopulateToolTipList      += new EventHandler <AutoCompletionEventArgs>(this.PopulateAutoCompleteList);
     this.thenTextBox.PopulateToolTipList           += new EventHandler <AutoCompletionEventArgs>(this.PopulateAutoCompleteList);
     this.elseTextBox.PopulateToolTipList           += new EventHandler <AutoCompletionEventArgs>(this.PopulateAutoCompleteList);
     this.reevaluationComboBox.Items.Add(Messages.ReevaluationNever);
     this.reevaluationComboBox.Items.Add(Messages.ReevaluationAlways);
     this.chainingBehaviourComboBox.Items.Add(Messages.Sequential);
     this.chainingBehaviourComboBox.Items.Add(Messages.ExplicitUpdateOnly);
     this.chainingBehaviourComboBox.Items.Add(Messages.FullChaining);
     base.HelpRequested     += new HelpEventHandler(this.OnHelpRequested);
     base.HelpButtonClicked += new CancelEventHandler(this.OnHelpClicked);
     if (ruleSet != null)
     {
         this.dialogRuleSet = ruleSet.Clone();
     }
     else
     {
         this.dialogRuleSet = new System.Workflow.Activities.Rules.RuleSet();
     }
     this.chainingBehaviourComboBox.SelectedIndex = (int)this.dialogRuleSet.ChainingBehavior;
     this.rulesListView.Select();
     foreach (Rule rule in this.dialogRuleSet.Rules)
     {
         this.AddNewItem(rule);
     }
     if (this.rulesListView.Items.Count > 0)
     {
         this.rulesListView.Items[0].Selected = true;
     }
     else
     {
         this.rulesListView_SelectedIndexChanged(this, new EventArgs());
     }
 }
Beispiel #18
0
        internal static bool ValidateRuleSet(System.Workflow.Activities.Rules.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);
            }

            var ruleValidation = new RuleValidation(targetType, null);

            ruleSetToValidate.Validate(ruleValidation);
            if (ruleValidation.Errors.Count == 0)
            {
                return(true);
            }
            var 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);
            }
            return(validationDialog.ContinueWithChange);
        }
 internal static string GetRuleSetPreview(RuleSet ruleSet)
 {
     StringBuilder builder = new StringBuilder();
     bool flag = true;
     if (ruleSet != null)
     {
         foreach (Rule rule in ruleSet.Rules)
         {
             if (flag)
             {
                 flag = false;
             }
             else
             {
                 builder.Append("\n");
             }
             builder.Append(rule.Name);
             builder.Append(": ");
             builder.Append(GetRulePreview(rule));
         }
     }
     return builder.ToString();
 }
Beispiel #20
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);
        }
        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;
            }
        }
        public UpdatedRuleSetAction(RuleSet originalRuleSetDefinition, RuleSet updatedRuleSetDefinition)
        {
            if (originalRuleSetDefinition == null)
                throw new ArgumentNullException("originalRuleSetDefinition");
            if (updatedRuleSetDefinition == null)
                throw new ArgumentNullException("updatedRuleSetDefinition");

            if (originalRuleSetDefinition.Name != updatedRuleSetDefinition.Name)
            {
                string message = string.Format(CultureInfo.CurrentCulture, Messages.ConditionNameNotIdentical, originalRuleSetDefinition.Name, updatedRuleSetDefinition.Name);
                throw new ArgumentException(message);
            }
            original = originalRuleSetDefinition;
            updated = updatedRuleSetDefinition;
        }
 public void saveRuleSet(string site, string station, string name, RuleSet ruleSet)
 {
     StringWriter sw = new StringWriter();
     using (XmlTextWriter writer = new XmlTextWriter(sw))
     {
         RuleDefinitions ruleDef = new RuleDefinitions();
         ruleDef.RuleSets.Add(ruleSet);
         WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
         serializer.Serialize(writer, ruleDef);
     }
     string content = sw.ToString();
     RouteManager.WriteRuleSet(site, station, name, content);
 }
Beispiel #24
0
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            ValidationErrorCollection errors    = base.Validate(manager, obj);
            RuleSetReference          reference = obj as RuleSetReference;

            if (reference == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Messages.UnexpectedArgumentType, new object[] { typeof(RuleSetReference).FullName, "obj" }), "obj");
            }
            Activity activity = manager.Context[typeof(Activity)] as Activity;

            if (activity == null)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.ContextStackItemMissing, new object[] { typeof(Activity).Name }));
            }
            if (!(manager.Context[typeof(PropertyValidationContext)] is PropertyValidationContext))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.ContextStackItemMissing, new object[] { typeof(PropertyValidationContext).Name }));
            }
            if (!string.IsNullOrEmpty(reference.RuleSetName))
            {
                RuleDefinitions   definitions       = null;
                RuleSetCollection ruleSets          = null;
                CompositeActivity declaringActivity = Helpers.GetDeclaringActivity(activity);
                if (declaringActivity == null)
                {
                    declaringActivity = Helpers.GetRootActivity(activity) as CompositeActivity;
                }
                if (activity.Site != null)
                {
                    definitions = ConditionHelper.Load_Rules_DT(activity.Site, declaringActivity);
                }
                else
                {
                    definitions = ConditionHelper.Load_Rules_RT(declaringActivity);
                }
                if (definitions != null)
                {
                    ruleSets = definitions.RuleSets;
                }
                if ((ruleSets == null) || !ruleSets.Contains(reference.RuleSetName))
                {
                    ValidationError error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.RuleSetNotFound, new object[] { reference.RuleSetName }), 0x576)
                    {
                        PropertyName = base.GetFullPropertyName(manager) + ".RuleSetName"
                    };
                    errors.Add(error);
                    return(errors);
                }
                RuleSet       set     = ruleSets[reference.RuleSetName];
                ITypeProvider service = (ITypeProvider)manager.GetService(typeof(ITypeProvider));
                using ((WorkflowCompilationContext.Current == null) ? WorkflowCompilationContext.CreateScope(manager) : null)
                {
                    RuleValidation validation = new RuleValidation(activity, service, WorkflowCompilationContext.Current.CheckTypes);
                    set.Validate(validation);
                    ValidationErrorCollection errors2 = validation.Errors;
                    if (errors2.Count > 0)
                    {
                        string fullPropertyName = base.GetFullPropertyName(manager);
                        string str6             = string.Format(CultureInfo.CurrentCulture, Messages.InvalidRuleSetExpression, new object[] { fullPropertyName });
                        int    errorNumber      = 0x577;
                        if (activity.Site != null)
                        {
                            foreach (ValidationError error2 in errors2)
                            {
                                ValidationError error3 = new ValidationError(error2.ErrorText, errorNumber)
                                {
                                    PropertyName = fullPropertyName + ".RuleSet Definition"
                                };
                                errors.Add(error3);
                            }
                            return(errors);
                        }
                        foreach (ValidationError error4 in errors2)
                        {
                            ValidationError error5 = new ValidationError(str6 + " " + error4.ErrorText, errorNumber)
                            {
                                PropertyName = fullPropertyName
                            };
                            errors.Add(error5);
                        }
                    }
                    return(errors);
                }
            }
            ValidationError item = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.InvalidRuleSetName, new object[] { "RuleSetReference" }), 0x578)
            {
                PropertyName = base.GetFullPropertyName(manager) + ".RuleSetName"
            };

            errors.Add(item);
            return(errors);
        }
 private void InitializeDialog(System.Workflow.Activities.Rules.RuleSet ruleSet)
 {
     this.InitializeComponent();
     this.conditionTextBox.PopulateAutoCompleteList += new EventHandler<AutoCompletionEventArgs>(this.PopulateAutoCompleteList);
     this.thenTextBox.PopulateAutoCompleteList += new EventHandler<AutoCompletionEventArgs>(this.PopulateAutoCompleteList);
     this.elseTextBox.PopulateAutoCompleteList += new EventHandler<AutoCompletionEventArgs>(this.PopulateAutoCompleteList);
     this.conditionTextBox.PopulateToolTipList += new EventHandler<AutoCompletionEventArgs>(this.PopulateAutoCompleteList);
     this.thenTextBox.PopulateToolTipList += new EventHandler<AutoCompletionEventArgs>(this.PopulateAutoCompleteList);
     this.elseTextBox.PopulateToolTipList += new EventHandler<AutoCompletionEventArgs>(this.PopulateAutoCompleteList);
     this.reevaluationComboBox.Items.Add(Messages.ReevaluationNever);
     this.reevaluationComboBox.Items.Add(Messages.ReevaluationAlways);
     this.chainingBehaviourComboBox.Items.Add(Messages.Sequential);
     this.chainingBehaviourComboBox.Items.Add(Messages.ExplicitUpdateOnly);
     this.chainingBehaviourComboBox.Items.Add(Messages.FullChaining);
     base.HelpRequested += new HelpEventHandler(this.OnHelpRequested);
     base.HelpButtonClicked += new CancelEventHandler(this.OnHelpClicked);
     if (ruleSet != null)
     {
         this.dialogRuleSet = ruleSet.Clone();
     }
     else
     {
         this.dialogRuleSet = new System.Workflow.Activities.Rules.RuleSet();
     }
     this.chainingBehaviourComboBox.SelectedIndex = (int) this.dialogRuleSet.ChainingBehavior;
     this.rulesListView.Select();
     foreach (Rule rule in this.dialogRuleSet.Rules)
     {
         this.AddNewItem(rule);
     }
     if (this.rulesListView.Items.Count > 0)
     {
         this.rulesListView.Items[0].Selected = true;
     }
     else
     {
         this.rulesListView_SelectedIndexChanged(this, new EventArgs());
     }
 }
Beispiel #26
0
		public static string Serialize(RuleSet rules)
		{
			StringBuilder sbXOML = new StringBuilder();
			using ( StringWriter wtr = new StringWriter(sbXOML, System.Globalization.CultureInfo.InvariantCulture) )
			{
				using ( XmlTextWriter xwtr = new XmlTextWriter(wtr) )
				{
					WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
					serializer.Serialize(xwtr, rules);
				}
			}
			return sbXOML.ToString();
		}
Beispiel #27
0
 internal MSRuleSetEvaluationResult Evaluate(System.Workflow.Activities.Rules.RuleSet ruleSet, T instanceOfObject)
 {
     _instanceOfObject = instanceOfObject;
     return(EvaluateRuleSet(ruleSet, false));
 }
 public RuleEngine(RuleSet ruleSet, RuleValidation validation)
     : this(ruleSet, validation, null)
 {
 }
        private string SerializeRuleSet(RuleSet ruleSet)
        {
            StringBuilder ruleDefinition = new StringBuilder();

            if (ruleSet != null)
            {
                try
                {
                    StringWriter stringWriter = new StringWriter(ruleDefinition, CultureInfo.InvariantCulture);
                    XmlTextWriter writer = new XmlTextWriter(stringWriter);
                    serializer.Serialize(writer, ruleSet);
                    writer.Flush();
                    writer.Close();
                    stringWriter.Flush();
                    stringWriter.Close();
                }
                catch (Exception ex)
                {
                    if (selectedRuleSetData != null)
                        MessageBox.Show(string.Format(CultureInfo.InvariantCulture, "Error serializing RuleSet: '{0}'. \r\n\n{1}", selectedRuleSetData.Name, ex.Message), "Serialization Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    else
                        MessageBox.Show(string.Format(CultureInfo.InvariantCulture, "Error serializing RuleSet. \r\n\n{0}", ex.Message), "Serialization Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                if (selectedRuleSetData != null)
                    MessageBox.Show(String.Format(CultureInfo.InvariantCulture, "Error serializing RuleSet: '{0}'.", selectedRuleSetData.Name), "Serialization Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    MessageBox.Show("Error serializing RuleSet.", "Serialization Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return ruleDefinition.ToString();
        }
 private static void ExecuteRuleSet(RuleSet ruleSet, System.Workflow.ComponentModel.Activity root, ActivityExecutionContext executionContext)
 {
     RuleValidation validation = new RuleValidation(root.GetType(), null);
     RuleExecution execution = new RuleExecution(validation, root, executionContext);
     ruleSet.Execute(execution);
 }
Beispiel #31
0
        public MSRuleSetEvaluationResult EvaluateRuleSet(System.Workflow.Activities.Rules.RuleSet ruleSet, bool translatedRule)
        {
            MSRuleSetEvaluationResult ruleSetEvaluationResult = null;

            if (translatedRule)
            {
                ruleSetEvaluationResult = new MSRuleSetEvaluationResult(_msRuleSetTranslationResult);
            }
            else
            {
                ruleSetEvaluationResult = new MSRuleSetEvaluationResult();
            }

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

            ruleSet.Validate(rv);

            ValidationErrorCollection errors = rv.Errors;

            if (errors.Count > 0)
            {
                //string validationErrorMessages = Helper.GetErrorMessageFromValidationErrorsCollection(errors);

                // if the rule set has errors at top level should we stop here or try each individual rule?  i think for now
                //we can continue to try each individual rule and then after evaluations report the errors in the return execution result
                //object

                ruleSetEvaluationResult.AddRuleSetValidationErrors(errors);
            }

            foreach (System.Workflow.Activities.Rules.Rule rule in ruleSet.Rules)
            {
                if (rule.Active)
                {
                    try
                    {
                        EvaluateRule(rule, ref ruleSetEvaluationResult, ref rv);
                    }
                    catch (RuleEvaluationException rex)
                    {
                        //_log.Error("Rule Name:  " + rule.Name + "threw a Rule Evaluation Exception during its evaluation.  ", rex);
                        //loop again cause if this one failed we still want to try to evaluate the other rules in this rule set
                        if (rex.InnerException != null)
                        {
                            ruleSetEvaluationResult.AddEvaluationError(rule.Name, rule.Description, (Exception)rex.InnerException);
                        }
                        else
                        {
                            ruleSetEvaluationResult.AddEvaluationError(rule.Name, rule.Description, (Exception)rex);
                        }
                        continue;
                    }
                    catch (Exception ex)
                    {
                        //_log.Error("Unhandled exception during evaluation of Rule Name:  " + rule.Name, ex);
                        ruleSetEvaluationResult.AddEvaluationError(rule.Name, rule.Description, ex);
                        continue;
                    }
                }
                else
                {
                    ruleSetEvaluationResult.AddRuleToInactive(rule.Name, rule.Description);
                }
            }

            return(ruleSetEvaluationResult);
        }
Beispiel #32
0
        private string SerializeRuleSet(RuleSet ruleset)
        {
            WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
            StringBuilder ruleDefinition = new StringBuilder();

            if (ruleset != null)
            {
                try
                {
                    StringWriter stringWriter = new StringWriter(ruleDefinition);
                    XmlTextWriter writer = new XmlTextWriter(stringWriter);
                    serializer.Serialize(writer, ruleset);
                    writer.Flush();
                    writer.Close();
                    stringWriter.Flush();
                    stringWriter.Close();
                }
                catch (Exception ex)
                {
                }
            }

            return ruleDefinition.ToString();
        }
Beispiel #33
0
		public static RuleSet BuildRuleSet(DataTable dtRules, RuleValidation validation)
		{
			RuleSet        rules = new RuleSet("RuleSet 1");
			RulesParser    parser = new RulesParser(validation);

			DataView vwRules = new DataView(dtRules);
			vwRules.RowFilter = "ACTIVE = 1";
			vwRules.Sort      = "PRIORITY asc";
			foreach ( DataRowView row in vwRules )
			{
				string sRULE_NAME    = Sql.ToString (row["RULE_NAME"   ]);
				int    nPRIORITY     = Sql.ToInteger(row["PRIORITY"    ]);
				string sREEVALUATION = Sql.ToString (row["REEVALUATION"]);
				bool   bACTIVE       = Sql.ToBoolean(row["ACTIVE"      ]);
				string sCONDITION    = Sql.ToString (row["CONDITION"   ]);
				string sTHEN_ACTIONS = Sql.ToString (row["THEN_ACTIONS"]);
				string sELSE_ACTIONS = Sql.ToString (row["ELSE_ACTIONS"]);
				
				RuleExpressionCondition condition      = parser.ParseCondition    (sCONDITION   );
				List<RuleAction>        lstThenActions = parser.ParseStatementList(sTHEN_ACTIONS);
				List<RuleAction>        lstElseActions = parser.ParseStatementList(sELSE_ACTIONS);
				System.Workflow.Activities.Rules.Rule r = new System.Workflow.Activities.Rules.Rule(sRULE_NAME, condition, lstThenActions, lstElseActions);
				r.Priority = nPRIORITY;
				r.Active   = bACTIVE  ;
				//r.ReevaluationBehavior = (RuleReevaluationBehavior) Enum.Parse(typeof(RuleReevaluationBehavior), sREEVALUATION);
				// 12/04/2010   Play it safe and never-reevaluate. 
				r.ReevaluationBehavior = RuleReevaluationBehavior.Never;
				rules.Rules.Add(r);
			}
			rules.Validate(validation);
			if ( validation.Errors.HasErrors )
			{
				throw(new Exception(RulesUtil.GetValidationErrors(validation)));
			}
			return rules;
		}
Beispiel #34
0
		// 12/12/2012   For security reasons, we want to restrict the data types available to the rules wizard. 
		public static void RulesValidate(Guid gID, string sRULE_NAME, int nPRIORITY, string sREEVALUATION, bool bACTIVE, string sCONDITION, string sTHEN_ACTIONS, string sELSE_ACTIONS, Type thisType, SplendidRulesTypeProvider typeProvider)
		{
			RuleSet        rules      = new RuleSet("RuleSet 1");
			RuleValidation validation = new RuleValidation(thisType, typeProvider);
			RulesParser    parser     = new RulesParser(validation);
			RuleExpressionCondition condition      = parser.ParseCondition    (sCONDITION   );
			List<RuleAction>        lstThenActions = parser.ParseStatementList(sTHEN_ACTIONS);
			List<RuleAction>        lstElseActions = parser.ParseStatementList(sELSE_ACTIONS);

			System.Workflow.Activities.Rules.Rule r = new System.Workflow.Activities.Rules.Rule(sRULE_NAME, condition, lstThenActions, lstElseActions);
			r.Priority = nPRIORITY;
			r.Active   = bACTIVE  ;
			//r.ReevaluationBehavior = (RuleReevaluationBehavior) Enum.Parse(typeof(RuleReevaluationBehavior), sREEVALUATION);
			// 12/04/2010   Play it safe and never-reevaluate. 
			r.ReevaluationBehavior = RuleReevaluationBehavior.Never;
			rules.Rules.Add(r);
			rules.Validate(validation);
			if ( validation.Errors.HasErrors )
			{
				throw(new Exception(GetValidationErrors(validation)));
			}
		}
 public void saveRuleSetDesign(string site, string station, string name, RuleSet ruleSet)
 {
     saveRuleSet(site, station, name, ruleSet);
 }
 public RuleEngine(RuleSet ruleSet, Type objectType)
     : this(ruleSet, new RuleValidation(objectType, null), null)
 {
 }
Beispiel #37
0
        public void SetUp()
        {
            ruleService = new RuleService();
            rulesetWrapper = new CardShop.Models.RuleSet();
            rulesets = new List<CardShop.Models.RuleSet>();
            ruleset = new System.Workflow.Activities.Rules.RuleSet();
            ruleObject = new RuleObject();
            ruleObjects = new List<RuleObject>();
            rulesetDetails = new RulesetDetails();

            mockRuleService = new Mock<IRuleService>();
            mockContext = new Mock<IPracticeGDVPDao>();
            mockDbSet = new Mock<IDbSet<CardShop.Models.RuleSet>>();

            ruleService.dbContext = mockContext.Object;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Excel.Range cell;

            RuleSet myRuleset = new RuleSet("RuleSet1");

            // Define property and activity reference expressions through CodeDom functionality
            CodeThisReferenceExpression refexp = new CodeThisReferenceExpression();
            CodePropertyReferenceExpression refTotalCost = new CodePropertyReferenceExpression(refexp, "totalCost");
            CodePropertyReferenceExpression refParamCategory = new CodePropertyReferenceExpression(refexp, "paramCategory");
            CodePropertyReferenceExpression refParamPrivilege = new CodePropertyReferenceExpression(refexp, "paramPrivilege");

            // Example :
            // IF paramCategory == 3
            // THEN totalCost = totalCost + 300

            for (int row = 4; row <= 8; row++)
            {
                cell = (Excel.Range)this.Cells[row, 2];
                if (String.IsNullOrEmpty((string)cell.Value2))
                    break;
                Rule myRule = new Rule("Rule" + row);
                myRuleset.Rules.Add(myRule);

                // Example :
                // paramCategory == 3
                CodeBinaryOperatorExpression ruleCondition = new CodeBinaryOperatorExpression();
                if ((string)cell.Value2 == "種別 (category)")
                    ruleCondition.Left = refParamCategory;
                else if ((string)cell.Value2 == "特典 (privilige)")
                    ruleCondition.Left = refParamPrivilege;
                ruleCondition.Operator = CodeBinaryOperatorType.ValueEquality;
                cell = (Excel.Range)this.Cells[row, 3];
                ruleCondition.Right = new CodePrimitiveExpression((int)(double)cell.Value2);
                myRule.Condition = new RuleExpressionCondition(ruleCondition);

                // Example :
                // totalCost = totalCost + 300
                CodeAssignStatement ruleAction = new CodeAssignStatement();
                ruleAction.Left = refTotalCost;
                CodeBinaryOperatorExpression actionRight = new CodeBinaryOperatorExpression();
                actionRight.Left = refTotalCost;
                cell = (Excel.Range)this.Cells[row, 4];
                if((string)cell.Value2 == "+")
                    actionRight.Operator = CodeBinaryOperatorType.Add;
                else if ((string)cell.Value2 == "-")
                    actionRight.Operator = CodeBinaryOperatorType.Subtract;
                else if ((string)cell.Value2 == "*")
                    actionRight.Operator = CodeBinaryOperatorType.Multiply;
                else if ((string)cell.Value2 == "/")
                    actionRight.Operator = CodeBinaryOperatorType.Divide;
                cell = (Excel.Range)this.Cells[row, 5];
                actionRight.Right = new CodePrimitiveExpression((int)(double)cell.Value2);
                ruleAction.Right = actionRight;
                myRule.ThenActions.Add(new RuleStatementAction(ruleAction));
            }

            // 必要に応じ、RuleValidation オブジェクトを使ってチェック!
            // (今回は省略 . . . . . . .)

            // RuleDefinitions を設定して保存
            RuleDefinitions ruleDef = new RuleDefinitions();
            ruleDef.RuleSets.Add(myRuleset);
            WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
            cell = (Excel.Range) this.Cells[11, 2];
            XmlTextWriter writer = new XmlTextWriter((string) cell.Value2, System.Text.Encoding.Unicode);
            serializer.Serialize(writer, ruleDef);
            writer.Close();

            // ここでは、すぐにコンパイルして実行
            // (Custom WorkflowRuntime Service と Custom Policy Activity を作成して、データベースなど独自の Rule Cache を作成することも可能 . . .)

            MessageBox.Show("ルールを反映しました");
        }
 private RuleSetData CreateRuleSetData(RuleSet ruleSet)
 {
     RuleSetData data = new RuleSetData();
     if (ruleSet != null)
     {
         data.Name = ruleSet.Name;
         data.RuleSet = ruleSet;
     }
     else
     {
         data.Name = this.GenerateRuleSetName();
         data.RuleSet = new RuleSet(data.Name);
     }
     data.MajorVersion = 1;
     this.MarkDirty(data);
     return data;
 }
Beispiel #40
0
		public static void CreateDynamicRule(string fileNameWithPath, TPromotionRule promotionRuleObj)
		{
			Rule minTktFareRule = null;
			Rule validityStartDateRule = null;
			Rule validityEndDateRule = null;
			Rule validDayRule = null;
			Rule validRouteRule = null;
			Rule validBulkBookingRule = null;
			Rule validAdvanceBookingRule = null;
			Rule validLastMinuteBookingRule = null;
			Rule discountRule = null;
			Rule offerCodeRule = null;
			Rule maxDiscountLimitRule = null;
			
			RuleSet ruleSet = new RuleSet(promotionRuleObj.OfferCode +  "RuleSet");
			
			if(promotionRuleObj.MinTicketFare != decimal.Zero)
			{
				minTktFareRule = CreateMinTicketFareRule(promotionRuleObj);
				ruleSet.Rules.Add(minTktFareRule);
			}

			if (promotionRuleObj.ValidityStartDate != null)
			{
				validityStartDateRule = CreateValidityStartDateRule(promotionRuleObj);
				ruleSet.Rules.Add(validityStartDateRule);
			}

			if (promotionRuleObj.ValidityEndDate != null)
			{
				validityEndDateRule = CreateValidityEndDateRule(promotionRuleObj);
				ruleSet.Rules.Add(validityEndDateRule);
			}

			if(promotionRuleObj.DaysCSV != null)
			{
			   validDayRule = CreateValidDayRule(promotionRuleObj);
			   ruleSet.Rules.Add(validDayRule);
			}

			if (promotionRuleObj.RouteIDCSV != null)
			{
				validRouteRule = CreateValidRouteRule(promotionRuleObj);
				ruleSet.Rules.Add(validRouteRule);
			}

			if (promotionRuleObj.MinNumOfSeats != null)
			{
				validBulkBookingRule = CreateValidBulkBookingRule(promotionRuleObj);
				ruleSet.Rules.Add(validBulkBookingRule);
			}

			if (promotionRuleObj.MinNumOfAdvanceBookingDays != null)
			{
				validAdvanceBookingRule = CreateValidAdvanceBookingRule(promotionRuleObj);
				ruleSet.Rules.Add(validAdvanceBookingRule);
			}

			if (promotionRuleObj.LastMinuteCountBeforeDept != null)
			{
				validLastMinuteBookingRule = CreateValidLastMinBookingRule(promotionRuleObj);
				ruleSet.Rules.Add(validLastMinuteBookingRule);
			}

			if (promotionRuleObj.DiscountUnit != decimal.Zero)
			{
				discountRule = CreateDiscountUnitRule(promotionRuleObj);
			}
			else if(promotionRuleObj.DiscountPercent != decimal.Zero)
			{
				discountRule = CreateDiscountPercentRule(promotionRuleObj);
			}

			ruleSet.Rules.Add(discountRule);

			offerCodeRule = CreateOfferCodeRule(promotionRuleObj);
			ruleSet.Rules.Add(offerCodeRule);

			if(promotionRuleObj.MaxDiscountAmount != decimal.Zero)
			{
				maxDiscountLimitRule = CreateMaxDiscountLimitRule(promotionRuleObj);
				ruleSet.Rules.Add(maxDiscountLimitRule);
			}

			using (XmlWriter xmlWriter = XmlWriter.Create(fileNameWithPath))
			{
				WorkflowMarkupSerializer markupSerializer = new WorkflowMarkupSerializer();
				markupSerializer.Serialize(xmlWriter, ruleSet);
			}
		}