Skip Ribbon Commands Skip to main content
 
     
Rating: 5/5 (2 votes cast)
Creating custom validation rules for Visio 2010
Learn how to extend the diagram validation feature in Microsoft Visio Premium 2010. This white paper discusses how to create your own validation rules and include your validation rules in a custom solution. For example, you could build rules to check that network diagrams include mandatory components, that process diagrams comply with company policies, or that workflows in Microsoft SharePoint Workflow diagrams are structured correctly.

Read the white paper online.

Expand +
 

Using Diagram Validation in a Custom Solution

Although Visio 2010 provides Diagram Validation support for certain diagram types, there are many opportunities for creating custom validation rules. For example, you can build rules to check that a network diagram includes mandatory components or that a process diagram complies with company policies. A large number of Visio diagrams have some inherent structure to them, and certain ways of assembling shapes on the page simply do not make sense. Solution providers can now enhance their offerings by supporting the ability to verify that a diagram created with their solution is correct.

The ability to verify the correctness of a diagram and raise issues to end-users is also crucial for solutions that need a certain diagram structure to work. For example, Visio uses validation for Microsoft SharePoint Workflow diagrams to ensure that SharePoint workflows are structured correctly before exporting them. As a developer, you can leverage Diagram Validation to support diagram verification for the diagram types and issues that are important to you.

Options for creating custom rules

There are two approaches that you can use for creating custom validation rules. Before you start creating new rules, you should decide whether you are going store your validation rules and their associated validation logic in a custom Visio template, or write your validation logic as part of solution code. Below, we discuss each option in more detail.

When validation rules and their associated validation logic are stored in a Visio template, these rules are automatically available to Microsoft Visio Premium 2010 users who create or edit a diagram based on this template. When a user clicks Check Diagram on the Process tab, Visio uses the validation logic provided to determine whether the diagram has issues. In Visio 2010, this technique is used for the Basic Flowchart, Cross Functional Flowchart, Six Sigma and Business Process Modeling Notation templates.

When validation logic is written in solution code, the logic is deployed as part of a solution. For this approach, Visio notifies the solution when validation is triggered and the solution uses its own logic to determine the list of issues. Visio displays, in the Issues window, the validation issues added by your solution, and end users work with your issues in the same manner as issues created by validation logic stored in a template. As the solution provider, you can write code as complex as necessary to determine whether there are problems in a diagram. You are also responsible for adding and deleting the validation issues related to your rules. In Visio 2010, this technique is used for the Microsoft SharePoint Workflow template.

Each approach is designed to provide particular functionality, so it is worthwhile evaluating the options based on the behavior you want to offer. Table 1 provides a list of the key differences between the two approaches.

Table 1: Approaches for Creating Custom Validation Rules

Approach

Key differentiators

Store your validation rules and their validation logic in a Visio template

· The rules are stored in a Visio template. Microsoft Visio Premium 2010 users can use your rules to validate any diagram created from this template. These users can also transfer your rule set into another diagram by using the method described in the section Importing Rule Sets by Using the User Interface.

· No Visio add-in, add-on or macro is needed for Diagram alidation.

· The complexity of the rules is limited by the supported validation expression logic.

Write custom code to express your validation logic

· A user must have your Add-In, Add-On or VBA code to run Diagram Validation on your rules.

· Very complex rules can be expressed in code.


Overview of the Diagram Validation API overview

Figure 7 shows the key objects, methods and properties for Diagram Validation.

Figure 7: Key Diagram Validation Objects, Methods and Properties

Description: Validation API

