---
title: "坚持学习WF(23):以代码的方式构造和执行RuleSet"
author: "carysun"
date: "2008-10-12T12:19:00Z"
tags: []
slug: "wf-23-ruleset"
draft: false
lastmod: "2008-10-12T12:19:00Z"
id: 463259
url: "https://carysun.iteye.com/blog/463259"
---

[\[置顶\]坚持学习WF文章索引](/carysun/archive/2008/05/29/WF.html)

通常情况下，我们都是使用PolicyActivity活动来执行RuleSet。除了这种方式我们还可以用代码的方式来执行。首先我们建立一个项目，借助PolicyActivity的的规则编辑器来构造一个最简单的RuleSet，该RuleSet包括一个最简单的规则为RuleTest，如下表：

Rule Conditon ThenAction ElseAction RuleTest True System.Console.WriteLine("Hello World")  

**以代码方式执行RuleSet**

规则集建立完成后会生成对应的.Rules文件，这时候我们就可以删掉PolicyActivity，添加一个CodeActivity活动来以代码的方式执行RuleSet，代码如下：

```
Assembly assembly = Assembly.GetAssembly(typeof(Workflow1));
Stream stream = assembly.GetManifestResourceStream("Workflow1.rules");

using (XmlReader xmlReader = XmlReader.Create(new StreamReader(stream)))
{
      WorkflowMarkupSerializer markupSerializer = new WorkflowMarkupSerializer();
      RuleDefinitions ruleDefinitions = markupSerializer.Deserialize(xmlReader) as RuleDefinitions;
      if (ruleDefinitions != null)
      {
           if (ruleDefinitions.RuleSets.Contains("CaryRuleSetTest"))
           {
               RuleSet rs = ruleDefinitions.RuleSets["CaryRuleSetTest"];
               RuleValidation validation = new RuleValidation(typeof(Workflow1), 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);
                   }
               }
            }
        }
}
```

**以代码方式构造RuleSet**

上面的例子中我们以代码的方式执行了RuleSet,这个RuleSet是利用PolicyActivity的规则编辑器生成的.Rules文件，我们也可以使用CodeDom技术来构造一个RuleSet，我们就以上面的RuleSet为例，构造一个同样的RuleSet并执行，代码如下：

```
RuleSet rs = new RuleSet("CaryRuleSetTest");
Rule RuleTest = new Rule("RuleTest");
//condition:true           
CodePrimitiveExpression condition = new CodePrimitiveExpression(true);
RuleTest.Condition = new RuleExpressionCondition(condition);
//ThenActions:System.Console.WriteLine("Hello World")           
CodeExpressionStatement then = new CodeExpressionStatement(
     new CodeMethodInvokeExpression(
         new CodeTypeReferenceExpression("System.Console"), "WriteLine",
         new CodePrimitiveExpression("Hello World2!")));
RuleTest.ThenActions.Add(new RuleStatementAction(then));

rs.Rules.Add(RuleTest);

RuleValidation validation= new RuleValidation(typeof(Workflow2), 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);
    }
}
```

```
执行的效果如下图：
```

```
 
```