Share via


Creating Custom Validation Rules for Visio Premium 2010

Summary:  Learn how to use the Microsoft Visio Premium 2010 Diagram Validation feature to detect errors in your diagrams. Visio Premium 2010 provides built-in validation for a number of templates, or you can develop complex validation rules for a custom solution.

Applies to: Office 2010 | SharePoint Server 2010 | Visio 2010 | Visio Premium 2010

In this article
Overview of Diagram Validation
Diagram Validation Terminology: Rule Sets, Rules, and Issues
Validating a Diagram by Using the User Interface
Importing Rule Sets by Using the User Interface
Working with the Issues Window by Using the User Interface
Removing Diagram Validation Information by Using the User Interface
Using Diagram Validation in a Custom Solution
Overview of the Diagram Validation API
Using the API to Manipulate the Issues Window
Using the API to Validate a Diagram
How Visio 2010 Manages Validation Issues
Defining Filter and Test Expressions
Filter and Test Expression Examples
Filter and Test Expression Performance
Diagram Validation XML
Conclusion
Additional Resources

Published:  June 2010

Provided by:  Stephanie Horn, Microsoft Corporation

Contents

  • Overview of Diagram Validation

  • Diagram Validation Terminology: Rule Sets, Rules, and Issues

  • Validating a Diagram by Using the User Interface

  • Importing Rule Sets by Using the User Interface

  • Working with the Issues Window by Using the User Interface

  • Removing Diagram Validation Information by Using the User Interface

  • Using Diagram Validation in a Custom Solution

  • Overview of the Diagram Validation API

  • Using the API to Manipulate the Issues Window

  • Using the API to Validate a Diagram

  • How Visio 2010 Manages Validation Issues

  • Defining Filter and Test Expressions

  • Diagram Validation XML

  • Conclusion

  • Additional Resources

Overview of Diagram Validation

Microsoft Visio Premium 2010 provides a new way for users to check their diagrams to detect common errors and for companies to ensure that employees are following certain diagramming standards. By using the new Diagram Validation feature, you can have Visio verify properties of a diagram and display diagramming issues. By interacting with the displayed issues, you can easily review and fix problems with your diagram.

Note

The Diagram Validation feature is available only in Visio Premium 2010.

By providing a way to automatically verify a diagram, Visio reduces the amount of time you must spend manually reviewing diagrams for errors. For example, Visio can detect issues such as shapes that are not labeled or connectors that are not glued to other shapes. Visio also enables companies to enforce a standardized notation, such as Business Process Modeling Notation (BPMN), within their organizations to ensure that diagrams are drawn in a consistent manner. By using the Diagram Validation feature, you can check the correctness of a diagram against any organization’s business rules.

Visio Premium 2010 provides Diagram Validation support for the Basic Flowchart, Cross-Functional Flowchart, Six Sigma, Microsoft SharePoint Workflow, and BPMN diagrams. Using the Visio user interface (UI), you can easily validate these types of diagram against the provided validation rules. Visio also provides an extensive Diagram Validation API that you can use to implement Diagram Validation support for any diagram type. This support allows companies to develop custom validation rules and functionality to meet their own needs.

Diagram Validation Terminology: Rule Sets, Rules, and Issues

A validation rule, or simply a rule, represents one condition that a diagram should satisfy. Each rule has some underlying business logic that determines whether this condition has been met. An issue is one case in a diagram where the rule has not been satisfied. Depending on your diagram, you may find multiple issues that are associated with the same rule. For example, if the rule requires that all shapes be labeled, the Diagram Validation feature displays an issue for each shape that has no label.

Rule sets are logical groupings of rules, such as the BPMN and flowchart rule sets. To see which rule sets are available in your current diagram, on the Process tab, click the arrow next to Check Diagram and then click Rules to Check, as shown in Figure 1. Rule sets that have a check mark next to them are active—only rules from active rule sets are evaluated during Diagram Validation. Clicking a rule set will switch it between active and inactive.

Figure 1. Rule sets in a diagram

Rule sets in a diagram

Basic Flowchart, Cross-Functional Flowchart, Six Sigma, Microsoft SharePoint Workflow, and BPMN diagrams created in Visio 2010 already contain an appropriate rule set, and corresponding rules, for the particular diagram type.

Validating a Diagram by Using the User Interface

You can access the Diagram Validation functionality from the Process tab in Visio Premium 2010. While you are working on a diagram that has an active rule set, click Check Diagram, as shown in Figure 2, to see whether the diagram has any issues.

Figure 2. Process tab

Process tab

Visio will either notify you that there are no issues in the diagram or list the issues in the Issues window. Figure 3 shows a basic flowchart diagram in which a connector is not attached to the next shape in the flowchart. When you click Check Diagram, Visio displays two issues associated with the diagram. You can click an issue in the Issues window to navigate to the page or shape associated with the issue.

Figure 3. Validation Issues window

Validation Issues window

Once you fix the listed issues, you can click Check Diagram again to confirm that there are no longer any issues associated with the diagram.

Sometimes you may find that an issue does not apply to a certain shape in your diagram. When this happens, you can ignore the issue and Visio will not display it in the Issues window. If a rule does not apply to the entire diagram, you can also ignore the rule so that no issues associated with the rule are displayed. As shown in Figure 4, you can do this by right-clicking an issue in the Issues window and selecting the appropriate option.

Figure 4. Ignoring a validation issue

Ignoring a validation issue

When a rule set is evaluated during Diagram Validation, ignored rules are still checked and issues associated with these rules are still detected. By default, however, ignored issues and issues associated with ignored rules are not visible in the Issues window. Using the menu shown in Figure 4, you can choose to display the ignored issues or stop ignoring a rule or issue. You can also use this menu to rearrange issues in the Issues window so that issues are sorted by rule, category, or page.

Importing Rule Sets by Using the User Interface

Using the Visio UI, you can import the flowchart rule set into any diagram and transfer any rule set from one diagram to another. The ability to import rule sets into a diagram is particularly useful when you are working with diagrams created by using previous versions of Visio because, by default, these diagrams do not have validation rules. If you create a diagram in Visio 2010 from the Basic Flowchart, Cross-Functional Flowchart, Six Sigma, Microsoft SharePoint Workflow, or BPMN template, you already have the appropriate rule set in your diagram and do not need to import rule sets.

To import the flowchart rule set into any flowchart diagram, first open the diagram in Visio Premium 2010. Then, on the Process tab, click the arrow next to Check Diagram, click Import Rules From, and then click Flowchart Rule Set, as shown in Figure 5. The flowchart rule set is always listed as a rule set that can be imported into your diagram.

Figure 5. Importing rules into a diagram

Importing rules into a diagram

To import rule sets from another diagram, first ensure that this diagram in open in Visio. Then, on the Process tab, click the arrow next to Check Diagram, click Import Rules From, and then select the name of the open diagram that contains the rule sets to import.

Working with the Issues Window by Using the User Interface

If you save a diagram that has issues, these issues are saved with your diagram and are available when you open the diagram again. Validation issues also stay in the diagram if the Issues window is closed. This allows you to fix issues with your diagram over time without having to rerun Diagram Validation.

As shown in Figure 6, there is a check box on the Process tab that controls the visibility of the Issues window. This can be useful, for example, if you want to close the Issues window when showing the diagram to others, and then open it again later to fix any remaining issues in your diagram.

Figure 6. Check box to control the visibility of the Issues window

Check box to show the Issues window

Removing Diagram Validation Information by Using the User Interface

Because issues are saved in your diagram, whoever opens the diagram can view the issues by clicking the Process tab and then selecting the Issues Window check box. The Issues window opens with the saved issues. You can remove saved issues from your diagram along with other personal information by using the following steps.

To remove saved issues and other personal information from your diagram

  1. Click the File tab.

  2. Click Info, and then click Remove Personal Information.

  3. On the Personal Information tab, select Remove these items from the document.

Rule sets and rules are also stored as part of your diagram. You can remove inactive rule sets from a diagram to reduce the file size before sharing it. This also prevents others from using these rule sets to validate your diagram. You should remove rule sets only from a final document, because this removal is permanent.

Before you remove a rule set from your diagram, you must mark it as inactive.

To mark a rule set as inactive

  1. On the Process tab, click the arrow next to Check Diagram.

  2. Click Rules to Check.

  3. If the rule set has a check mark next to it, click the rule to make it inactive.

Once the rule set that you want to remove is inactive, you can remove it as follows.

To remove a rule set

  1. Click the File tab.

  2. Click Info, and then click Reduce File Size.

  3. Select Remove inactive validation rule sets.

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 by using 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 use 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 to store your validation rules and their associated validation logic in a custom Visio template, or write your validation logic as part of solution code. This section discusses 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 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 that they would with 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. 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 Validation.

  • 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

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

Figure 7. Key Diagram Validation objects, methods, and properties

Key Diagram Validation objects and members

You can find the complete set of Diagram Validation objects, methods, and properties in the Visio 2010 Automation Reference.

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

ValidationRuleSet Object

Every rule set has a unique NameU property, which is set when the rule set is created and represents its universal name. The Name and Description rule set property values are displayed in the UI. The Name value 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 the same value as NameU. The Description value appears as a tooltip 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 value for each rule set.

Figure 8. Tooltip that contains the rule set description

Tooltip that contains the rule set description

The other ValidationRuleSet properties have default initial values; you need to 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

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

Enabled

Determines whether the rule set is active or inactive. Only rules that belong 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:

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

  2. Click a rule set name to switch the enabled state for that rule set.

Name

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

NameU

Specifies the universal name of the rule set.

Rules

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

RuleSetFlags

Determines whether the rule set appears in the UI. By default, rule sets are visible in 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 value for each rule, because these property values are displayed in the Issues window. The Category value should inform the user about the type of issue and may be used to identify the rule set that triggered the issue. The Description value 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, TargetType, and TestExpression properties are fundamental for detecting issues during validation. If you decide to write validation logic in solution code, do not set these property values. The FilterExpression, TargetType, and TestExpression properties are described in more detail in the section Defining Filter and Test Expressions.

Table 3 shows the key properties of the ValidationRule object.

Table 3. Key ValidationRule properties

Property

Description

Category

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

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

Ignored

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

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

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

  • 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

Specifies the universal name of the rule.

RuleSet

Returns the rule set that contains the rule.

TargetType

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

TestExpression

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

ValidationIssue Object

Every issue has an associated Rule property that specifies the description and category that is displayed in Issues window. When a user clicks an issue in the Issues window, Visio navigates to the page of the issue (if the issue targets a page or shape) and selects 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.

Table 4 shows the key properties of the ValidationIssue object.

Table 4. Key ValidationIssue properties

Property

Description

Ignored

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

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

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

  • 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

Specifies the rule that generated the issue.

TargetPage

Specifies the page that is associated with the issue.

TargetPageID

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

TargetShape

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 must 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, you can prepopulate rules in a template and then deploy the template 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 use these rules and run validation.

For each of these diagram validation methods, Table 5 shows a brief description of the method, along with an explanation of the method’s parameters.

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

Method

Method description

Parameter

Parameter description

ValidationRuleSets.Add (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 (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 manages issues associated with the rule for you. For very complex validation rules, it is 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 by using this method is limited only by your 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 parameters.

Table 6. Key Methods for managing issues

Method

Method description

Parameter

Parameter description

ValidationRule.AddIssue ([TargetPage],[TargetShape])

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.

  • The shape that has the issue.

ValidationIssue.Delete ()

Deletes the ValidationIssue object from the document.

Once you detect the RuleSetValidated event for your rule set, you should delete the issues associated with your rule set, reevaluate your validation logic, and then add new issues, as necessary. The following VBA code iterates 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.

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.

' 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, because 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 by using the API.

The following VBA code 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.

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 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 that has keyboard focus or, if no issue has keyboard focus, the first selected issue.

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 method validates a particular validation rule set (if specified) and updates the Validation.LastValidatedDate property. It also triggers the RuleSetValidated events associated with the rule sets validated. Table 7 shows details of the Validation.Validate method.

Table 7. Details of the Validation.Validate method

Method

Method description

Parameter

Parameter description

Validation.Validate ([RuleSetAsValidationRuleSet], [FlagsAsVisValidationFlags])

Validates the specified validation rule set.

  • RuleSet (Optional)

  • Flags (Optional)

  • The rule set to validate across the entire document.

  • Indicates whether to open the Issues window after validation.

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

' Validate the document.
Call Visio.ActiveDocument.Validation.Validate(,Visio.VisValidationFlags.visValidationDefault)

Note

When you develop a solution by 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 the information in the following section and how this might affect your validation results.

How Visio 2010 Manages Validation Issues

For performance reasons, Visio 2010 optimizes the number of 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 reevaluates only 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. For 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. If validation was triggered by 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, because its ID may have changed.

Important

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:

  • Managing issues associated with a rule set in solution code.

  • Calling Validation.Validate with a rule set as a parameter.

  • Creating rules that target the document.

These circumstances are described in more detail in the following sections.

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, you should 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 Using 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 by 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 you validate only a subset of the active rule sets:

  1. 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.

  2. 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 have only one active rule set. If you want to validate more than one rule set, leave the rule set parameter empty.

  3. 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.

These steps 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, the target type of this rule should 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 reevaluated only 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. Because 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, you should 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 can 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 automatically uses 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 strings 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 property values 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 value for a validation rule that has 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 you 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 is not 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 expressions, 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 that indicates 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 that indicates whether the shape is a member of the specified layer.

If called on a page, returns a Boolean that indicates whether the layer exists on the page.

If called on a document, returns #REF!.

CONNECTEDSHAPES(Direction)

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

GLUEDSHAPES(Direction)

Returns the set of shapes, matching the Direction criteria, that are 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 that have side effects. The following functions perform actions when evaluated: CALLTHIS, DOOLEVERB, DEFAULTEVENT, DOCMD, GOTOPAGE, HELP, HYPERLINK, OPENFILE, GROUPWIN, OPENPAGE, OPENSHEETWIN, OPENTEXTWIN, PLAYSOUND, RUNADDON, RUNADDONWARGS, MACRO, and SETF. Because you cannot predict the context in which validation is 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 you work with functions that involve 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 the following.

    "AND(AGGCOUNT(GLUEDSHAPES(4)) = 1, AGGCOUNT(GLUEDSHAPES(5)) = 1)"

This example uses the filter expression to filter out all shapes that are not connectors. The test expression checks that there is exactly one 2-D shape glued to the incoming connection point and one 2-D shape glued to the outgoing connection point.

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

  1. Pick your target type as pages: Visio.VisRuleTargets.visRuleTargetPage.

  2. To limit your search to pages that have swim lanes, set your filter expression to the following.

    "AGGCOUNT(FILTERSET(SHAPESONPAGE(),"HASCATEGORY(""Swimlane"")"))>0"

  3. To ensure that all flowchart shapes belong to a swim lane, 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 that have 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 swim lane. A flowchart shape is defined as a shape that either belongs to the Flowchart layer or has the category "Flowchart". The test expression looks at all shapes on the page and asks the following two questions for each shape:

  1. Is the shape a flowchart shape?

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

It then sums the number of shapes that answer "yes" to both these questions. If the sum is non-zero, the example has detected at least one flowchart shape that is not in a swim lane.

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 semicolons. By default, cross functional flowcharts (CFFs) belong to the "CFF Container" category, and individual swim lanes 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 function calculates the set of all shapes on the page, a computation that 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 in the number of shapes on the page.

When in doubt, you should 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

Validation XML from the Basic Flowchart template

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 that includes 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 whether there are issues.

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

XML from Microsoft SharePoint Workflow template

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

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. Using this feature, you can easily detect and display diagramming issues specified by validation rule sets. Because 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: