matt winkler – technical evangelist wf microsoft corporation con312

Post on 23-Dec-2015

214 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Rules Engine Use and Extensibility in Microsoft Windows Workflow FoundationMatt Winkler – Technical Evangelist WFMicrosoft Corporationhttp://blogs.msdn.com/mwinkle

CON312

Agenda

IntroductionRule executionRule extensibility

Activity Library

Workflow Runtime Engine

Runtime Services

Visual Studio Designer

Long Running Logic

Flexibility

What is Workflow?

Workflow is the software implementation of business process or business logic

What’s the value of Workflow?

Released Nov 2006 as a part of Windows Vista

Transparency

A Workflow

Host Process

Activity

Windows Workflow Foundation

WF Rules Terminology

Conditions Boolean expressions

RuleIf Condition THEN <ThenActions> ELSE <ElseActions>

RuleSetCollection of rulesExecution semantics

Rules BenefitsSimple semantics for defining discrete, atomic rulesAggregation of rules into rule sets that represent rich application behavior

Modeling Power

Declarative nature allows domain experts to concentrate on the business requirements

Model-driven design allows for rich authoring and management toolsExternalization of rule logic from application code

Rapid deployment model

Supporting impact analysis and simulation capabilities

Approachability

Ease of Change

Why Rules?

Externalize decision details from processCreate tooling for rule customization by non-developersExecute a set of rules against a set of factsTake advantage of complex execution semantics that are nearly impossible to model in code

Where Do We Use Rules?Activity Conditions

If-ElseWhileReplicator Conditioned Activity Group (CAG)Conditions on Custom Activities

Policy ActivityEncapsulates the definition and execution of a RuleSet

Custom Activities.NET Applications

Rule Execution

Activity Conditions

Code conditionsFast, fast, fastCompiled into workflow

Declarative conditionsExternalized in .rules fileCompiled into workflow, but easy to change

Externalizing Rules

Versioning and ManagementIndependent from the applicationSpecialized management tools for rules

Deployment and CompilationEase of changeNo application recompilationRules only deployment / No application redeployment

Externalizing Rules Approach 1Use declarative, XAML-only workflows

public WorkflowInstance CreateWorkflow(

XmlReader workflowDefinitionReader, XmlReader rulesReader, Dictionary<string, object>

namedArgumentValues)

Externalizing Rules Approach 2Use DynamicUpdate

static void UpdateRules(WorkflowInstance instance){

WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();XmlTextReader reader = new XmlTextReader("..\\RealRules.rules");RuleDefinitions rules = serializer.Deserialize(reader) as RuleDefinitions;WorkflowChanges changes = new WorkflowChanges( instance.GetWorkflowDefinition());changes.TransientWorkflow.SetValue(

RuleDefinitions.RuleDefinitionsProperty, rules);instance.ApplyWorkflowChanges(changes);

}

Externalizing Rules Approach 3Write a custom loader

workflowRuntime.AddService(new CustomLoader());class CustomLoader : DefaultWorkflowLoaderService{ protected override Activity CreateInstance(Type workflowType) { Activity workflow = base.CreateInstance(workflowType); WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer(); XmlTextReader reader = new XmlTextReader("..\\RealRules.rules"); RuleDefinitions rules = serializer.Deserialize(reader) as RuleDefinitions; workflow.SetValue(RuleDefinitions.RuleDefinitionsProperty, rules); return workflow; }}

Externalizing Rules Approach 4Create rules service

RuleSet Designer

RuleSet Repository

Host

RuleSet Service

Workflow1 Workflow2 Workflow3CustomPolicy

Activity

CustomPolicy

Activity

CustomPolicy

Activity

Externalizing Rules

Option 1: Explicit Pattern

Option2: Custom Loader

Option 3: WorkflowChanges

Option 4:CreateWF overload

Outside WF

YES NO NO NO

When are the rules loaded?

When policy activity executes

When WF is loaded (initial, re-hydrated)

When DynamicUpdates are made

When instance is created

Workflows with code-beside

YES YES YES NO

Key APIs

RuleSetDialog ruleSetDialog = new RuleSetDialog(targetType, ruleSet);DialogResult result = ruleSetDialog.ShowDialog();RuleSet newRuleSet = ruleSetDialog.RuleSet;

Host RuleSet Editor

WorkflowMarkupSerializer.Serialize(XmlWriter writer, object obj);

Serialize Workflow

Add RuleSetService to WorkflowRuntime

WorkflowRuntime.AddService(new RuleSetService());

Key APIs

RuleValidation validation = new RuleValidation(targetObject.GetType(), null);

RuleExecution execution = new RuleExecution(validation, targetObject, null);

ruleSet.Execute(execution);

Execute RuleSet

ValidationErrorsCollection errors = validation.Errors;

Validation Errors

External Rule Execution

demo

Rule Chaining

Rulesets can get very big, (10,000+ rules)The rules engine tracks changes (side effects) of rule execution to enable rule re-executionWe have fine grained control over execution

PriorityChaining mechanisms

ImplicitExplicit“Partially Explicit”

Amount = $25 Total = $80Discount = 10%

Forward Chaining Example

Rule 1 (P0)If Total > $50 & < $100 Then Discount = 10%Rule 2 (P0)If Total >= $100Then Discount = 15%Rule 3 (P0)If Amount > $0Then Total = Total + Amount

Rule 1Rule 3 Rule 2

Execution Sequence

$105

RuleSet

15%

Rule Attributes

Declaratively decorate methods in a class to allow rule engine to infer chaining behavior[RuleRead(path)]

Indicate decorated method relies on variable in path

[RuleWrite(path)]Indicate decorated method updates variable in path

[RuleInvoke(methodName)]Indicate decorated method calls another method which updates a variable

Collection Processing

Rule 1 (Priority =2)If 1==1Then

this.enumerator = this.collection.GetEnumerator()

Rule 2 (Priority = 1)If this.enumerator.MoveNext()Then

this.currentInstance = this.enumerator.Current

Rules 3 – n (Priority = 0)// write these against currentInstance

Rule n+1 (Priority = -1)If this.currentInstance == this.currentInstanceThen

Update(this/enumerator)

Collection Processing

demo

RULES EXTENSIBILITY

Custom Rules Authoring UI ExampleBusiness Language Rules

InRuleTM for Windows® Workflow Foundation

InRuleTM for Windows® Workflow Foundation

Custom Rules Authoring UI ExampleDecision Table

Using the Rules Object ModelRule Conditions Object Model

RuleCondition

1

*

Activity

ActivityCondition

RuleConditionReference

-ConditionName

*

-Name *11

RuleDefinitions

RuleDefinitionsRuleSet 1

*

Rule

1*RuleSetReference - RuleSetName

*

-Name

1

Activity

11

RuleCondition

RuleExpressionCondition

CodeExpression

RuleAction

RuleStatementAction RuleHaltAction RuleUpdateAction

CodeStatement

Using the Rules Object ModelRules Object Model

Supported CodeDom TypesCodeArrayIndexerExpressionCodeAssignStatementCodeBinaryOperatorExpressionCodeCastExpressionCodeDirectionExpressionCodeExpressionStatementCodeFieldReferenceExpressionCodeIndexerExpression

CodeMethodInvokeExpressionCodeMethodReferenceExpressionCodePrimitiveExpressionCodePropertyReferenceExpressionCodeThisReferenceExpressionCodeTypeReferenceCodeTypeReferenceExpressionCodeObjectCreateExpression*

CodeArrayCreateExpression*

* New in NETFX 3.5

Using the Rules Object Model

demo

Custom Expression and Actions

Re-use/share commonly used expressions and actionsChoose text representation in the Rules editorCan participate in RuleSet validation and raise errorsCan participate in the forward chaining analysisAccess to ActivityExecutionContext (access to the running activities, host services, etc.)Raises the authoring semantic

Rule Expression Key APIs

Derives from CodeExpressionImplements IRuleExpression

public interface IRuleExpression

{

void AnalyzeUsage(RuleAnalysis analysis, bool isRead, bool isWritten, RulePathQualifier qualifier);

CodeExpression Clone();

void Decompile(StringBuilder stringBuilder, CodeExpression parentExpression);

RuleExpressionResult Evaluate(RuleExecution execution);

bool Match(CodeExpression expression);

RuleExpressionInfo Validate(RuleValidation validation, bool isWritten);

}

Rule Actions Key APIs

Derives from RuleAction

[Serializable]

public abstract class RuleAction

{

public abstract RuleAction Clone();

public abstract void Execute(RuleExecution context);

public abstract ICollection<string> GetSideEffects(RuleValidation validation);

public abstract bool Validate(RuleValidation validator);

}

Custom Rule Expressions and Actions

demo

Execute Activity Custom Rule Action

Given a rule action has access to ActivityExecutionInstance, we could schedule an activity to executeGain the ability to model rule actions as activities (or a sequence of activities)Lose the ability to react to side effects from activity execution (chaining), but could re-run ruleset

Using Rules to Drive Workflow

demo

Summary

Rules are an easy way to add flexible logic to your processRules can be used stand-alone by any .NET applicationManagement and tooling can be built on top of the rule API’sCustom actions and expressions make it easier to expose functionality to ruleset designers

Evaluation Forms

Questions?

© 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.

The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after

the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

top related