You can find the complete set of Diagram Validation objects, methods and properties can be found in the Visio 2010 Automation Reference [ http://msdn.microsoft.com/en-us/library/ee861526.aspx ].

Rules sets, rules and issues each have corresponding API objects, namely ValidationRuleSet, ValidationRule and ValidationIssue. Below we explain the key properties for each of these objects.


ValidationRuleSet

Every rule set has a unique NameU [ http://msdn.microsoft.com/en-us/library/ff768711.aspx ] property, which is set when the rule set is created and represents its universal name. The Name [ http://msdn.microsoft.com/en-us/library/ff766262.aspx ] and Description [ htttp://msdn.microsoft.com/en-us/library/ff766713.aspx ] rule set properties displayed in the UI. The Name appears when a user clicks the arrow next to Check Diagram on the Process tab, and then clicks Rules to Check. By default, Name is set to NameU. The Description appears as a tool tip when a user clicks the arrow next to Check Diagram on the Process tab, clicks Rules to Check, and then moves the mouse over a rule set. You should specify a Description for each rule set.

Figure 8: Tooltip that contains the rule set description

The other ValidationRuleSet properties have default initial values; and only need to be modify them only if you want a different behavior. Table 2 shows the key properties of the ValidationRuleSet object.

Table 2: Key ValidationRuleSet Properties

Property

Description

Description[http://msdn.microsoft.com/en-us/library/ff766713.aspx ]

Specifies the description of the rule set and appears in the UI as a tooltip.

Enabled[ http://msdn.microsoft.com/en-us/library/ff765542.aspx ]

Determines whether the rule set is active or inactive. Only rules belonging to active rule sets are checked when Diagram Validation is triggered. By default, rule sets are enabled, or active.

You can modify this property in the UI as follows:

· On the Process tab, in the Diagram Validation group, click the arrow next to Check Diagram and then click Rules to Check.

· Click on a rule set name to toggle the enabled state for that rule set.

Name[ http://msdn.microsof`t.com/en-us/library/ff766262aspx ]

Specifies the name of the rule set that appears in the UI. By default, it is the same as NameU.

NameU[ http://msdn.microsoft.com/en-us/library/ff768711.aspx ]

Specifies the universal name of the rule set.

Rules[ http://msdn.micrsoft.com/en-us/library/ff7670006.aspx ]

Specifies the collection of rules in the rule set. You can access the rules associated with a rule set using this collection.

RuleSetFlags[ http://msdn.microsoft.com/en-us/library/ff769184.aspx ]

Determines whether the rule set appears in the UI. By default, rule sets are visible through the UI.


ValidationRule Object

Every rule has a unique NameU property which is set when a new rule set is created, and represents its universal name. You should also specify a Category and Description for each rule, as these properties are displayed in the Issues window. The Category should inform the user about the type of issue and may be used to identify the rule set that triggered the issue. The Description should be explicit enough to explain the issue identified by the rule so that a user knows how to address the problem.

If you decide to store validation logic in a Visio template, the FilterExpression, TestExpression and TargetType are the fundamental properties for detecting issues during validation. If you decide to write validation logic in solution code, these fields should be left blank. The FilterExpression, TargetType and TestExpression properties are described in more detail in the section titled "Defining filter and test expressions".

The key properties of the ValidationRule object are shown in Figure 11.

Figure 11: Key ValidationRule Properties

Property

Description

Category[ http://msdn.microsoft.com/en-us/library/ff765754.aspx ]

Represents the text displayed in the Category column of the Issues window.

Description

Specifies the description of the rule that appears in the Issues window.

FilterExpression [ http://msdn.microsoft.com/en-us/library/ff768069.aspx ]

Specifies the logical expression that determines whether the validation rule should be applied to a target object.

Ignored [ http://msdn.microsoft.com/en-us/library/ff768827.aspx ]

Determines whether the validation rule is currently ignored. By default, rules are not ignored.

This property can be changed through the UI as follows.

1. In the Issues window, right-click on an issue associated with the rule, and then click Ignore Rule or Stop Ignoring Rule.

2. On the Process tab, in the Diagram Validation group, click the arrow next to Ignore This Issue and then click Ignore Rule or Stop Ignoring Rule.

NameU [ http://msdn.microsoft.com/en-us/library/ff768899.aspx ]

Specifies the universal name of the rule.

RuleSet [ http://msdn.microsoft.com/en-us/library/ff765052.aspx ]

Returns the rule set that contains the rule.

TargetType [ http://msdn.microsoft.com/en-us/library/ff767157.aspx ]

Determines the target type of the rule. A rule can target documents, pages, or shapes.

TestExpression [ http://msdn.microsoft.com/en-us/library/ff765244.aspx ]

Specifies the logical expression that determines whether the target object satisfies the rule.


ValidationIssue Object

Every issue has an associated Rule [ http://msdn.microsoft.com/en-us/library/ff766058.aspx ] which specifies the description and category that is displayed in Issues window. When a user clicks on an issue in the Issues window, Visio will navigate to the page of the issue (if the issue targets a page or shape) and will select the target shape (if the issue targets a shape). The TargetPage, TargetPageID and TargetShape properties are used determine the page to display and the shape to select.

The key properties of the ValidationIssue object are shown in Figure 12.

Figure 12: Key ValidationIssue properties

Property

Description

Ignored [ http://msdn.microsoft.com/en-us/library/ff768929.aspx ]

Determines whether the issue is currently ignored. By default, issues are not ignored.

You can use the UI to modify this property, as follows:

1. In the Issues window, right-click on an issue associated with the rule, and then click Ignore This Issue or Stop Ignoring This Issue.

2. On the Process tab, in the Diagram Validation group, click the arrow next to Ignore This Issue and then click Ignore This Issue or Stop Ignoring This Issue.

Rule [ http://msdn.microsoft.com/en-us/library/ff766058 ]

Specifies the rule that generated the issue.

TargetPage [ http://msdn.microsoft.com/en-us/library/ff765826.aspx ]

Specifies the page that is associated with the issue.

TargetPageID [ http://msdn.microsoft.com/en-us/library/ff765826.aspx ]

Specifies the ID of the page that is associated with the issue.

TargetShape [ http://msdn.microsoft.com/en-us/library/ff767459.aspx ]

Specifies the shape that is associated with the issue.


Diagram Validation methods for adding rule sets and rules

If you create your own validation rules, you need to add these rules to a Visio file. The Visio API provides an easy way to add rule sets and rules, and set the properties associated with them. Typically, these methods are executed once to populate a template or diagram with validation rules. In fact, rules can be pre-populated in a template, and then the template can be deployed to end-users without any solution code. If you are deploying solution code, you can also decide to populate the user’s current document with your rules when the user first wants to run validation using these rules.

For each of these diagram validation methods, Table 5 shows a brief description of the methods parameters.

Table 5. Diagram Validation methods for adding rule sets and rules.

Method

Method Description

Parameter

Parameter Description

ValidationRuleSets.Add

[ http://msdn.microsoft.com/en-us/library/ff766785.aspx ] (NameU)

Adds a new, empty ValidationRuleSet object to the ValidationRuleSets collection of the document.

NameU

The universal name to assign to the new validation rule set.

ValidationRules.Add

[ http://msdn.microsoft.com/en-us/library/ff765351.aspx ] (NameU)

Adds a new, empty ValidationRule object to the ValidationRules collection of the document.

NameU

The universal name to assign to the new validation rule.


The following Visual Basic for Applications (VBA) code adds a rule set and a rule that targets a shape to the active document.

Set vsoDocument = Visio.Activedocument

'Add a validation rule set to the document

Set vsoValidationRuleSet = vsoDocument.Validation.RuleSets.Add("Connectivity")

vsoValidationRuleSet.Description = "Verify that shapes are correctly connected in the document."

vsoValidationRuleSet.Enabled = True

vsoValidationRuleSet.RuleSetFlags = Visio.VisRuleSetFlags.visRuleSetDefault

'Add a validation rule to the document

Set vsoValidationRule = vsoValidationRuleSet.Rules.Add("Unglued2DShape")

vsoValidationRule.Category = "Shapes"

vsoValidationRule.Description = "This 2-dimensional shape is not connected to any other shape."

vsoValidationRule.Ignored = False

vsoValidationRule.TargetType = Visio.VisRuleTargets.visRuleTargetShape

'The validation function Is1D() returns a Boolean value indicating whether the shape is

'1D (True) or 2D (False)

vsoValidationRule.FilterExpression = "NOT(Is1D())"

'The validation function GLUEDSHAPES returns a set of shapes glued to the shape.

'It takes as input one parameter indicating the direction of the glue.

'The direction values are equivalent to members of VisGluedShapesFlags:

'0 = visGluedShapesAll1D and 3 = visGluedShapesAll2D

'The validation function AGGCOUNT takes a set of shapes as its input, and returns

'the number of shapes in the set.

vsoValidationRule.TestExpression = "AGGCOUNT(GLUEDSHAPES(0)) + AGGCOUNT(GLUEDSHAPES(3)) > 0"


Diagram Validation methods for managing issues

When you set the TargetType, FilterExpression and TestExpression properties of a rule, Visio will manage issues associated with the rule for you. For very complex validation rules, it will be easier to omit these properties and write the validation logic in solution code. For this approach, your solution should listen for the RuleSetValidated event associated with your rule set and use its own logic to determine the list of issues associated with your rule set. The complexity of the rules you can create using this method is only limited by the ability to develop code that can detect the corresponding issues.

There are two key methods for managing issues. Table 6 shows a brief description of each method, along with an explanation of the method's arguments.

 

Table 6. Key Methods for managing issues

 

Method

Method description

Parameter

Parameter description

ValidationRule.AddIssue

[ http://msdn.microsoft.com/en-us/library/ff767586.aspx ]

Creates a new validation issue that is based on the validation rule and adds it to the document.

If you do not pass a value for the optional TargetShape parameter, the validation issue target is the page. If you do not pass values for either of the optional parameters, the validation issue target is the document.

TargetPage(Optional)

TargetShape(Optional)

The page that either has the issue or has the shape with the issue.

ValidationIssue.Delete [ http://msdn.microsoft.com/en-us/library/ff765925.aspx ] ()

Deletes the ValidationIssue object from the document.


Once you detect the RuleSetValidated event for your rule set, we recommend that you delete the issues associated with your rule set, reevaluate your validation logic, and then add new issues as necessary. The following VBA code below traverses through the validation issues in the active document and, for each issue vsoIssue, the code checks whether this issue belongs to rule set vsoValidationRuleSet. The issues that belong to this rule set are deleted. The code assumes that vsoValidationRuleSet is a valid Visio.ValidationRuleSet object.

VBA Copy Code

Set vsoDocument = Visio.ActiveDocument

Set vsoIssues = vsoDocument.Validation.Issues

issueTotal = vsoIssues.Count

issueNumber = 1

'Walk through the validation issues

For curIssue = 1 To issueTotal

Set vsoIssue = vsoDocument.Validation.Issues(issueNumber)

' Delete the issues that belong to the vsoValidationRuleSet rule set

If vsoIssue.Rule.RuleSet Is vsoValidationRuleSet Then

vsoIssue.Delete

Else

issueNumber = issueNumber + 1

End If

Next curIssue

The following VBA code adds an issue, targeting shape vsoShape on page vsoPage, to the existing rule vsoValidationRule. It assumes that vsoValidationRule is a valid Visio.ValidationRule object, vsoShape is a valid Visio.Shape object and vsoPage is a valid Visio.Page object.

VBA Copy Code

'Add a custom issue to the vsoValidationRule validation rule and associate it with

'shape vsoShape on page vsoPage

Set vsoValidationIssue = vsoValidationRule.AddIssue(vsoPage, vsoShape)

When validation is triggered, Visio stores the ValidationIssue.Ignored property for all existing issues. At the end of validation, Visio restores this property for issues that existed when validation was triggered, including those that were deleted and reinserted as part of the validation process. Visio uses an issue’s associated shape, page and rule to determine whether the issue existed before validation, as its ID may have changed. This means that issues you delete and reinsert within the scope of handling the RuleSetValidated event keep their previous ValidationIssue.Ignored values.


Using the API to manipulate the Issues window

As part of Diagram Validation, Visio opens the Issues window if there are issues in the document. The Issues window is opened after the RuleSetValidated events, and issues added by Visio and by custom code are both displayed in the Issues window. If you want to direct users to the Issues window at other times, you can open and close the Issues window using the API.

The VBA code below checks whether there are any validation issues in the active document. If there are validation issues, it opens the Issues window. Otherwise, it closes the Issues window.

VBA Copy Code

Set vsoDocument = Visio.ActiveDocument

Set vsoWindow = vsoDocument.Application.ActiveWindow

'Display the Issues window if there is at least one validation issue

If vsoDocument.Validation.Issues.Count = 0 Then

vsoWindow.Windows.ItemFromID(Visio.VisWinTypes.visWinIDValidationIssues).Visible = False

Else

vsoWindow.Windows.ItemFromID(Visio.VisWinTypes.visWinIDValidationIssues).Visible = True

End If

The following VBA code below determines the issue vsoValidationIssue that is selected in the Issues window. Note that it is possible to select multiple issues. In this case, Visio returns the issue with keyboard focus or, if no issue has keyboard focus, the first selected issue.

VBA Copy Code

Set vsoIssuesWindow = Application.ActiveWindow.Windows.ItemFromID(Visio.VisWinTypes.visWinIDValidationIssues)

'Find the selected issue if the Issues window is visible

If vsoIssuesWindow.Visible Then

Set vsoValidationIssue = vsoIssuesWindow.SelectedValidationIssue

End If

'Check for the case when there are no validation issues selected

If vsoValidationIssue Is Nothing Then

MsgBox "Please select an issue."

End If


Using the API to Validate a Diagram

In your custom solution, you can add your own triggers for Diagram Validation. For example, if you have a custom solution that needs a certain diagram structure to function properly, you can use Diagram Validation to check for this structure and raise issues to the end-user.

The Validation.Validate [ http://msdn.microsoft.com/en-us/library/ff767580.aspx ] method validates a particular validation rule set (if specified) and updates the Validation.LastValidatedDate [ http://msdn.microsoft.com/en-us/library/ff768225.aspx ] property. It will also trigger the RuleSetValidated events associated with the rule sets validated. Table 7 shows the details of the Validation.Validate method.

Method

Method Description

Parameter

Parameter description

Validation.Validate[ http://msdn.microost.com/en-us/library/ff767580.aspx ]

([RuleSet As ValidationRuleSet], [Flags

As ValidationFlags])

Validates the specified validation rule set

RuleSet (Optional)

Flags (Optional):

The rule set to validate across the entire document

Whether to open the Issues window after validation.


The following VBA code validates all rule sets in the document and opens the Issues window.

VBA Copy Code

'Validate the document

Call Visio.Activedocument.Validation.Validate(, Visio.VisValidationFlags.visValidationDefault)

Note: When you develop a solution using the Diagram Validation feature, you should assume that the document has several active rule sets. You should also assume that an end-user may use the UI to change which rule sets are active in the document. Finally, you should be aware of How Visio 2010 manages validation issues and how this might affect your validation results.


How Visio 2010 manages validation issues

For performance reasons, Visio 2010 optimizes the number of the validation rules that are reevaluated when validation is triggered. It records which pages have changed since the last validation, and, when validation is triggered, it only reevaluates rules on pages that have changed. When you reopen a document, modify validation rule sets or rules, or clear all existing issues, Visio marks the entire document as changed: these actions can impact all validation issues in a document, so reevaluation of all rules is necessary. As an example, if you close and reopen a document, it is possible that you made changes to the document outside of Visio 2010 that might change the validation results.

When validation is triggered on a document, Visio performs the following tasks.

1. Visio deletes from the document every issue targeting a page that has been changed, including issues targeting shapes on that page. As Visio deletes these issues, it records the ValidationIssue.Ignored property for each issue.

2. Visio evaluates validation rules against changed pages, and shapes on changed pages. Only active rule sets are used in the validation, and, if validation was triggered using Validation.Validate with a rule set parameter specified, only the specified rule set is used. At this point, if a rule associated with one of these rule sets has validation logic stored in the document, Visio adds any associated issues to the document.

3. The RuleSetValidated event is triggered for these rule sets. Custom solutions listening for the RuleSetValidated event associated with their solution can then manage their validation issues.

4. Visio restores the ValidationIssue.Ignored property of issues that existed when validation was triggered, including those that were deleted and reinserted as part of the validation process. Visio uses the issue’s associated shape, page and rule to determine whether an issue existed before validation, as its ID may have changed.

Important Note: The performance optimizations above imply that validation issues targeting documents and issues targeting pages that have not been changed, including issues targeting shapes on these pages, are not regularly deleted or reevaluated during validation. It is worthwhile considering the implications of this behavior when you are doing one of the following

(1) Managing issues associated with a rule set in solution code,

(2) Calling Validation.Validate with a rule set as a parameter, or

(3) Creating rule sets that target the document.

These circumstances are described below in more detail.

Managing issues associated with a rule set in solution code

If you are using solution code to listen for the RuleSetValidated event and then managing issues based on validation logic written in custom code, Visio will potentially delete some, but not all, of the issues that you are managing before raising the RuleSetValidated event. When you detect the RuleSetValidated event for your rule set, we recommend that you delete the remaining issues associated with your rule set before reevaluating your validation logic and adding new issues. The code for deleting the issues associated with a particular rule set is given in the section “Diagram Validation methods for managing issues”.

Calling Validation.Validate with a rule set as a parameter

The Validation.Validate method allows you to use a rule set parameter to specify a single rule set to evaluate. In most cases, an end-user may have previously triggered validation using all active rules sets. Because Visio reevaluates rules only on pages that have changed since the last validation, you should perform the following steps to ensure that all issues on all pages are updated when validating only a subset of the active rule sets:

i. Traverse through the rule sets in the document, and set the ValidationRuleSet.Enabled property of the rule sets that you want to validate to True. Set the ValidationRuleSet.Enabled property of all other rule sets to False.

ii. Run Validation.Validate. If you want to validate a single rule set, you can specify this rule set as a parameter: specifying the parameter is optional, however, because the document should now only have one active rule set. If you want to validate more than one rule set, you should leave the rule set parameter empty.

iii. After validation is complete, traverse through the rule sets in the document, and set the ValidationRuleSet.Enabled property of every rule set back to its previous value.

The steps above ensure that Visio runs validation on all pages, using only the desired subset of rule sets. The last step also returns the rule sets to their state before you triggered validation.

Creating rules that target the document

If you create a rule that has validation logic stored in a document, we recommend that the target type of this rule be either a shape or a page. When you store validation rules and their associated validation logic in a custom Visio template, rules that target the document are only reevaluated when Visio marks the entire document as changed. This occurs when the document is reopened, the validation rule sets or rules are modified, or all validation issues are cleared. Since these actions are infrequent, a user may correct an issue targeting this type of rule and still see the issue in the Issues window after validation. For this reason, we recommend that you do not create validation rules that target the document unless the logic for the rule is written in solution code. When you manage the validation issues in code, you will be able to reevaluate the validation rule at your discretion.

Defining Filter and Test expressions

When you validate a diagram by calling the Validation.Validate method or by clicking Check Diagram on the Process tab, Visio will automatically use any validation logic stored in the document to detect errors. This validation logic is expressed in the ValidationRule.TargetType, ValidationRule.FilterExpression and ValidationRule.TestExpression properties.

Write the FilterExpression and TestExpression as Boolean expressions that can be evaluated on every object of type TargetType. During the validation of a rule, for every object of the target type, Visio uses the filter expression to determine whether the object must satisfy the rule. If the filter expression evaluates to True, Visio uses the test expression to determine whether to generate an issue for the object. If the filter expression evaluates to False, Visio does not apply the rule to the object. If the test expression evaluates to False, Visio generates a validation issue. If the test expression evaluates to True, no validation issue is generated.

The syntax for the FilterExpression and TestExpression properties are the same as that of a ShapeSheet expression. For example, because

NOT(IS1D())

is a valid Boolean expression for the ShapeSheet of a shape, "NOT(Is1D())" is a valid FilterExpression or TestExpression for a validation rule with TargetType = Visio.VisRuleTargets.visRuleTargetShape.

Note: When you set the FilterExpression and TestExpression properties for a rule, Visio does not check the syntax of these expressions. The FilterExpression and TestExpression properties are evaluated only when your run validation.

During the validation of a rule, for every object of the target type, if the filter expression is not syntactically correct, Visio does not evaluate the test expression and does not apply the rule to the object. If the test expression is not syntactically correct, the evaluation of the expression fails and Visio generates an issue for the object.

One way to generate a syntactically incorrect filter or test expression is to include a ShapeSheet cell in the expression and then apply this expression to a target object that does not contain the cell. Although the same ShapeSheet cell may not exist for every object in a diagram, you may still want to verify the value of this cell in validation logic. The following example demonstrates how you can work with ShapeSheet cells that are not guaranteed to exist for all target objects.

Assume that you want to ensure that the cost of all items is positive, and that the cost is stored in the ShapeSheet cell Prop.Cost. You should decide if the validation rule is broken when an object has no cost, and construct your validation expressions accordingly. If items are not required to have a cost, use Prop.Cost in the filter expression; in this case, the validation rule will not be applied to an item without the cell. For example, set the filter expression to Prop.Cost < 1 and the test expression to False.

If items must have a cost, use Prop.Cost only in the test expression: in this case, Visio generates an issue when the cell is missing. For example, set the filter expression to True and the test expression to Prop.Cost >0. Notice that, if you use Prop.Cost in both the filter and test expression, the validation rule is not applied to an item without the cell, because the filter expression filters out such items.

In addition to the standard ShapeSheet functions, you can use the Diagram Validation functions, shown in Table 8, in a filter or test expression.


Table 8: Specialized Diagram Validation functions

Function

Description

Role()

Returns an integer indicating the shape role:

{Element = 0, Connector = 1, Container = 2, Callout = 4}

If called on a page or document. Returns #REF!

OnLayer(LayerName)

Returns a Boolean indicating whether the shape is a member of the specified layer.

If called on a page, returns a Boolean indicating whether layer exists on page. If called on a document, Returns #REF!.

ConnectedShapes(Direction)

Returns the set of shapes, matching the Direction criteria, connected to the shape.

GluedShapes(Direction)

Returns the set of shapes, matching the Direction criteria, glued to the shape.

ContainerMembers()

Returns the set of shapes that are members of the container or list shape, including members of nested containers.

ListMembers()

Returns the set of shapes that are members of the list shape.

Callouts()

Returns the set of shapes that are callouts on the shape.

ParentContainers()

Returns the set of containers that the shape belongs to.

ShapesOnPage()

Returns the set of top-level shapes on page. If no page specifier precedes the function, the shape’s containing page is assumed.

AggCount(Set)

Counts the number of shapes in a set.

FilterSet(Set,Filterexpression)

Returns the subset of shapes in a set that match an expression.

OnBoundaryOf()

Returns the set of containers such that the shape is on the boundary of these containers.


The Diagram Validation expression functions ConnectedShapes and GluedShapes correspond to Visio API functions that have the same names. Similarly, the possible values of the Direction input parameter for ConnectedShapes and GluedShapes correspond to the VisConnectedShapesFlags and VisGluedShapesFlags enumerations, respectively.

Note: Although all ShapeSheet functions are permitted in validation logic, you should avoid using ShapeSheet functions with side effects. The following functions perform actions when evaluated: CallThis, DoOleVerb, DefaultEvent, DoCmd, GotoPage, Help, Hyperlink, OpenFile, OpenGroupWin, OpenPage, OpenSheetWin, OpenTextWin, PlaySound, RunAddon, RunAddonWArgs, RunMacro, and SetF. Because you cannot predict the context in which validation will be triggered, using functions that perform an action can lead to unexpected results.

As you examine the functions in Table 8, notice that several of the functions return sets of shapes. Also notice that AggCount and FilterSet are the only functions that take a set of shapes as an input. Use the following general strategy when working with functions involving sets:

1. Start with the function that returns a set.

2. If necessary, apply the FilterSet function to filter the set of shapes.

3. Apply the AggCount function to compute the number of elements in the set.

4. Compare the number of elements with an expected size or range of sizes to obtain a Boolean value.

The following section demonstrates this strategy with a pair of examples.


Filter and Test Expression Examples

The following examples of filter and text expressions were taken from the Flowchart rule set, the rule set included in the Visio 2010 Basic Flowchart, Cross Functional Flowchart and Six Sigma templates.

Example 1: You want a validation rule that checks that all connectors are glued at both ends.

1. Pick your target type to be shapes, Visio.VisRuleTargets.visRuleTargetShape.

2. To limit your search to connector shapes, set your filter expression to the following:

ROLE()=1.

3. To verify that a connector is glued at both ends, set your test expression to AND(AGGCOUNT(GLUEDSHAPES(4)) = 1, AGGCOUNT(GLUEDSHAPES(5)) = 1).

In this example, we use the filter expression to filter out all shapes that are not connectors. The test expression checks that there is exactly one 2D shape glued to the incoming connection point, and one 2D shape glued to the outgoing connection point.

Example 2: You want a validation rule that verifies that, on any page with at least one swimlane, all flowchart shapes belong to a swimlane.

1. Pick you target type as pages, Visio.VisRuleTargets.visRuleTargetPage.

2. To limit your search on pages to pages with swimlanes, set your filter expression to the following: AGGCOUNT(FILTERSET(SHAPESONPAGE(),"HASCATEGORY(""Swimlane"")"))>0.

3. To ensure that all flowchart shapes belong to a swimlane, set your test expression to the following: AGGCOUNT(FILTERSET(SHAPESONPAGE(),
"AND(OR(HASCATEGORY(""Flowchart""),ONLAYER(""Flowchart"")),
AGGCOUNT(FILTERSET(PARENTCONTAINERS(),""HASCATEGORY(""""Swimlane"""")""))=0)
"))=0
.

This example uses the filter expression to filter out all pages that do not have at least one Swimlane shape. For every page in the document, the filter expression takes all the shapes on the page and filters out only the shapes with the category “Swimlane”. The pages of interest for this example have at least one shape that meets this criterion.

The test expression checks that all flowchart shapes belong to a swimlane. A flowchart shape is defined as a shape that either belongs to the Flowchart layer or has category “Flowchart”. The test expression looks at all shapes on the page, and asks the following two question for each shape:

1. Is the shape a flowchart shape and

2. Does the shape have zero parent containers that are swimlanes?

It then sums the number of shapes that answer “yes” to both these questions. If the sum is non-zero, we

have detected at least one flowchart shape that is not in a swimlane.

Note: The list of categories that a shape belongs to appears in the User.msvShapeCategories cell in the ShapeSheet for the shape. You can define multiple categories for a shape by separating the categories with semi-colons. By default, cross functional flowcharts (CFFs) belong to the “CFF Container” category and individual swimlanes within a CFF belong to the “Swimlane” category.


Filter and test expression performance

Visio 2010 has implemented a number of optimizations to reduce the time required to validate a diagram, but poorly written rules will still lead to slow performance. Validation rules that have TargetType = Visio.VisRuleTargets.visRuleTargetShape are at most risk of slowing down validation, because they can potentially be evaluated once for every shape in the document.

It is generally unwise to use the SHAPESONPAGE function in a validation rule that targets shapes. The SHAPESONPAGE method calculates the set of all shapes on the page, a computation tht is linear in the number of shapes on the page. If this function is called for every shape on the page, the total computation time is exponential to the number of shapes on the page.

When in doubt, we recommend that you test the validation performance of your rule set against the diagram types intended for use with the rule set. As a guideline, given a particular rule, the validation performance of this rule is based most notably on the number of shapes in the diagram and the number of issues generated.


Diagram Validation XML

The validation rules, rule sets and issues associated with a diagram are stored in the file. You can examine the stored information by saving the file with validation rules as an XML Drawing (*.vdx) and opening the XML Drawing in an XML editor. A search for the keyword validation will lead you to the XML related to Diagram Validation. Figure 9 shows a section of XML for the Flowchart rule set. 


Figure 9: Diagram Validation XML from the Basic Flowchart template

Description: ValidationXML

Notice that each rule in the Flowchart rule set contains a RuleFilter and RuleTest expression. These two rule set expressions correspond to the FilterExpression and TestExpression properties, respectively, of the ValidationRule object in the API. You can see many examples of RuleFilter and RuleTest expressions in the Flowchart and BPMN rule sets, included in the Basic Flowchart and BPMN Visio templates.

If you save a Microsoft SharePoint Workflow diagram as an XML Drawing (*.vdx) and open the XML Drawing in an XML editor, you will see that there is no logic in the RuleFilter and RuleTest expressions. In this case, the solution contains code with the validation logic. The SharePoint Workflow solution listens for the SharePoint Workflow RuleSetValidated event, and, when this event occurs, it scans the diagram to determine if there are issues. 


Figure 10: Diagram Validation XML from the Microsoft SharePoint Workflow template

Description: ValidationXML-2

Although you can modify the Diagram Validation properties directly in the XML, the recommended way to manipulate Diagram Validation properties.

You can find more information about the Visio 2010 XML Schema, including validation elements, in the Visio 2010 XML Schema Reference.

Conclusion


This article describes how to use the Diagram Validation feature available in Microsoft Visio Premium 2010. With this feature, you can easily detect and display diagramming issues specified by validation rule sets. Since most diagrams have some logical structure to them, there are many opportunities to create your own custom validation rule sets and rules and extend the built-in functionality of the Diagram Validation feature. This extensibility allows companies to develop custom validation rules to ensure that certain diagramming standards are met and allows third-party solution providers to expand their solution offerings.


Additional Resources

For more information about Diagram Validation in Visio Premium 2010, see the following resources: