Visio 2010 Developer Training 03 - Programming With the Visio Object Model



Comments



Description

Microsoft Visio 2010 DeveloperTraining Volume 3: Programming with the Visio Object Model 1 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 1 DISCLAIMER © 2010 Microsoft Corporation. All rights reserved. Microsoft®, Internet Explorer, and Windows® are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners. THE CONTENTS OF THIS PACKAGE ARE FOR INFORMATIONAL AND TRAINING PURPOSES ONLY AND ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. No part of the text or software included in this training package may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or any information storage and retrieval system, without permission from Microsoft®. 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 presented after the date of publication. The names of actual companies and products mentioned herein may be the trademarks of their respective owners. To obtain authorization for uses other than those specified above, please visit the Microsoft Copyright Permissions Web page at http://www.microsoft.com/about/legal/permissions This content is proprietary and confidential, and is intended only for users described in the content provided in this document. This content and information is provided to you under a Non-Disclosure Agreement and cannot be distributed. Copying, disclosing all or any portion of the content and/or information included in this document is strictly prohibited. 2 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 2 Table of Contents VBA Primer .................................................................................................................................................. 10 Event Driven vs. Procedure Based Programming ....................................................................................................11 Visual Basic Editor ...................................................................................................................................................12 Variables ..................................................................................................................................................................15 Dimensioning ...........................................................................................................................................................16 Data Types ...............................................................................................................................................................18 Using Hungarian Notation ...................................................................................................................................20 Manipulating Variables............................................................................................................................................21 Exercise 1 .................................................................................................................................................................23 Other Operations.....................................................................................................................................................25 Exercise 2 .................................................................................................................................................................27 Data type conversions and variable scope ..............................................................................................................29 Exercise3 ..................................................................................................................................................................31 Constants .................................................................................................................................................................33 Control structures....................................................................................................................................................34 Branching Statements .........................................................................................................................................34 Looping Statements ............................................................................................................................................36 Jumping Statements ............................................................................................................................................37 Procedures ..........................................................................................................................................................38 Functions .............................................................................................................................................................38 VBA Primer Conclusion ............................................................................................................................................40 Introduction to Automation........................................................................................................................ 41 Introduction.............................................................................................................................................................43 Automation Basics ...................................................................................................................................................44 Programming a Server's Objects .............................................................................................................................46 VBE Tools Menu ......................................................................................................................................................49 Object Browser ........................................................................................................................................................ 3 51 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 3 Review: Introduction to Automation.......................................................................................................................52 Automation and Visio Technology .............................................................................................................. 53 Overview .................................................................................................................................................................54 The Visio Object Model ...........................................................................................................................................55 A Sample Visio Program ..........................................................................................................................................58 Getting and Setting Properties ................................................................................................................................60 Invoking Methods ....................................................................................................................................................62 Compound References ............................................................................................................................................64 Lab 3.1: Get the Name of an Open Visio Document................................................................................................65 Coding Issues ...........................................................................................................................................................66 Running Your Program ............................................................................................................................................68 RUNADDON(“string”) ..............................................................................................................................................70 CALLTHIS ..................................................................................................................................................................72 Where to Find Visio Automation Information .........................................................................................................73 Lab 3.2: Running VB Add-ons ..................................................................................................................................75 Review: Automation and Visio ...............................................................................................................................76 Generating Drawings .................................................................................................................................. 78 Creating a Document ...............................................................................................................................................79 Getting a Reference to the Master ..........................................................................................................................81 Dropping the Master on the Page ...........................................................................................................................82 Adding Text to Shapes .............................................................................................................................................84 Getting Formulas of Shapes and Pages ...................................................................................................................85 Getting a Formula or Its Result ................................................................................................................................87 Setting a Formula ....................................................................................................................................................89 Tips for Positioning Shapes......................................................................................................................................90 Tips for Positioning Shapes (Continued) ..................................................................................................................91 Connecting Shapes ..................................................................................................................................................92 Getting the Cell to Glue ...........................................................................................................................................93 Gluing to the Other Shape .......................................................................................................................................94 4 96 AutoConnect Mode ................................................................................................................................................. Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 4 Adding Data to Shapes ............................................................................................................................................99 Adding Sections and Rows.....................................................................................................................................100 Lab 3.3: "Hello World" ...........................................................................................................................................101 Review: Generating Visio Drawings ......................................................................................................................102 Getting Data From Drawings..................................................................................................................... 104 Overview ...............................................................................................................................................................105 Iterating Through a Collection ...............................................................................................................................106 Getting Data from Documents ..............................................................................................................................108 Noteworthy Document Properties ........................................................................................................................109 Getting Data from Pages .......................................................................................................................................111 Getting Data from Shapes .....................................................................................................................................112 Getting Data About Connections ...........................................................................................................................113 Connect Object for a Control Handle to a Shape ..................................................................................................115 Connect Object for a 1-D Between 2-D Shapes .....................................................................................................116 More Connectivity API options ..............................................................................................................................118 Getting a Selection Object .....................................................................................................................................124 Working with Windows and Selected Shapes .......................................................................................................126 Getting Cells with CellsSRC ....................................................................................................................................128 Determining Shape Proximity ................................................................................................................................130 SpatialRelation.......................................................................................................................................................131 Lab 3.4: Calculate the Area of a Shape ..................................................................................................................132 Review: Getting Data from Drawings ...................................................................................................................133 Managing Events ....................................................................................................................................... 135 Learning Objective .................................................................................................................................................136 Introduction...........................................................................................................................................................137 Cell Dependencies .................................................................................................................................................138 Force Dependencies with DependsOn ..................................................................................................................139 DependsOn Example .............................................................................................................................................140 SetAtRef ShapeSheet Function ..............................................................................................................................142 5 144 Use the ShapeSheet to Manage Events ................................................................................................................. Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 5 Use Formulas Over Code .......................................................................................................................................145 Visual Basic for Applications Code Behind Events .................................................................................................146 Supported Events ..................................................................................................................................................147 Hierarchical Event Sets ..........................................................................................................................................148 Built-In Document Events ......................................................................................................................................149 WithEvents Keyword .............................................................................................................................................151 Controls .................................................................................................................................................................153 Query Events .........................................................................................................................................................155 Query Events (Continued)......................................................................................................................................157 Marker Events .......................................................................................................................................................158 Scoping Methods ...................................................................................................................................................160 Lab 3.5: Create a Shape Area Calculator ...............................................................................................................161 Points to Consider .............................................................................................................................................161 Other Considerations ............................................................................................................................................162 Review: Managing Events .....................................................................................................................................164 Automating Data Graphics ........................................................................................................................ 165 Lesson 1: Data Graphics Concepts .........................................................................................................................167 Overview of Objects / Methods / Properties ....................................................................................................167 Creating Data Graphics Masters ........................................................................................................................170 Creating Data Graphics Items ............................................................................................................................173 Managing Data Graphic Masters .......................................................................................................................195 Lesson 2: Related Topics .......................................................................................................................................198 Shape Data Management ..................................................................................................................................198 Lab 3.6: Data Graphics ...........................................................................................................................................204 Exercise 1: Create a Pie Chart data graphic item ..............................................................................................204 Exercise 2: Test the New Pie Chart data graphic item.......................................................................................207 Exercise 3: Add a data bar to the Data Graphic that totals the 9 th, 10th, 11th, and 12th grade slots for a class section. ..............................................................................................................................................................209 Additional Resources – Data Graphics ..................................................................................................................210 Review: Automating Data Graphics ...................................................................................................................... 6 212 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 6 ................................................................................................................ and manage changes required by the data ................................................................................................................................249 Visio Software Development Kit (SDK) ...275 7 281 Lab 3......................... 251 Lesson 1: Setup / Overview .....................................................230 Linking data to shapes ..........................................................215 Data Sources......................................................................259 Changes from Visio 2010 SDK................................................................................................................247 Review: Managing External Data Sets .............................................................................................................................................................................................................. 214 Lesson 1: Data Link Concepts ........................................................273 Publish Component ..............................242 Lab 3.................................................................................................................................................................................................269 About Using the Persistent Events Tool ............................................. refresh the drawing..................................256 TypeLibs Included ....Managing External Data Sets .......................................................................................................................................................................................................................................................................................................................221 Lesson 2: Managing Data sets ........................................................................................................................................................................................................................................................255 Containers ..............................................................................................................................8: Build and run the Visio SDK Flowchart sample .................. All rights reserved..................................................................................................................267 Event Monitor ...................260 Visual Studio 2005 and 2008 Add-in Wizards.....245 Exercise 3: Drop and link the Section shapes to the rows in the Section DataRecordset ..............................................................................246 Additional Resources – External Data ...............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................215 Overview of Objects / Methods / Properties .........................................................................................................267 Demo: Use Event Monitor to track actions in Visio .............................................................................253 Documentation .............................................................................270 Print ShapeSheet ........................................................................................................................252 Software Requirements for Visio 2010 SDK Tools and Samples .......246 Exercise 4: Change the external data.................245 Exercise 2: Link the Instructor shapes to rows in the Teacher DataRecordset ....................... Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation..........................................260 Lesson 2: Tools .....................................................................................244 Exercise 1: Connect to an external data set .................... Volume 3: Programming with the Visio Object Model 7 .........................................................................................................................................................................................7: Data Linking ........231 Managing Refresh ..............................................237 Changing data locations ........................................... ...................................................................................................................................285 Review: SDK ...........287 Visio Drawing Control ................................................................................................316 Review – Visio Drawing Control .......................................................................................................................................................................314 Exercise 3: Add SaveAs menu ............318 Adding the Office Fluent UI to an existing Add-in ..................................321 8 321 Updating References ...............................................................................................................................................................................................307 Window management ....................315 Additional Resources – Drawing Control .........................................290 Requirements / Containers ..............................................................................................................................................................290 Demo: Drawing Control ..........................................................................304 Loading a document ........................................................................................................................................................ Volume 3: Programming with the Visio Object Model 8 ........................................................................................................................................SDK ............................................................................................................301 Porting existing code ........................................................................8: Using the Visio Drawing Control ........................................................................................................................................................................................................................................................................................ Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation..................................................291 Lesson 2: Creating an application ..........................................................................................................................313 Exercise 1: Set the Src property of the document and display the External Data window ....310 Using the Visio Control with the Internet Explorer Browser Control ....................................................................... .....................................................................................................................................303 Getting a reference to the Visio Application Object ...........................................314 Exercise 2: Add menus to place and delete Sections ...............304 Saving a document .............................................................................................................................................................................................................................305 Integrating the control with the host container..................................................................................Exercise 1: Build and run the Flowchart (VB.................................................................283 Additional Resources ....................................................308 Integrating menus and toolbars .................................................................................................................................301 Best Practices .........................................................................302 The Controls SDI (single document interface) ......................................... 289 Lesson 1: Concepts .....................................................................................................................................................................306 Page sizing and zoom ................................................................................................................................................................312 Lab 3................................................................................. 320 Getting started .............NET) sample code from the SDK ................................................. All rights reserved................309 Handling events .....281 Exercise 2: Code review............................................................................................................................................................................................................................................................... .................................................332 Sample Code.................................... Volume 3: Programming with the Visio Object Model 9 .......................................................................................................................................................................................................................329 CommandBars and Ribbon ...............................................................................................................................333 9 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation....................................................................................................................................Preparing the add-in for Ribbon support ............................................328 Manage Ribbon control state .........................................321 Creating the Ribbon ........................................ All rights reserved.........................................................................................................324 Callbacks ................ Upon completion of this supplement. 10 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved.VBA Primer This supplement is designed to be a primer for programming with Visual Basic and Visual Basic for Applications. Volume 3: Programming with the Visio Object Model 10 . and will use the VBA programming language. you should be familiar with some basic coding concepts such as:          Variables Objects Methods Properties Conditionals Functions and Procedures Visual Basic Editor Environment Events COM – Object Models Examples and exercises will demonstrate basic coding concepts. Event Driven vs. the sequence of operations for an application is determined by a central controlling program (e. in contrast to some other programming languages and architectures that are procedure-based. menus. a small data verification program is executed. buttons. Volume 3: Programming with the Visio Object Model 11 .). and so on. In conventional programming. VB is event-driven. To create an event-driven application. and object-orientation are all related since forms and the graphical interface objects on the forms serve as the skeleton for the entire application. Event-driven programming. rather than having a main procedure that executes an order entry module followed by a data verification module followed by an inventory update module. Procedure Based Programming Visual Basic is a structured programming language derived from the BASIC language. the programmer creates small programs and attaches them to events associated with objects.g. a main procedure). the sequence of operations for an application is determined by the user’s interaction with the application’s interface (forms. when the user indicates that the order entry is complete. Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. In event-driven programming. the inventory update module is executed. For example. graphical user interfaces (GUIs). etc. the behavior of the application is determined by the 11 interaction of a number of small manageable programs rather than one large program. an event-driven application remains in the background until certain events happen: when a value in a field is modified.. All rights reserved. In this way. All rights reserved. You will first notice that there are several windows in the VBE: Project. You can access it from the Tools > Macros menu or by pressing Alt-F11.Visual Basic Editor There are a number of ways to open the Visual Basic Editor. If you do not see these windows. You can also add the Developer toolbar to your Visio user interface to expose the Visual Basic Editor toolbar button. Immediate. and others. Properties. 12 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 12 . Code. go to the View menu to turn them on. Figure 1: The Visual Basic Editor window The Project window displays a hierarchical list of the projects and all of the items contained in and referenced by each of the projects. From the Immediate window you can execute code. 2. you can view and modify design time properties for objects in a project. To execute a line of code. All rights reserved. To view the value of a variable or expression. From the Project window. Volume 3: Programming with the Visio Object Model 13 . Create a Visio drawing with a few shapes and select some or all of them. type: Msgbox "This is my message. Demonstration: Visual Basic Editor 1. place a question mark (?) before the code. enter it into the Immediate window and press the Enter key. In the Immediate window of VBE. This is extremely useful when debugging to view the values of variables and expressions. The code will execute displaying a message box with the text. From the Properties window." Press Enter. It can also be used to set values of variables to test extreme or unusual conditions. you can view the code contained in modules and forms and you can view form objects. Return to the Visual Basic for Applications Editor and in the immediate window type: 13 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. ActiveWindow. Volume 3: Programming with the Visio Object Model 14 . The immediate window returns the number of shapes you have selected in the Visio drawing.?Application. All rights reserved. 14 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Count Press enter.Selection. one a string of text. and can be retrieved or replaced with new data at any time during the running of an application.C. All rights reserved. The following code shows three variables. This part of memory is used to store important pieces of information that will be used in a program. Variables are stored in memory.Variables A variable is a part of memory that is given a name by a programmer.” NumberOfStates = 50 IndependenceDay = #7/4/1776# Variables are empty until you put information in them. Volume 3: Programming with the Visio Object Model 15 . Variables are containers for information that you wish to store in your application. and the last a date: Dim Capitol as String Dim NumberOfStates as Integer Dim IndependenceDay as Date Capitol = “Washington D. 15 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. the other an integer. Volume 3: Programming with the Visio Object Model 16 . Declaring a variable is done by putting the keyword Dim (which stands for Dimension) in front of the variable name. The variable is empty and contains nothing until the variable is assigned a value. it is good practice to first declare the variable. The following example assigns the variable a value: myFirstVariable = “Some String of Text…” The previous example declared the variable explicitly.Dimensioning To create a variable in a program. to avoid creating unnecessary variables and to help debug your programs by using Option Explicit. like so: Dim myFirstVariable as String Dimensioning a variable sets aside the name and space in memory for the variable. All rights reserved. like so: myFirstVariable = “Another String of Text…” It is generally good practice to explicitly declare all of your variables. It is possible to implicitly declare a variable in your code by simply assigning a value to the variable without declaring it first with the Dim keyword. 16 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. however. For ASP scripts that use VBScript.Option Explicit Option Explicit is a line of code that you add to ensure that all your variables are explicitly declared. This is very helpful at design time in catching any mistyped variable names. This helps debug your programs because errors will be thrown if you ever misspell a variable name. This displays a tabbed dialog box. 17 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. If using Option Explicit. an error will be generated if a variable is implicitly declared. It does not. Volume 3: Programming with the Visio Object Model 17 . you can add the line Option Explicit to the first line of your code. add Option Explicit to already existing forms and modules.” Checking this option causes the keywords Option Explicit to be inserted at the beginning of any new module or form added to the project. All rights reserved. One of the check boxes on this tab is “Require Variable Declaration. Choose the Editor tab. For VBA you can do this by choosing Options from the VBA Tools menu. Option Explicit forces any variable name used in code to be explicitly defined. All rights reserved.Data Types In most programming languages. Numeric. If you use Option Explicit it will force all of your variables to have explicit data types. In this case. Boolean. String. you specify the data type when you declare a variable with the As keyword: Dim BabyFirstWord As String BabyFirstWord = “Googoo” To create concise and fast code. Date/Time. or Object. Variants When you do not specify a data type for a variable. etc. it is recommended to explicitly specify a data type. Volume 3: Programming with the Visio Object Model 18 . data types are specified for each variable. VB assigns the variable to a special data type called Variant. the variable is assigned to the data type called Variant. such as String. Depending on the value and the context VBA will automatically assign the Variant one of the following sub-types: Null. Date. The Variant is a special type of variable that can store a value of any type. Integer. In VBA. 18 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Boolean. You can of course declare a variable without specifying a data type. 147. NULL means “nothing”. Object Data Types The Object data type stores a reference to an object. or FALSE. String values are usually put in quotes. 19 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.767. no data and no data type. NULL does not mean zero.768 to 32. but supports ranges from -2.NULL Data Type A NULL subtype is an unusual subtype that is used in conjunction with databases. Numeric Data Types Numeric Data Types include the following:       Integer – Whole numbers within the range of -32.147.483. or even empty. All rights reserved. Volume 3: Programming with the Visio Object Model 19 . and empty is a data type that has nothing assigned to it yet. Byte – Integers within the range of 0-255 Long – Similar to Integer. Objects will be discussed further a bit later in this supplement. and must be enclosed in # characters: myBirthDate = #5/4/1965# Boolean Data Types Boolean data types store values as either TRUE.648 to 2. even if numbers are present in the string: Number1 = “12” Number2 = “14” Number3 = Number1 + Number2 ‘Will Produce “1214” Date/Time Data Types Date/Time data types store dates and times. Zero is a valid value.647 Single – A single precision floating point number Double – A double precision floating point number Currency – Accepts numbers up to four decimal places String Data Type A string holds textual information or words. You cannot perform mathematical functions on strings. NULL refers to a field that contains no data.483. All rights reserved.Naming Variables It is important to establish a good naming convention for your variables. Check if your organization has a defined naming convention and coding standard to use. 20 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. capitalizing the first letter of each word. Your naming convention should be easily understood by another developer who might look at your code later. Using Hungarian Notation The Hungarian notational convention is to use the first three letters of the variant’s name to distinguish the sub-type. but something similar is recommended. Some tips for naming: NameFirst and NameLast are better than FirstName and LastName because they will appear together in a search. you do not have to use the Hungarian notation. Within a procedure or function you may want to prefix your variables with a p_ or f_ type code letter. Volume 3: Programming with the Visio Object Model 20 . Note: Naming conventions and coding style standards evolve over time. as shown in the following table: Data Type Prefix Example Boolean bln blnMember Byte byt bytByte Date / Time dat datToday Double dbl dblDouble Integer int intSalary Long lng lngLong Object obj objConn Single sng sngSingle String str strTextBox For your applications. Create names with multiple words. All rights reserved.Manipulating Variables In order for variables to be of any use. Assignment Operator The assignment operator is the ‘equal’ (=) sign. You can manipulate variables using a number of different operators and by concatenating or converting them. intMyFavoriteNumber = 11 The assignment operator can also be used to assign a new value to a variable. The variable name goes on the left. you will need to manipulate them in some way. as in the following mathematically unsound formula: intMyFavoriteNumber = intMyFavoriteNumber + 1 In the above case. Volume 3: Programming with the Visio Object Model 21 . and the value to be assigned on the right side of the equals sign. With it. you can assign a value to variable. it may look like we are saying 11 = 11 + 1. However. we are simply reassigning a new value to intMyFavoriteNumber. Comparison Operators Comparison Operators are the following: 21 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 22 . All rights reserved.      Equality: = Inequality: <> Less than: < Greater than: > Less than or equal to: <= Greater than or equal to: >= Arithmetic Operators You can use the following arithmetic operators to perform mathematical operations on your variables:        Addition: + Subtraction: Multiplication: * Division: / Exponentiation: ^ Negation: Modulus: MOD or \ 22 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Public Sub Exercise1() 'Dimension the Variables Dim intNumber1 As Integer Dim intNumber2 As Integer 23 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. You can give the new module a name or leave it as the default name. Add the following code to the new aubroutine. double click the module name. assign numbers to them. This will display the code window for the new module. Open the VBA window in Visio (Alt-F11). 3. Click in the code window and choose the menu Insert > Procedure. Exercise 1. 2. and then perform some simple mathematical operations on them. 5. All rights reserved.Exercise 1 Exercise 1 – Variable Manipulation This exercise will use VBA to declare some variables. In the Project window. 4. Give the new procedure a meaningful name such as “Excercise1”. In the VBA window add a new module to the project using the menu Insert > Module. Set Type to Sub and Scope to Public. Volume 3: Programming with the Visio Object Model 23 . Choose OK to close the dialog. Print "intNumber2 = " & intNumber2 Debug. Volume 3: Programming with the Visio Object Model 24 .Print "intNumber3 = " & intNumber3 End Sub 24 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved.Dim intNumber3 As Integer 'Assign them values intNumber1 = 10 intNumber2 = 20 intNumber3 = intNumber1 + intNumber2 'Display the operations in the Immediate widow Debug.Print "intNumber1 = " & intNumber1 Debug. You concatenate strings together in VB with the ampersand character (&). Volume 3: Programming with the Visio Object Model 25 .Other Operations Logical Operators The three most common logical operators are:    AND NOT OR These are mostly used in Conditional statements (IF THEN ELSE). The following code combines two strings together. a process called concatenation. which will be discussed shortly. Concatenating Variables Often times you will want to combine strings together. with a space added in between: Dim strPeter as String Dim strPan as String Dim FullName as String 25 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. strPeter = “Peter” strPan = “Pan” strFullName = strPeter & “ “ & strPan 26 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 26 . All rights reserved. and then concatenate them. Volume 3: Programming with the Visio Object Model 27 . Add the following code to the new subroutine: Public Sub Exercise2() 'Dimension the Variables Dim strNameFirst As String Dim strNameMiddle As String Dim strNameLast As String Dim strNameFull As String 'Assign them values strNameFirst = "Thomas" strNameMiddle = "Alva" 27 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Call it “Exercise2”. assign values to them. Add another subroutine to your coding module. 2.Exercise 2 Exercise 2 – String Concatenation This exercise will use VBA to declare some variables as strings. Exercise 1. It signifies that the code for this statement wraps to the next line.Print "The full name is:" & strNameFull End Sub Note: The underscore character at the end of the statement assigning a value to strNameFull is a line continuation charater in VBA. All rights reserved. 28 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 28 .strNameLast = "Edison" strNameFull = strNameFirst & " " & strNameMiddle & _ " " & strNameLast 'Display the results in the Immediate window Debug. There are many conversion functions. and we will not cover all of them in this supplement. You can do this through several conversion functions that are built into VBA.Data type conversions and variable scope Conversions Often times you will have to convert values in order to work with them better. The CStr function will convert an integer into a string subtype. Note: Global variables must be defined at the top of the module before any subroutines or functions are defined. CInt and CStr. that is. We will only look at two functions. the variable is only valid for the time that the procedure or function is executed. This might mean converting a decimal number into a whole number. All rights reserved. if you declare a variable in a procedure or a function. which are blocks of code that you can reuse throughout your application. 29 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 29 . The CInt function will convert a number variant into an integer and rounds it to the nearest even number. or a numerical sequence into a string. In this case. Variable Scope Variables can be either local or global in scope. The variables we have seen so far have been global in nature. they are valid for the entire block of code that we have written. Sometimes you may wish to break your code into functions or procedures. Volume 3: Programming with the Visio Object Model 30 . All rights reserved.30 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 31 . All rights reserved.Exercise3 Exercise 3 – Variable Scope This exercise will demonstrate local variables that are used in sub-procedures. Exercise 1. This must be done outside of any subroutine or function and must be defined at the top of the module before any subroutines or functions are defined Dim strFirst as String 2. Sub Procedure_1() strFirst = "I'm a string in procedure 1" Debug. Add the following code to the module.Print "Calling Procedure 2:" & strFirst 31 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Print "Calling Procedure 1:" & strFirst End Sub Sub Procedure_2() strFirst = "I'm a string in procedure 2" Debug. Define the global variable. 32 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. The results are displayed in the Immediate window. click within subroutine Exercise3 and choose hit F5.End Sub Public Sub Exercise3() 'Display the results in the Immediate window Procedure_1 Procedure_2 End Sub 3. To run the code. Volume 3: Programming with the Visio Object Model 32 . All rights reserved. All rights reserved. Examples Define the mathematical constant pi. but not to procedures in other modules. Volume 3: Programming with the Visio Object Model 33 . A variable or constant with Private scope is only available to procedures in the module that defines it.Constants Constants are declared with the Const keyword.14159 33 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Constants are valuable when you want to assign a value to a variable and have it remain fixed throughout the execution of the code. Public Const pi As Double = 3. The syntax for Constants is as follows: Public | Private Const name [As type] = Expression A variable or constant with Public scope is available to all procedures in all modules in a project.  Branching statements perform a test. Volume 3: Programming with the Visio Object Model 34 . and then return back to the original code. To nest If statements. when it should happen. and different blocks of code if they are FALSE. The three most common control structures are branching statements. Branching statements test for conditions. use a skeleton like the following: If condition_1 Then ‘Second If Statement If condition_2 Then ‘Code if True Else 34 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. as well as the Select Case statement. and under what circumstances it should happen. but be careful of doing this too many times as the code can become unmanageable very fast. control structures are used to determine what should happen. looping statements. If/Then The If …Then conditional is probably the most widely used control structure in programming. and then execute certain blocks of code if the conditions are TRUE. All rights reserved. and jumping statements.Control structures In VBA. jump to a different block of code.  Looping statements execute a portion of code again and again  Jumping Statements pause the execution of the current code. and then execute some lines of code but not others. Branching Statements Branching statements include the familiar If … Then conditional. The syntax for an If statement is as follows: If logical_expression Then ‘Code to execute if True Else ‘Code to execute if False End If It is entirely possible to nest If statements. Select Case varCurrentMood Case "Sad" 'code for Buy Kleenex and Sob Case "Mad" 'code for Punch the pillow Case "Happy" 'code for Smile Case "Homesick" 'code for Write a letter Case "Irritated" 35 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.‘Code if False End If Else ‘Code if condition_1 is False End If If you want to have multiple tests in a single If statement. you can use ElseIf. ElseIf will enable you test a condition multiple times. Use the following skeleton for an ElseIf statement: If strBreakfast = “Sausage” Then ‘Code if True ElseIf strBreakfast = “Donuts” Then ‘Code if True ElseIf strBreakfast = “Green Eggs and Ham” Then ‘Code if True Else ‘Code if none of the above are True End If Select Case Select Case is used when you need to make a choice among several different answers. Volume 3: Programming with the Visio Object Model 35 . All rights reserved. The following example carries out one of five actions depending on what is contained in the variable varCurrentMood. There can be multiple lines of code for each Case. For Each …Next. Volume 3: Programming with the Visio Object Model 36 . You could name it whatever you want.DateStart For varCounter = 0 To NumberOfDays 'Code to execute here 36 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. For …Next. Here is the syntax: For varCounter = X to Y ‘Code to execute here Next varCounter is a variable that the script uses to keep track of the current count. Go out and play. 'None of the above? Then you must be bored. X signifies the starting number to set the counter to.'code Smirk Case Else 'The catch-all phrase for anything that doesn't fit the above. or is stored in a variable. or can be variable names that store numbers. End Select Looping Statements Looping statements perform the same action over and over again. There are two main looping structures. For … Next Typically the For …Next statement is used when the number of required loops is known. X and Y can be either numbers. and Do …While. and Y is the end number of loops to perform. Dim DateStart As Date Dim DateEnd As Date Dim NumberOfDays As Integer Dim varCounter As Integer DateStart = #7/1/2002# DateEnd = #7/15/2002# NumberOfDays = DateEnd . run through the commands of the mini-program. the value of varVariable1 will change within the loop. or a collection of objects. Volume 3: Programming with the Visio Object Model 37 . There are two types of jumping statements:   Sub procedures – Used to carry out actions. The syntax is as follows: Do While varVariable1 < varVariable2 ‘Code to execute here varVariable1 = varVariable1 + 1 Loop Typically. These are essentially mini-programs that force the main program to jump from the main body of code. 37 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. and then return to the main body of code. On each loop a test is performed.Next For Each … Next The For Each …Next statement is used for looping through items that are in an array or a collection. In the example it is incremented by 1 each time through the loop. Functions – Used to carry out actions and to return an answer to the main body of code. All rights reserved. Jumping Statements Jumping Statements are useful when you need reusable chunks of code that need to be called at specific moments. Do … While The Do …While statement is used when you are not sure of the number of loops to perform. At some point it will become bigger than the value in varVariable2 and the loop will end. The syntax is as follows: For Each Item In varVariable ‘Code to execute here Next varVariable can either be the name of an array. and as long as the condition is met the loop will continue to occur. A sub procedure does not return values. you can pass a variable that stores the current mileage into the function. to create a function to calculate the next time to change the oil of a car (current mileage + 3000 miles). All rights reserved. meaning they can accepts values from the main body of code and use them during the execution of the function. as in the following code: Dim dCurrentMileage as Double dCurrentMileage = 145000 Function FindNextOilChange(dCurrentMileage) as Double 38 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Procedures Sub procedures are used to execute a bit of code. The syntax is as follows: Function NameOfFunction(Parameter) As Integer 'Code to Execute Goes Here 'Assign a value to the function before it ends 'This will be the value that the function returns NameOfFunction = 10 End Function Functions can take parameters. Volume 3: Programming with the Visio Object Model 38 . The syntax is as follows: Sub nameofsub() ‘Code to Execute Goes Here End Sub You can then execute a sub procedure by calling it using the Call command: Call nameofsub Functions Functions are used to execute a bit of code and to return a value back to the main code. Inside the parenthesis () you can place the name of a variable that you want to pass to the function. and then return to the main body of the code. For example. they return the result as a value of a new variable. Volume 3: Programming with the Visio Object Model 39 . it is available for use automatically. It is not necessary to Dim this variable. which is the name of the function. Sub CalculateNewMileage() Dim dCurrentMileage As Double Dim dNewMileage As Double dCurrentMileage = 145000 dNewMileage = FindNextOilChange(dCurrentMileage) MsgBox “The mileage for your next oil change is” & “ “ & dNewMileage End Sub 39 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.When functions are finished performing their calculations. This invokes the function and stores the function’s value as a global variable. All rights reserved. So. the code above becomes complete when we assign the value to the function name: Function FindNextOilChange(dCurrentMileage) as Double FindNextOilChange = dCurrentMileage + 3000 End Function It is common to create a new variable. and make the variable equal to the function. When you create a function and give it a name. that name becomes a variable that will store the resulting value of the function’s calculations. 40 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Defining and using an application’s objects will be covered in the next few lessons as will learning to manage events within VBA.VBA Primer Conclusion There are many more topics that could be covered to help get you started using VBA. All rights reserved. Volume 3: Programming with the Visio Object Model 40 . and the Visio drawing environment. All rights reserved. These requests can be satisfied though automation. drop master shapes on the page. Volume 3: Programming with the Visio Object Model 41 . and creating a Bill of Materials 41 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Introduction to Automation We’ve covered a few of the techniques that can be used for developing SmartShapes symbols. You can open a document. It is common to store descriptive information in a database or a spreadsheet (describing a network. It is very advantageous to get a graphical view of this data by creating a Visio document. Following a brief introduction to general Automation (previously referred to as ActiveX Automation or OLE Automation). you will cover the basics of automation and Visio—the Visio object model and how to access the Visual Basic Editor (VBE). you often need to ask questions or extract information about the drawing. Once a drawing is created. and position and size the newly created shape. All these steps can be done through automation and the techniques will be covered in Generating Drawings. as well as other applications. A common application of automation and Visio technology is the automatic generation of Visio documents. starting an application such as Microsoft Excel. An example of this would be getting an inventory of the shapes in the drawing. for example). Many times the generation of this document can be automated through the extraction of data and the creation of a document through automation. Automation can be used to control Visio shapes. documents. Now let’s cover how to use these symbols as part of a larger solution. with part numbers and price information. you often need to know when something has occurred. Managing Events covers these topics. or a network connection has been made. shape. prompt the user for action. To validate the drawing. In Getting Data from Drawings. All rights reserved. you can trap events and if needed. Volume 3: Programming with the Visio Object Model 42 . 42 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. we will cover the basics of accessing document. and cell properties. a new piece of equipment has been added. As you work with drawings. page. This should not be considered a recommendation that you use VBA for all of your application development. examples are shown using Visual Basic for Applications.Introduction Let’s start by reviewing what is meant by Automation as well as some Visual Basic for Applications fundamentals. These early exercises focus on the Visio object model and not on development environments. 43 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 43 . It’s just that VBA is a very convenient platform for learning about an application’s object model. As such. All rights reserved. NET language as well. Visual Basic. Visual Basic for Applications. one program can incorporate the functionality of another by using objects exposed by the other program. The Visio application is the ActiveX server you are interested in today. 44 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. or container application. This is a program you write in a language that supports Automation. Visual C++. C#. or Microsoft Visual C++. This is the program that exposes the objects for the controller application to use. Automation encompasses several services defined under the OLE 2 specification. It is this interface structure that allows COM objects to make their services available to other applications. The objects have properties and methods that the controller can use to manipulate the objects. COM defines the interfaces for the objects an application exposes. The program that controls the automation is sometimes called a controller. The foundation of this technology is COM (Component Object Model). but you can use the Visio object model with Visual Basic. such as linking and embedding objects and in-place editing.Automation Basics With Automation. client. for example. You are going to focus on Visual Basic for Applications in this module. or any Microsoft Visual Studio . All rights reserved. The program being automated is sometimes called a server or source application. Volume 3: Programming with the Visio Object Model 44 . Some applications can act as both controllers and servers by embedding Visual Basic for Applications. Excel and Visio. such as Word. Volume 3: Programming with the Visio Object Model 45 . Many of the Microsoft Office applications contain VBA. All rights reserved. 45 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. When a row is selected in the Excel 46 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. and invoking methods through the object variable. Objects accessed through Automation remain with the object’s server. Demonstration scenario: The Visio drawing shows the Tech ED 97 General Session Theater which seats 10. This demonstration is a nice example of how multiple applications can work together by accessing the object models of each other’s application. store the reference in an object variable Container (Controller) 'Create a reference to an object Source (Server) object Set myObj = Source.Programming a Server's Objects Programming a Server's Objects   The server owns the objects. However. They are not incorporated in your program. In this scenario. Everything you do with a server’s object is done by way of a reference to that object. which you assign to an object variable in your program. you just use them You get a reference to an object. All rights reserved. by setting properties. it is valid at run time but it is not something you can store between executions. You manipulate the objects remotely. An object reference is similar to a pointer. For example. from your program. having a reference doesn’t guarantee that you have an object. Furthermore. if the user deletes the shape. you still have the reference but it’s not referring to anything useful. Visio controls Excel by gathering information from the Visio drawing and writing it to an Excel spreadsheet.  The object always resides with its source.object myObj. Volume 3: Programming with the Visio Object Model 46 . you can get a reference to a shape on a page.000 and was the actual location for the original showing of this program.method  Access to the properties and methods of the object is made through the interface provided by the object. description. In the Visio drawing there is a T-shirt firing Air Gun on the stage. controls.xlt. Contents of the drawing can be pushed to an Excel spreadsheet by right clicking on the page and selecting "Create Asset Report". A control on the Air Gun allows you to direct the gun by moving it around the drawing. From the spreadsheet there are events tied to the up and down arrow keys so that as you move through the spreadsheet using the arrow keys the corresponding Visio object is selected and centered in the drawing. 5. 2. Minimize all windows except the Visio window. All rights reserved. From your student CD.spreadsheet there is code that controls Visio and selects and centers the drawing on the selected object. etc. but was part of the original demo. 3. Bold. number of individual items and unit cost. The demonstration will take advantage of this feature as you select the Visio drawing objects from the Excel spreadsheet. If any item is greater than $10. open <install path>\Demos\Vol3\Introduction to Automation\TechEd. This add-on starts Excel. and writes each component of the drawing to the spreadsheet. This starts Microsoft Excel and creates a Bill of Materials for all of the objects in the drawing. Set Center Selection on Zoom. The Wet Bar is priced at $25. opens the template file TechED. and a larger point size. 47 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Try it! TechEd 1. When placed into the spreadsheet the total cost of each item is also calculated. project units. That is the automated control of an air cannon gun that was on stage and used to fire tshirts into the crowd. In Visio select File > Options > Advanced tab. Right-click on the drawing page and select Create Asset Report. NOTE: Be sure to set the option "Center selection on zoom" in the File > Options > Advancced tab for the centering to occur. Notice that the corresponding item is selected in the Visio window (you may have to zoom in or out in Visio to get a better view). demonstration machines.. 4. Tile the Excel and Visio windows. The drawing depicts seating. Volume 3: Programming with the Visio Object Model 47 . Select a row in Excel. 6.000 the row item is made Red. Each item in the drawing has shape data which capture the manufacturer. As you move the pointer for the air cannon in Visio.vsd. The air cannon is represented by a shape in the Visio drawing. There is a third application which unfortunately cannot be demonstrated here. the coordinates from the Visio drawing were being fed to the actual air cannon on the stage through Rockwell’s own automation interface for this device.000 so it gets flagged in the spreadsheet. stage. Right click on the Air Gun to either display its shape data or to display a form with the trajectory coordinates. 48 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 48 . All rights reserved. When a Visio document with a VBA project is loaded. a developer can digitally sign a project and be identified as a trusted source. Just check the ones that you want to access. from the References menu. This is done from the References menu under Tools. All rights reserved.” Checking this option causes the keywords Option Explicit to be inserted at the beginning of any new module or form added to the project. Objects other than Visio objects can be accessed by Visual Basic for Applications. This is very helpful at design time in catching any mistyped variable names. if you want to control Excel from the Visio application. 49 Visio Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. add Option Explicit to already existing forms and modules. Choose the Options menu under Tools. check the appropriate Excel object library. One of the check boxes on this tab is “Require Variable Declaration. but the Visual Basic for Applications environment must first be notified. Choose the Editor tab. Digital Signatures allow you to add an extra level of security to your VBA projects. The functionality of Digital Signatures was added to Visio 2002. For example. Using digital certificates. This displays a tabbed dialog box. It does not. The dialog box displays all object libraries installed on the local machine. however.VBE Tools Menu From the VBE Tools menu you can get to some very useful menu options. Volume 3: Programming with the Visio Object Model 49 . Option Explicit forces any variable name used in code to be explicitly defined. microsoft. If it has not. All rights reserved. search the Microsoft Developer Web site (msdn. the project will be loaded under any security level. For more information on Microsoft Office security. 50 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.checks to see whether the project has been digitally signed by a trusted source before loading it. If it has. Volume 3: Programming with the Visio Object Model 50 .com) for “Digital Signing”. Macro security settings in Visio can be found in the Trust Center. Visio will load the project based on the current security level set for the Visio application. To turn off the Object Browser. methods. and events.Object Browser Once an object library is part of the project. From the Object Browser you can view the hierarchical structure of any object library. Volume 3: Programming with the Visio Object Model 51 . just close the window. 51 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. you can view its properties. Choose View > Object Browser (or F2) to use the browser. You can search for objects by name. Once an object is selected. its objects can be viewed with the Object Browser. Values of constants defined in a type library can also be determined from the object browser. All rights reserved. Automation allows one program to incorporate the functionality of another by using objects exposed by the other program. Because it exposes its object model it can be used as a server. What allows Visio to be a controller and a server at the same time? 4. The controller application can use this handle to ask the server application to do things with this object. All rights reserved. 4. What actually happens when one program uses Automation to drive another program? 3.Review: Introduction to Automation Questions 1. 2. The server application returns a handle to an object. Using digital certificates. Define Automation. 52 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Because Visio has embedded VBA it can be used as a controller. Volume 3: Programming with the Visio Object Model 52 . 2. 3. What function does a digital signature provide? Answers 1. a developer can digitally sign a project and be identified as a trusted source. Automation and Visio Technology In this section, we will tie together some of the concepts that were learned in the ShapeSheet modules with Automation objects from the Visio object model. We have spent a good deal of time learning about the ShapeSheet. The ShapeSheet is important to understand in order to effectively automate Visio because each cell in the ShapeSheet is effectively a property that you can control through automation. However, most ShapeSheet cells will not be found directly in the Visio Object Model. Instead, you will access them indirectly through the Cells or CellsU property of the Shape object. 53 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 53 Overview Automation and Visio Technology  The Visio Object Model  Working with Objects, Methods, and Properties  When and How to Run Your Program  Getting More Information Now you will learn about how you can use SmartShapes as part of a larger solution by using Automation to control the Visio application and the objects within it. In this module you will look in depth at the Visio Object Model. You will analyze each object and begin the process of discovering its methods and properties. You will learn different strategies for when and how to run your programs and issues to consider when choosing a platform for your program. Finally, we will look at other resources that are available to help in you in learning about and using the Visio Object Model. 54 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 54 The Visio Object Model The Visio Object Model  Slide is portion of the complete model  Collections are blue  Individual objects are yellow  Walk the object model in code to obtain your object reference This slide shows a portion of the Microsoft Visio object model. A richer, but not complete view of the Visio object model is on the following page. The image shows the object model of Visio 2003, but at this high level view it is still shows the major components and the basic structure of the model. It is not as complicated as it looks; many of the objects are used primarily to access other objects, and you’re unlikely to use all of the objects in a given program. For example, you’ll probably do more with shapes than you will with documents and pages; you may never manipulate layers from a program, although Visio exposes layer objects so you can if you need to. Many objects in the model correspond to items you can see and select in Visio windows. For example, a Page object corresponds to a drawing page; a Shape object can represent anything on the drawing page that you can select with the pointer tool—a shape, a group, a guide or guide point, or an object that is linked or embedded in a Visio drawing. The Application object represents a running instance of the Visio application, and this is where you’ll typically start. In some circumstances you can start at the document or the page. The Application object has properties that return references to “next objects” in the model—for example; the Documents property returns a reference to the Documents collection, which represents all of the documents that 55 are open in the instance. You would retrieve a particular document by using the Item property of the Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 55 Documents collection. Use the Pages property of that Document object to get its Pages collection, and so on, down to a particular shape or even a particular formula of that shape, represented by a Cell object. The Microsoft Visio global object is automatically available to Microsoft Visual Basic for Applications (VBA) code that is part of the VBA project of a Visio document. The Visio global object is not available to code in other contexts. The global object holds references to such properties as ActiveWindow, ActiveDocument, and ActivePage. These properties are also available through the Application object if you are building your solution outside of VBA within Visio. 56 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 56 57 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 57 A Sample Visio Program Sample Visio Program  Open Sample Code.vsd  Navigates the object model   Starting with the <Global> object Gets the shape’s Name and NameID properties and displays the values on a form Code sample conventions Code samples in the demonstration files and code displayed on slides generally follow a simple Hungarian notation. Variable names start with a lower case letter or letters that designate the data type of the variable. Following the data type designator will be a name describing the variable that starts in upper case. Below are some examples of variable names:      oDocs – a data type Object referencing a Documents collection oDoc – a data type Object referencing a single Document sShapeName – a data type String containing a shape’s name txtShapeName – a text box control containing a shape’s name dCellResult – a double precision variable containing the contents of a ShapeSheet cell Try it! A Sample Visio Program 1. Run an instance of Visio, and from your student CD open <install path>Demos\Vol3\ Automation and Visio\Sample Code.vsd. 58 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 58 It returns the Documents collection. All rights reserved.Documents Documents is a property of the Application object and also of the <global> object (accessed through the application name Visio). Press Alt+F11 to open Visual Basic for Applications. 3. txtShapeName. which can be assigned to the Text property of our text box. Volume 3: Programming with the Visio Object Model 59 . 5.Pages Set oPage = oPages. Set oDoc = oDocs. Close the GetShape add-on.GetShape). Set oPages = oDoc. The rest of the code establishes a reference to each collection and collection member. too).Name The Name property of a shape returns a string. In the Project Window. We will look at the VBA code for this add-on in step 5. It happens to be the default property.Item(1) Item is a property of the Documents collection (and of most other collections.2. so you can omit Item but not (1). Right-click on the page to run the add-on GetShape (or from View > Macros > ThisDocument. Select View Code and look at the following line: Set oDocs = Visio.Shapes Set oShape = oShapes.Item(1) sShapeName = oShape.Text = sShapeName 59 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. 4. open the Forms folder and right-click on frmGetShape.Item(1) Set oShapes = oPage. Shape  Set oShape = ActivePage. This is a Shape object that has Type=visTypePage. write-only properties Once you get the object you want.# Read-write: ShapeSheet cells Write-only: Custom menu or toolbar sets The Developer Reference help file contains a list of objects with their properties and methods. in addition to the Name property. 60 or write-only. a guide. You can set properties too. and a Type property that identifies the type of shape—whether it’s a group. read-write.Getting and Setting Properties Getting and Setting Properties    Properties that return an object  Dim oShape As Visio.Name Setting properties   oShape. Most properties that don’t return objects return strings or integers. you’ll probably become interested in its other properties. Volume 3: Programming with the Visio Object Model 60 . read-write. For example. or other kind of shape. All rights reserved.PageSheet Properties that return other data types  Dim sName As String  sName = oShape. The PageSheet property of the page returns a reference to the page’s ShapeSheet.Name = "Box" Read-only. Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. a Shape object has a Text property that returns its text. whether they’re read-only. and their return type. This reference also has an alphabetical list of properties and methods. as long as they’re read-write or write-only. Here are some examples of property types:    Read-only: A shape’s Sheet. Note: When making an assignment to a variable of type Object. Volume 3: Programming with the Visio Object Model 61 . All rights reserved. the Set keyword must be used. 61 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. When making an assignment to a variable that is not an object (such as a string variable). the Set keyword is not used. SendToBack  Properties or methods with arguments Set oShape = ActivePage.Item(1) Set oShape = ActivePage. For example.3) oFromCell. but their syntax is similar to properties.1.GlueTo oToShape.Activate oShape. Both properties and methods sometimes take arguments.DrawOval(1. a Shape object has a Copy method that performs the same action as selecting the shape and choosing Copy from the Edit menu in Visio.Add("")  Methods that perform other actions Visio. Volume 3: Programming with the Visio Object Model 62 . For example:   A Shape object’s Cells property takes the name of the ShapeSheet cell to return.3. a Window object has an Activate method that makes that window the active window. Methods that don’t create objects typically don’t return anything. it typically returns a reference to that object. If a method creates an object. The Documents collection’s Add method takes the name of a template on which to base a new document.Windows.Shapes. Other methods correspond to actions.Document Set oDocument = Documents. All rights reserved. 62 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. For example. Passing an empty string is equivalent to choosing File > New Drawing from the menu or New from the Toolbar. Methods often correspond to Visio commands.Invoking Methods Invoking Methods  Methods that create objects  Define specific object type Dim oDocument As Visio.Item(2).Cells("PinX") There were no methods used in the demonstration program of getting the shape’s name. All rights reserved. Volume 3: Programming with the Visio Object Model 63 .63 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 64 .Compound References Compound References   You can concatenate object  References  Properties  Methods Example: Set oShape = Visio. All rights reserved.Shapes. However. you’ll get an error at the statement but it may not be obvious where the failure occurred. 64 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Each expression is evaluated and its return value plugged into the statement before the next expression can be evaluated. simple references are better.Pages _ . properties.Documents. A compound statement can also be harder to debug. if you’re going to be working with more than one shape from the Shapes collection—it makes sense to assign the intermediate objects to variables so you have them available for other uses. If you use any of the intermediate objects in your program—for example.Item(3).Item(1). and enhances performance.Item(1)  Simple references can be more efficient  Store intermediate objects in variables  Code is easier to read and debug The examples in this course tend to declare an object variable and set it for every object in the model that we need a reference to. This requires less overhead than repeatedly calling a compound statement. You don’t have to do this as you can concatenate Visio object references. If one fails. and methods as you can with Visual Basic objects. there are some tradeoffs and sometimes. This will display a form with the title GetDoc. Establish each object reference separately. run the macro. Without looking at the code for how the solution was produced.Lab 3. From Visio. Consider the document properties Description. choose View > Macros > ThisDocument. 65 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. From your student CD. 2. 4.1: Get the Name of an Open Visio Document Lab 4. Click the button on the form to display the name of the document. 3. open <install path>\Labs\Vol3\Start\Get Doc.vsd 2.vsd  Add code to display the document’s name in the text field of the Visual Basic for Applications form  Add additional command buttons and text boxes to your form to display other Document properties Points to Consider 1. Path or Subject for your additional information. Volume 3: Programming with the Visio Object Model 65 . When complete. 5. All rights reserved. Exercise 1. develop code to retrieve the document’s name and place it in frmExercise.1: Get the Name of an Open Visio Document  Run Visio and open GetDoc.Solution. Coding Issues If an object is defined to be a specific type at design-time. If late binding is used. This creates more efficient run-time code. Many design-time checks can be made such as testing assignment statements to ensure the correct data type is being used. Using Visual Basic for Applications code makes distribution of your add-on easy since the Visual Basic for 66 Applications code is part of the drawing file. All rights reserved. and assigning the wrong type of data to the object can cause a run-time error. method.Document it is bound to that data type at design time. This is called early binding. Using early binding of objects also allows you to take advantage of the Visual Basic Intellisense feature. however. Volume 3: Programming with the Visio Object Model 66 . as with the statement Dim oDoc as Object the type of the object must be determined at run time. is more difficult. event and parameter information. Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. as with the following statement Dim oDoc as Visio. Updating the code. giving you property. Volume 3: Programming with the Visio Object Model 67 . 2. Save and close the file. From the Tools menu. and open the Visual Basic Editor window. 3. 67 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. choose <document name> Properties. and click the Lock project for viewing checkbox. All rights reserved. The next time the file is opened and the VBE is accessed. Click the Protection tab.Demonstration: Protect Your VBA Code 1. 5. the project is locked and a password must be entered to view or edit the project. Open a new Visio drawing. 4. Enter a password and confirm it. 68 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Add a public procedure into a module or ThisDocument of the VBA project for the drawing. Create a Macro through the Visio interface. Use the Add method of the application's Addons collection to programmatically add the add-ons.vsl file into a designated Add-ons folder. 3. You can also use the file paths refresh method . When Visio is launched a. From the ribbon under View > Add-ons a. Macros in any one open project can be accessed by another open project. To set the Startup folder go to File > Options > Advanced > File Locations… b.exe or . To set the Add-ons folder go to File > Options > Advanced > File Locations… b. 2. Volume 3: Programming with the Visio Object Model 68 . All rights reserved. Put the . b. From the ribbon under View > Macros a.Running Your Program To run your program: 1. Register the COM-Addin and set its load behavior to Load at Startup.vsl file into a designated Startup folder. Put the . Note: You have to restart Visio to refresh its Add-ons list before you’ll see your program on the menu.exe or . stencils and other files as components to be integrated with the Visio application. you can publish your add-ons. When the user opens a document Place your code or a reference to it in the DocumentOpened event in the ThisDocument module in Visual Basic for Applications. Publish Components will be covered in the section on the Visio Software Development Kit. When a shortcut menu command is chosen Create an entry in the Actions section of the ShapeSheet and make sure the add-on is either a public procedure within the Visual Basic for Applications project or is in the Addons path specified in the File > Options > Advanced > File Locations… dialog. templates. Volume 3: Programming with the Visio Object Model 69 . It offers tighter integration with the Visio application. Publishing components is the preferred method of integrating add-ons and other content with Visio. 5. Note: Beginning with Microsoft Visio 2003.4. All rights reserved. 69 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. and better performance on add-on discovery. All rights reserved. Visio will first check for a macro of name “string” and execute that macro if one is found.exe") 2. you must preface the string with "ThisDocument" as shown.exe”) RUNADDON can execute a macro or call an add-on. RUNADDON("Array Shapes") 3. Visio reports no error and takes no action  Examples:  RUNADDON(“ModuleName. Visio reports no error and does nothing. Call the ReportStatistics macro in ModuleName in the document project that contains this function call.ReportStatistics") 4. Launch the (VSL-implemented) add-on whose name is Array Shapes.exe RUNADDON("Calendar. it will execute that macro  If no macro is found. If no add-on can be found.RUNADDON(“string”) RUNADDON(“string”)  If Visio recognizes the string as a macro. To invoke a macro in the ThisDocument module.Report”)  RUNADDON(“Calendar. Volume 3: Programming with the Visio Object Model 70 . the RUNADDON function looks for “string” in the add-on list and executes the add-on if it is found. 70 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Launch an add-on called Calendar. If “string” is not recognized as a macro. Examples: 1. Call the ReportStatistics macro in the ThisDocument module in the document project containing this function call. RUNADDON("ThisDocument. the RUNADDON function looks for “string” in the add-on list and executes the add-on if it is found  If no add-on can be found. ReportStatistics") For more information. All rights reserved. Volume 3: Programming with the Visio Object Model 71 . see the demonstration file <install path>\Demos\Vol3\Automation and Visio\RunAddon.RUNADDON("ModuleName. 71 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.vsd for some examples of using the RUNADDON function. 72 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. CALLTHIS is a variation of RUNADDON that automatically passes a reference to the shape that caused the add-on to be executed. there are times where the add-on being executed needs to get a reference to the shape that initiated the action. a cell that contains a formula with CALLTHIS is saying. the name "CALLTHIS. All rights reserved." The demonstration file CallThis. hence." In effect. Volume 3: Programming with the Visio Object Model 72 .CALLTHIS Even though RUNADDON is a very powerful function.vsd has some good examples of using the CALLTHIS function. Notice that the reference to the shape is very much like the "this" argument passed to a C++ member procedure. "Call procedure and pass it a reference to my shape. Help > Search > Developer Reference. Other sources of information include the Visio Developer Portal on msdn. This is the key entry point to gaining access to the latest articles. Review what is in each property and method topic. A good place to start is with the Visio help files.microsoft. examples and downloads related to Visio. 3. http://www. 4. This describes the object and lists its properties and methods. Use some of the other jumps in the method topic to related properties and methods or other objects that have the same method. The Developer Reference help file contains material for the automation model. Help information for the ShapeSheet is contained in the Visio SDK. Demonstration: Developer Reference 1.com. 5. There are also Visio discussion groups where you can post questions and get answers.microsoft. Display the topic for one of the object’s methods. Volume 3: Programming with the Visio Object Model 73 . Open the Developer Reference help file. In the Table of Contents select Visio Automation Object Model Reference. All rights reserved. 2.com/communities/newsgroups/en-us/ 73 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Where to Find Visio Automation Information There are many ways to get helpful information on the Visio automation model. Display an object topic. you cannot record the action of shutting down the application. and then turn off the recorder. or any actions which leave Visio in a Modal state. Turn on the Macro recorder. Data Graphics. and Pivot diagrams does not cover everything that can be done in the user interface so use of the macro recorder in these areas has been short circuited. code librarian code snippets. perform the function you wish to automate. Dialog only commands and Solution-specific commands are generally not recorded . properties. documentation. A great way to explore the object model and really get a feel for how everything ties together is through the Object Browser. Print ShapeSheet. however. All rights reserved. Viewing the generated code will show you how the operation is performed through automation. for example. and tools— including the Event Monitor. limitations on the actions that can be captured by the Macro Recorder. The Macro Recorder can be used to develop snippets of code for performing some function in Visio. Also. 74 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. There are. Persistent Events. and Solution Publishing. From the Object Browser you can explore the entire Visio Object Model. and methods of the current running instance of Visio. From the Immediate window investigate objects. You can also explore a live Visio application by using the Immediate window from VBE.so you could not automate the dropping and property setting of Database Model entities. From the Visual Basic Editor choose View > Object Browser to display the Object Browser window.The Visio SDK provides sample applications. The Watch Window and the Locals Window are great places to view data values when exercising or debugging code in VBA. The API programmability model for Themes. Volume 3: Programming with the Visio Object Model 74 . Choose View > Immediate Window. 2: Running VB Add-ons Lab 4.exe into the appropriate folder to list it as an add-on  Create a new Visio drawing and shape  Add your DispName. Note: Check File > Options > Advanced > File Locations for the appropriate add-on folder.Lab 3.exe file to the shortcut menu for the shape to run the program via right-click  Run the program when you double-click a shape as well For the lab. copy DispName.2: Running VB Add-ons  From the Student CD. Volume 3: Programming with the Visio Object Model 75 . follow the directions listed on the slide. 75 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. 2. Window. Cell. what are some of the different ways you can run it? 3. What are some of the objects in Visio’s object model? How might you use them in a program? 2. Shape. A fundamental decision is between creating a macro and creating an add-in. How might this influence the design of your program? Answers 1. Macros are useful for fairly simple one-off type solutions. Methods. 76 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. 3. and Properties  Running Your Program  Getting More Information Questions 1. Solutions can be set up to run from a shape with a right-click action or a double-click. All rights reserved. etc. Addins and macros can also be executed from the View tab of the ribbon. Volume 3: Programming with the Visio Object Model 76 . Once you’ve finished building your custom solution. Visio drawings can be created using automation or existing drawings can be interrogated for information. Application.Review: Automation and Visio Summary: Automation and Visio  The Visio Object Model  Working with Objects. Document. All rights reserved. Volume 3: Programming with the Visio Object Model 77 .77 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Generating Drawings Overview  Creating Visio Documents  Dropping Masters in a Drawing  Getting and Setting  Shape Properties  Cell Formulas and Values In this section let’s begin by using automation to create a document, drop masters in a drawing, and set the text of shapes. Along the way you’ll see more generally how to get and set shape properties, including how to access a particular formula and get either the formula as a string, or the value that is its result. 78 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 78 Creating a Document Creating a Document  Get the Documents collection of the Application object Set oDocs = Visio.Application.Documents 'or Set oDocs = Application.Documents 'or Set oDocs = Documents  Add a new document to the collection Set oDoc = Documents.Add("Basic Network.vst") Set oDoc = Documents.Add("") Set oDocStencil = Documents.OpenEx( _ “Basic Network Shapes.vss", visOpenDocked) To create a new drawing, add a Document object to the Documents collection of the Application object. As you may recall, the Application object has a Documents property that returns its Documents collection. Because this is an object, you need to assign it to an object variable using Set. The first three code statements are equivalent in VBA because the global Visio is predefined and contains a reference to the Application object and the Documents object. If working outside of VBA it will be necessary to get a reference to the active instance of Visio’s Application object in order to access the Documents collection. If no documents are open in the instance, its Documents collection is empty. This can be important to remember if, for example, you run Visio and attempt to get a document without opening one first. Attempting to get an object from an empty collection causes an error. To create a new document, use the Add method. For a Documents collection, Add takes the filename of a template as an argument. Visio searches for the template in the template location defined under the menu File > Options > Advanced > File Locations. Alternatively, you may specify the file path explicitly. If you don’t want to base the new document on a template, use a null string. This creates a new blank document. 79 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 79 The Open and OpenEx methods can be used to open existing document files. OpenEX takes the additional parameter that flags how to open the file. See the Microsoft Visio Developer Reference for more information. 80 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 80 Getting a Reference to the Master If you base a new drawing on a template, it probably opens one or more stencils for you. This means the Documents collection now has more than one object in it. It has the new document you created plus each stencil opened by the template. When you use automation to drop a master in a drawing, you’ll be working with two Document objects—one that represents the new drawing, and the other that represents the stencil containing the master. Note: Every Visio document has a stencil which holds the master shapes that have been added to the drawing, so every Document object has a Masters collection. But the Masters collection of a new drawing is generally empty. Just make sure that you set your object reference to the Masters collection of the stencil, not the drawing. 81 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 81 Dropping the Master on the Page Dropping the Master on the Page  Get the drawing page Set oPage = ActiveDocument.Pages.Item(1) Set oPage = ActivePage  Drop the master on the page Set oShape = oPage.Drop(oMaster,4.25,5.5)  4.25, 5.5 indicate where to place the pin of the new shape instance on the page  Drop coordinates are always in inches, regardless of drawing scale or language version  Use ConvertResult method to convert units Having obtained a reference to the master, you now need a page on which to drop it. The next step is to get a Page object. A new document has at least one page, so its Pages collection will contain at least one Page object. To drop a master, use the Drop method of the Page. Drop takes three arguments: a Master object and a pair of x,y coordinates that indicate where to place the pin of the new shape (the instance of the master). The coordinate arguments to Drop must be expressed in inches, which are the units that Visio uses internally. Unfortunately, this means you may have to convert the arguments before dropping the master, if for example, you’re working in a scaled drawing or an unscaled drawing in metric units. The ConvertResult method of the Application is a handy tool for solving these unit conversion problems. Tip: Because you are going to do more to the new instance of the master, assign the object returned by Drop to an object variable, such as oShape. You’ll usually want to do this, but it’s not required. 82 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 82 83 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 83 of course. You assign text to a shape by setting its Text property to a string. 84 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. and insert special characters (such as the linefeed shown here) using the VB Chr$() function or vbCrLf.Text = "K. which will be ample for most purposes. or have the user type it in a form. you’ll usually set the text in shapes at run time. concatenate strings and variables with the Visual Basic concatenation operator. You might get the text from another file.Text = "This is a text string"  Use ASCII linefeed Chr$(10) or vbCrLf to control line breaks oShape. for example.Adding Text to Shapes Adding Text to Shapes  Set the text property of the Shape object oShape. You can.Text = """Hello?"""  Equivalent way to get embedded quotes oShape.Text = Chr$(34) & "Hello" & Chr$(34) When you are creating a drawing from a program. The Text property of a shape can contain up to 64K of character data. All rights reserved. Volume 3: Programming with the Visio Object Model 84 . just as you can do through the user interface. Use the Characters object to control field codes within the stream of text. Anderson" & _ Chr$(10) & "Chairman of the Board"  Use double double quotes to embed quotes in the string oShape. All rights reserved. So it might seem that your options are limited. Change the contents of a cell by setting its Formula property. To get a Cell object.Cells("PageWidth") Compared to everything you can do to a shape in Visio.Cells(“User. however. such as the width and height of the page. Most commonly. Once you have a Cell object. such as a shape’s Width formula. To get page cells. which returns a Shape object. They’re not.Getting Formulas of Shapes and Pages Getting Formulas of Shapes and Pages  In Visio’s object model. Shape objects have relatively few properties and methods (although they have many compared to some other objects in the model). 85 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. you can get the formula or the value it represents. a formula is represented by a Cell object  To get a Cell object for a shape formula Set oCell = oShape. Volume 3: Programming with the Visio Object Model 85 . you’ll get the values of certain formulas so you can use them to construct your drawing. Use the same names for cells as are used in the ShapeSheet. because you have full access to the ShapeSheet through Cell objects.Cells("Width") Set oCell = oShape.Shape Set oPageSheet = ActivePage. first get the PageSheet property of the page. A Cell object represents a particular formula. get the Cells property of a shape object and specify the name of the cell.PageSheet Set oCell = oPageSheet.WatchHeight”)  To get a Cell object for a page formula Dim oPageSheet as Visio. The ShapeSheet reference under help lists all of the ShapeSheet cells alphabetically by name. just as you can choose Formulas or Values when viewing the ShapeSheet. Then use the Shape object’s Cells property to get the formula of a particular cell. or the drawing scale. Volume 3: Programming with the Visio Object Model 86 .Tip: When should you use Cell vs CellU and Cells vs CellsU. using CellU instead of Cell and CellsU instead of Cells will save you some work. If you are faced the possibility of having to localize your solution. 86 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. The universal names never change in localized versions of Visio. CellU and CellsU take the universal name (not localized) name of a cell as their argument. Volume 3: Programming with the Visio Object Model 87 . hold down the Ctrl key and press the space bar. ResultIU. you can use visDrawingUnits to get a result expressed in units defined for the drawing. Result and ResultIU return a double precision value as a floating-point number with 15 significant digits. use its Formula property to get its formula as a string. All rights reserved. Tip: Use VBA’s Intellisense to help view available Visio constants.Result("mm")  See also ResultInt. For example. To explicitly specify a unit-less number. use one of the Result properties. If you want the formula’s value instead.Formula  The Result property returns the value of the formula as a double in the units specified Dim dCellResult as Double dCellResult = oCell. You can specify units for the value returned by a Result property by passing any valid unit string or one of the unit constants defined in the Visio type library. ResultStr returns the value as a string. ResultStr Once you have a Cell object. Also check the Developer Reference help file for a complete list of these constants. ResultInt returns a long integer. use visNumber.Getting a Formula or Its Result Getting a Formula or Its Result  The Formula property of a Cell object returns its formula as a string Dim sCellFormula as String sCellFormula = oCell.Result("in") dCellResult = oCell. In VBA just type “vis”. 87 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. for cells that measure linear dimensions or radians for cells that measure angular dimensions. Volume 3: Programming with the Visio Object Model 88 .Tip: Visio’s internal units are inches. 88 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. just as it is when you type in the ShapeSheet window To set a cell value to a constant.5  Can also set ResultInt and ResultIU   ResultStr is read-only To overwrite a guarded cell use  FormulaForce  ResultForce When you set formulas from a program. All rights reserved. you probably won’t need to construct the kinds of complex formulas you’ve been building in the class to control shape behavior. Volume 3: Programming with the Visio Object Model 89 . set either the Result or the Formula. Those more complex formulas will most likely already be in place in your solution. If you’re working with a cell whose formula is guarded. you’ll need to use the “force” equivalents of Formula and Result:     FormulaForce ResultForce ResultIUForce ResultFromIntForce 89 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Note: Using the equal sign (=) is optional.Result(visNumber) = 2.Setting a Formula Setting a Formula  Set the Cell object’s Formula property oCell.Formula = "GUARD(Width*2)"  Set the Cell object's Result property  oCell. 5). Only when you have an unscaled drawing are these the same.Cells("PageWidth").5) ‘0. 90 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Cells("PageHeight").5  Use an offset to position one shape relative to another dXLoc2 = (dXLoc + 0.ResultIU*0. PageHeight *0. The Drop method requires the position to be in drawing units (not page size).5. One simple technique involves calculating the shape’s position relative to the page’s width and height.5) ‘1. if you know you want to center a shape on the page. For example. for example.ResultIU*0. and exactly how you do this will depend on the kind of drawing your program creates.5 inches down Positioning shapes in a drawing can be a challenge.5 dYLoc = _ oPageSheet.1. to determine the center of the page Dim dXLoc as Double Dim dYLoc as Double dXLoc = _ oPageSheet.5 inches right dYLoc2 = (dYLoc . Another technique is to position one shape at a constant offset from another–by getting the PinX and PinY values of one shape and adding the offset to them for the other. Volume 3: Programming with the Visio Object Model 90 .Tips for Positioning Shapes Tips for Positioning Shapes  Use drawing units to place shapes. All rights reserved. you can drop its pin at (PageWidth*0. Note: Using this method. the PinX and PinY values in your shapes will typically change. Consider using a page margin offset and the CenterDrawing method together to enhance shape position on the final page. Volume 3: Programming with the Visio Object Model 91 .Cells(“PageHeight”) _ . Because the page is resized using this method.PageSheet. Visio provides the ResizeToFitContents method for Master and Page objects.CenterDrawing There may be functionality in your solution that requires page size to change based on how many shapes are added or deleted from the page. the page extents are right at the edge of the outer most shapes on the page.PageSheet.ResultIU = dPageWidth + 1 oPage. This method resizes the page to fit tightly around the shapes that are on it.ResizeToFitContents ‘ create margin around shapes oPage.ResultIU = dPageHeight + 1 ‘ center shapes on larger page oPage. All rights reserved.Tips for Positioning Shapes (Continued) Tips for Positioning Shapes (Continued)  Use ResizeToFitContents method to resize the page to fit tightly around the shapes that are on it Set oPage = ActivePage oPage. 91 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. If your solution keeps track of shape position. this fact may ultimately be a deterrent of using the ResizeToFitContents method. This method is the equivalent of clicking the Size to fit drawing contents on the Page Size tab in the Page Setup dialog.Cells(“PageWidth”) _ . Assume that you are working with two shapes on the drawing. Shape Geometry or Guide To create a connected diagram from a program. A and B. Volume 3: Programming with the Visio Object Model 92 . To connect the shapes:    Use the Cells property of shape A to get a Cell object that represents the part of the shape you want to glue. use the GlueToPos method of shape A’s Cell object and indicate the shape you want to glue to shape B with a position relative to shape B’s width-height box.) Or. You are not interested in their formulas or results. 92 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. you work with cell objects  Get a Cell object that represents the part of a shape you want to glue   1-D End Point or Control Handle Use the GlueTo or GlueToPos methods of the Cell object and specify what you want to glue to  Connection Point. All rights reserved. but in a slightly different capacity. Use the GlueTo method of that Cell object and indicate a cell that represents the part of shape B you want to glue to. instead. such as a connection point. such as a control handle.Connecting Shapes Connecting Shapes  To create a connected diagram from a program. (You do not necessarily need to get a Cell object for shape B. you use them to indicate what gets glued to what. you work with cells. All rights reserved. To do this. you can indicate a different row. or AlignBottom for a horizontal one. For example.Y pair  Control handle Set oFromCell = _ oFromShape. and you can use either one.Getting the Cell to Glue Getting the Cell to Glue  You can specify either cell of an X. AlignCenter. If you’re gluing a 2-D shape to a guide or guide point. and AlignTop.Cells(“BeginX”)  Edge of a shape that will glue to guide or guide point Set oFromCell = _ oFromShape. Controls. The shape edge that you specify needs to be appropriate for the type of guide—AlignLeft. the control handle must be able to be glued (some aren’t). you’ll get an Inappropriate Target Cell error.Cells(“AlignLeft”) Here are a few examples of how you can indicate various parts of a shape you want to glue. Volume 3: Programming with the Visio Object Model 93 . You may not get this error with a guide point.Cells(“Controls. If the shape had more than one control handle. which depends on the CanGlue setting in the ShapeSheet. or AlignRight for a vertical guide. 93 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. if you try to glue the right edge of a shape to a horizontal guide.X1 refers to the first row of the Controls section in the ShapeSheet. you can indicate which edge of the shape you want to glue. Control handles and the begin and end points of 1-D shapes are defined by two cells—one for X and one for Y. You do not need both cells in order to glue the item. AlignMiddle. In this example. but you will get odd results.X1”)  Begin point or end point of a 1-D shape Set oFromCell = oFromShape. GlueTo _ oToShape. AlignTop. AlignCenter and AlignMiddle both glue to the center of the shape. Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.GlueTo celObj2 You can glue to the same items you can in Visio. Internally. 0. For a guide point. All rights reserved. use AlignLeft.Y position in another shape oFromCell.5. If you check a guide’s Type property.Y pair.Cells("Connections. If you want to glue to a guide. use GuidePosX for a horizontal guide or GuidePosY for a vertical one.X1") ‘ connection point oFromCell. Volume 3: Programming with the Visio Object Model 94 . such as a vertex (Geometry1. If it did.GlueToPos oToShape.Cells (“Geometry1.Yn).Gluing to the Other Shape Gluing to the Other Shape  GlueTo glues to a specific cell in another shape oFromCell. As when specifying the cell to glue. you only need one cell of the X. a guide is a shape. This example does not have a Cell object to represent the glue destination.5  GlueToPos always creates a connection point. 94 you can use either. the statement would be: celObj1. To create a guide you use the AddGuide method of a Page object. One type of cell you can glue to using the GlueTo method is a connection point. it returns visTypeGuide.GlueTo _ oToShape. AlignRight. or AlignBottom to indicate the selection handle in the center of that edge of the shape (rather than the whole edge).X1”) ‘ geometry vertex  GlueToPos glues to an X. even if one already exists. If you want to glue to a selection handle.Xn or Geometry1. like anything else on the page. 0. Y coordinates of a position relative to the shape’s width-height box.GlueToPos takes slightly different arguments: a Shape object and the X. All rights reserved. 95 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. In this case.5 indicate the center of the shape’s width and height. 0.5. Volume 3: Programming with the Visio Object Model 95 . 0. Cell 'Get references for the cell to glue from and the cell to glue to for 'the beginning of the connector Set vsoCellFrom = vsoConnector. All rights reserved.Masters. Try It! Below are two procedures for connecting a dynamic connector between two shapes. Sub ConnectWithGlue() 'Glue a connector between two shapes using the GlueTo method Dim vsoConnector As Visio.ActiveDocument. Execute the macros and see that the connector is placed and glued.Shape 'Drop the connector shape Set vsoConnector = Application.Drop _ (Application.CellsU("EndX") 96 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.ActivePage. 2.Cell Dim vsoCellTo As Visio.ItemU _ ("Dynamic connector"). 0#.AutoConnect Mode The AutoConnect feature added can be accessed programmatically as well as through the user interface.ActivePage. 0#) Dim vsoCellFrom As Visio.ItemFromID(1). To run the code open the file Autoconnect. 0) 'Glue the cells vsoCellFrom.vsd from the Samples folder for the class.CellsSRC(7. Volume 3: Programming with the Visio Object Model 96 .AutoConnect to simulate Auto-Connect.CellsU("BeginX") Set vsoCellTo = _ Application.GlueTo vsoCellTo 'Get references for the cell to glue from and the cell to glue to for 'the end of the connector Set vsoCellFrom = vsoConnector.Shapes. Use Shape. Autoconnect vsoShapeTo. Sub EnableAutoConnect() 97 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. hovering the mouse over a shape presents the four autoconnect triangles around the shape.Shapes.Item("Decision") vsoShapeFrom. The reason for this is that the Autoconnect method hooks up both ends of the connector with one command. 0) 'Glue the cells vsoCellFrom.Shape Dim vsoShapeTo As Visio. Volume 3: Programming with the Visio Object Model 97 .Item("Process") Set vsoShapeTo = Application.ItemFromID(2).CellsSRC(7. All rights reserved. When Autoconnect is turned on. Clicking on one of these triangles connects the shape to another shape.ActivePage.ActivePage.ActivePage. Using the GlueTo method requires that each end of the connector be handled separately.Set vsoCellTo = _ Application.GlueTo vsoCellTo End Sub Sub ConnectWithAutoConnect() 'Glue a connector between two shapes using Autoconnect Dim vsoShapeFrom As Visio.Shapes. visAutoConnectDirNone End Sub A quick inspection reveals that it takes about one-half the lines of code to glue shapes using Autoconnect.Shapes.Shape 'Get a reference to the two shapes Set vsoShapeFrom = Application. Enable/Disable Autoconnect Autoconnect can be enabled or disabled within the File > Options > Advanced tab. 2. Below are VBA code snippets for turning autoconnect on or off. When autoconnect is turned off these triangles do not appear. Settings.EnableAutoConnect = True End Sub Sub DisableAutoConnect() Application.EnableAutoConnect = False End Sub Note: It is not necessary for EnableAutoConnect to be set to True in order to use the Autoconnect method through automation. Volume 3: Programming with the Visio Object Model 98 .Application. All rights reserved.Settings. 98 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. you can add a Shape Data section. if a shape does not have Shape Data. Volume 3: Programming with the Visio Object Model 99 . Sometimes you may need to add cells to a shape. add rows to it. For example. and then set formulas of cells in those rows. just as when you’re developing a shape in Visio. All rights reserved. 99 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Adding Data to Shapes Earlier you learned about getting cells that represent formulas. You don’t need to explicitly add cells to the new row. Unlike adding a section in the ShapeSheet (which automatically gives you one row). which is the constant for the Shape Data section.AddSection visSectionProp  Add a row oShape.Cells("Prop. AddNamedRow will create it Then reference cells and set formulas oPropCell = oShape. All rights reserved. when adding a section from your program you need to add the rows explicitly.PartNo") oPropCell. for those it’s used to indicate the row type. 0   Note : If the section does not exist. Constants for these are defined in the VBA object browser. If you try to add a section that a shape already has. you’ll get an error. and a row tag of zero. use the AddNamedRow method. To do this in a shape data section.AddNamedRow visSectionProp. If the section doesn’t already exist.Adding Sections and Rows Adding Sections and Rows  Add the section oShape. such as LineTo. you use the AddSection method and specify the type of section . 100 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. or just add the row. _ "PartNo". Volume 3: Programming with the Visio Object Model 100 .Formula = "XYZ-123" To add a section. specify the section. either use the SectionExists property to test whether the shape already has the section. The example uses visSectionProp. you can access its cells in the usual way. the row name. it will be created automatically. Note: The row tag should be zero for any kind of row except the Geometry section rows. To avoid this. Once you’ve added the row. Volume 3: Programming with the Visio Object Model 101 . one in each quadrant of the drawing Points to Consider Do the procedure manually first.vst  Instance a master in the drawing and set its text to "Hello World“  Change the size of the page to more closely match the size of the shape Challenge  Repeat the exercise with a scaled template  Drop four masters. Do not look at the solution code before attempting the exercise. and master.3: "Hello World" Lab 4. Use X and Y coordinate variables to make dropping the four masters on the page more efficient. and note each step and the names of your template. stencil.vsd and add code to:  Create a drawing using an unscaled template such as Basic Diagram (US Units).3: "Hello World"   Open Hello. 101 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Lab 3. Comments have been developed in a partially completed exercise to guide you through the process. All rights reserved. If you opened a new blank drawing. What does a Cell object represent? 3. What object property would you use to replace a guarded cell formula? Answers 1.Review: Generating Visio Drawings Summary: Generating Visio Drawings  Creating Visio Documents  Dropping Masters in a Drawing  Getting and Setting  Shape Properties  Cell Formulas and Values Questions 1. Why are drop-coordinates always in inches? 4. All rights reserved. 2. how many items would the documents collection contain? 2. FormulaForce or ResultForce 102 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 102 . A Cell is an object representing a single cell in the ShapeSheet. 4. Visio maintains internal units in inches. 3. There would be only one document in the Documents collection since a blank drawing has no stencils opened. 103 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 103 . All rights reserved.Getting Data From Drawings 104 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 104 . and shapes. or do something to. pages. It is frequently necessary to access objects selected in the drawing. can be accessed through the Selection property of the Window object. The Selection can be accessed through automation or can be created through automation. All rights reserved.Overview Overview  Iterating through Visio Collections  Getting Information from   Documents  Pages  Shapes  ShapeSheets Getting the Selection Object Now you’re going to approach Visio objects from a slightly different perspective—by retrieving information about the objects that already exist in the drawing. plus you’ll discover another way of getting a Cell object using CellsSRC. The Selection object. and the kinds of information you can get from them that you might use in a program. You’ll read briefly about documents. each object in the collection. Here’s what you are going to cover in this section: You’ll learn about how to iterate through a collection so you can get something from. 105 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 105 . or set of shapes selected in a window. Cells(“Width”). Volume 3: Programming with the Visio Object Model 106 . All rights reserved. This could make a difference in the example above. Hyperlink collections also start with 0. You can iterate through a collection to perform the same operation on every member. where Count is evaluated for each pass through the loop. Use it to build your object references and process shape data. Be sure to check before you start writing code. Some Things to Remember about Collections Most Visio collections are indexed starting at 1. however if you add or remove objects from the collection.Iterating Through a Collection Iterating Through a Collection  Most Visio collections are indexed starting with 1   Except for user interface objects which start at 0 The Count property returns a number of items in the collection For i = 1 to Documents. A good way to iterate through collections like page or shape collections is with the For Each… Next statement.Count Set oDoc = Documents. or check each member until you find the one you want. but be careful. by name or by index. in which case Count returns 0. only the UI object collections are indexed starting at 0.Item(i) 'process item Next i  Use the For Each…Next statement to iterate through a collection For Each oThisShape in oShapesCollection oThisShape.Formula = “2” Next You’ve seen how you can retrieve objects from collections. Generally. The Count property returns the number of items in the collection at the time you get the property. 106 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. the value of Count will change. Collections associated with a valid Visio object always exist. but the collections may be empty. ColorShapes adds a color to each shape. Note that the For loop in the code counts down from the highest indexed shape. 2. 107 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Count to 1 Step -1 A collection is not like an array. until sooner or later you overreach Count and try to delete an item with an invalid index. including the groups themselves. 3. Open the file <install path>Demos\Vol3\Getting Data from Drawings\ Collections. Try it! Collections 1. as you delete an item. which causes an error. 4. you skip that item and delete the next one. DeleteShapes deletes all of the shapes on the page.When you delete objects from a collection using an iteration loop. the next item moves into that position. Instead. Use CountShapes to count all of the shapes in the groups. decrement the counter rather than incrementing it. Form some group shapes on the page.vsd. items don’t keep a fixed index position. Run the sample code via right-click on the page. Each macro is an example of working with collections. All rights reserved. 5. But if you’ve incremented your counter. For example: For i = oDocs. Volume 3: Programming with the Visio Object Model 107 . Item("filename") Set oDoc = Documents. or open a file without adding it to Visio’s file menu of most recently used files. Under some circumstances you might be able to construct the path from the Path property of a document that is already open. because you probably don’t want your users changing those. Use OpenEx with the appropriate flag to open a file as read-only. Do not hard code the path but instead use the common Open dialog box to get the user to indicate the path. Volume 3: Programming with the Visio Object Model 108 . For best results.OpenEx(“Logical Symbols. _ visOpenDocked)  Getting an open document Set oDoc = Documents.vsd") ‘Binary Visio file or Documents. for read/write access). 108 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Using relative path names can be unpredictable at times. which is not good for stencils and templates. try to use a full path when opening a document.Getting Data from Documents Getting Data from Documents  Opening a document Set oDoc = _ Documents.Item(index) The Open method opens a document as an original (that is.vss". you can get it by its filename or its index in the collection.Open(“Logical Network.vdx”) ‘XML for Visio file Set oDoc = _ Documents.Open(“Physical Network 3. Open a stencil docked in a drawing window. If the document you want is already open. Fullname.Noteworthy Document Properties Noteworthy Document Properties  Masters. and Title correspond to options of the same name in the document’s summary information. Keywords. Volume 3: Programming with the Visio Object Model 109 . If an existing document has been opened or a new document has been saved. The Name. To determine whether a document has been saved. TimeEdited. Styles. and just the path portion of a document’s full filename. Fullname. You’ve already see the Masters and Pages collections. InPlace  TimeCreated. Title  ReadOnly. has been changed since it was opened (the Saved property is really a dirty flag) or has been opened for in-place editing in a container document rather than in a standalone instance of Visio. Fonts. Saved. Subject. with objects that represent those items. Colors  Name. Fonts. Subject. Pages. ReadOnly. Saved. (Properties command from the File menu. and Visual Basic Project collections. The return value is a date formatted like this one: 109 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. full filename. but a Document object also has Styles. and Path properties contain the short filename. Description. Keywords. All rights reserved. and InPlace are Boolean properties that indicate whether a document was opened as read-only. Colors. TimePrinted  Various Print… properties These are a few of the Document object properties available through the object model. its Path property will be set. Path  Creator. TimeSaved. TimeCreated. TimeSaved and TimePrinted return the date and time of each action.) Creator corresponds to Author in the File Properties dialog. respectively. check its Path property. Description. TimeEdited. Volume 3: Programming with the Visio Object Model 110 . PrintPagesDown. etc. Set these properties first and then use the Print method to print your document. 110 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.4/6/10 1:50:21 PM There are several Print… properties that allow you to set properties for printed output. such as Printer. PrintFitOnPages. All rights reserved. PrintCenteredH. The Page also has a Layers property for accessing information about Layers defined for the page and a Connects property for getting information about connections that exist on the page. you can get the page by its name or by its index in the Pages collection. All rights reserved.Getting Data from Pages Getting Data from Pages  Getting a page Set oPage = oPages. when you learn about windows and the selection object. This will make more sense a little bit later in the session. 111 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. The ActivePage property is a quick way of getting a page without going through a document.Item(index)  Example: Set oPage = oPages. If a stencil window had focus and you attempted to get the ActivePage.ActivePage  When you use ActivePage. However.Delete True  Getting the active page Set oPage = Application.Item("pagename") Set oPage = oPages. We have already seen that a Page has a Shapes property for accessing the shape collection on the page.Item(“Bill of Materials") oPage. make sure the active window is the drawing window or an error will occur Getting a page is similar to getting an open document. it only works if the active window is a drawing window. Volume 3: Programming with the Visio Object Model 111 . an error would occur in your solution. groups. and linked or embedded objects (bitmaps. guides and guide points. the definition is somewhat expanded. Recall getting the PageSheet property in the last session. When you’re working with shapes from a program. The Type property of a Shape object returns a constant describing the shape. Volume 3: Programming with the Visio Object Model 112 . Characters. metafiles. and Layer.). 112 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. visTypePage  For shape properties and methods. such as Text and Cells.Getting Data from Shapes Getting Data from Shapes   A Shapes collection can include  Basic shapes  Groups  Guides/guide points  Linked/embedded objects Type property indicates a shape’s type visTypeShape. That property returns a Shape object so you can use its Cells property to get page formulas. it returns visTypePage. which returns the area of the shapes geometry in internal units. So if you’re iterating through a Shapes collection. If you check that Shape object’s Type property. A few interesting Shape properties include AreaIU. which contain shape connection information. visTypeGroup. these various items differ quite a bit in what you can do with them. Excel spreadsheets. which contains information about the layers a shape is assigned to. visTypeForeignObject. which contains the shapes text and the fields that control that text. Connects and FromConnects. A page’s Shapes collection includes basic shapes. visTypeGuide. and so forth. Obviously. see the Developer Reference Help file You’ve already worked with shapes and used some of their properties. you’ll almost always want to check a shape’s type before continuing with whatever you’re doing to the shape. All rights reserved. or guide that the Shape object is glued to  FromSheet. If the shape isn’t glued to anything. the collection is empty.Getting Data About Connections Getting Data About Connections  The Connects property of a Shape object returns its Connects collection  Contains a Connect object for each shape. The FromPart and ToPart properties return integers that indicate which parts of the shapes are involved. All rights reserved. The relationship between a shape and the object that it is glued to is represented by a Connect object. Volume 3: Programming with the Visio Object Model 113 . group. You access the Connects collection differently depending upon whether the shape is a one-dimensional or two-dimensional shape. ToPart properties   Return shape objects involved in the connection Return integers indicating part of the shape involved FromCell. These are represented by constants such as visControlPoint and visConnectionPoint. You can get information about the connection by getting properties of the Connect object. Every shape has a Connects collection. The FromCell and ToCell properties return Cell objects that correspond to the FromPart and ToPart values. 113 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. ToSheet properties   FromPart.    The FromSheet and ToSheet properties return Shape objects for the shapes involved in the connection. If the shape is glued to one other shape (or guide). its Connects collection contains one Connect object representing that relationship. ToCell properties  Return cell objects that correspond to From/ToPart values Earlier you saw how to connect shapes in a drawing through Automation. For example. FromCell returns a Cell object that represents that control handle in the ShapeSheet. if FromPart is visControlPoint. Volume 3: Programming with the Visio Object Model 114 . 114 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. and for simplicity’s sake. All rights reserved. Volume 3: Programming with the Visio Object Model 115 .Connect Object for a Control Handle to a Shape Study the following case. it contains one Connect object with these properties: FromSheet = A ToSheet = B FromPart = visControlPoint + 0 ToPart = visConnectionPoint + 0 FromCell = Cell objects for FromPart ToCell = Cell object for ToPart 115 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. If you get the Connects collection of shape A. The control handle is glued to a connection point on shape B. assume that shape A has only one control handle and shape B only one connection point:   Shape A has a geometry that is tied to its control handle. Connect Object for a 1-D Between 2-D Shapes Here’s a more common case:    Shape C is a one-dimensional connector glued to shapes A and B. Select the dynamic connector. Try it! Connect Object 1. nor are they glued to each other. Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Open <install folder>\Demos\Vol3\Getting Data from Drawings\ Connect Object. Shape C’s Connects collection contains two Connect objects because it’s glued to shape A and shape B. and remove its connection to Shape 1. In this case.vsd. and the shapes that were 116 involved. A and B aren’t glued to shape C. A message box will appear describing the action that occurred. All rights reserved. the begin point of shape C is glued to the third connection point of shape A (first row + 2 = row 3). Volume 3: Programming with the Visio Object Model 116 . See the Developer help file for more information about the Connects object. and the end point of shape C is glued to the fourth connection point of shape B (first row + 3 = row 4). 2. 3. Open the Visual Basic Editor and review the code in the ConnectionsAdded and ConnectionDeleted page events. 4. Re-glue the connection you just removed. 117 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. The message box utilizes the From/ToSheet and From/ToCell properties of the connect object to relay its information. Volume 3: Programming with the Visio Object Model 117 . All rights reserved. Print ActivePage.ConnectedShapes to get the shapes that are incoming connections to a shape Dim shp As Visio. it does get tedious to use the Connects objects to retrieve this connectivity information.ConnectedShapes(Flags. 2.Selection. Visio 2010 introduces several new methods that make these efforts a lot easier. However. The IDs can be filtered as incoming or outgoing connections. Public Sub GetIncomingShapes_WithCategories() 'Use Shape. In other words you no longer have to go through the connector to see what is on the other side.Shapes(shpIDs(i)).vsd.Shape Dim shpIDs() As Long Dim i As Integer If ActiveWindow. All rights reserved.Print "Incoming shapes" For i = 0 To UBound(shpIDs) Debug. The results of running the macros are written to this window. Volume 3: Programming with the Visio Object Model 118 .Selection(1) End If shpIDs = shp.Name 118 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Select page ConnectedShapes and follow the directions on the page. separated by a 1-D connector). "Square") Debug.ConnectedShapes(visConnectedShapesIncomingNodes. Try it! ConnectedShapes 1.e. Use Shape. CategoryFilter) to return an array of identifiers (IDs) of shapes that are one degree of separation away from the given shape (i. Open <install folder>\Demos\Vol3\Getting Data from Drawings\Connections API.Count = 0 Then MsgBox ("select a shape with connections") Exit Sub Else Set shp = ActiveWindow. 3.More Connectivity API options One of the very nice features of Visio has always been the ability to maintain and interrogate connected diagrams through automation. Open the VBA Window (Alt—F11) and turn on display of the Immediate Window (View > Immediate Window). Print ActivePage. positions it relative to the target shape and adds a connector from the target shape to the new shape. Dim shpIDs() As Long shpIDs = shp.GluedShapes(visGluedShapesIncoming1D. All rights reserved.msvShapeCategories cell of its ShapeSheet.vsd.Shapes(shpIDs(i)). TargetShape. Select page GluedShapes and follow the directions on the page. You can optionally specify another shape to which any returned shapes must also be glued. A shape’s categories can be found in the User. Volume 3: Programming with the Visio Object Model 119 . PlacementDir. You can optionally specify a specific connector to use if you need to override the default connector. [pOtherConnectedShape]) to return an array of identifiers for the shapes that are glued to a shape. Try it! GluedShapes 1. 119 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Name Next    Flags: Specifies dimensionality and directionality of connectors of shapes returned. 2D and by incoming vs. Use Shape.Next End Sub   Flags: Filters the list of returned shape IDs by the directionality of the connectors.DropConnected(ObjectToDrop. CategoryFilter: Filters the list of returned shape IDs by limiting it to IDs of shapes that match the specified category. The returned IDs can be filtered by 1D vs. "") Debug.Print "Incoming 1D shapes" For i = 0 To UBound(shpIDs) Debug. 3. The results of running the macros are displayed in VBA’s Immediate window. [Connector]). pOtherConnectedShape: Optional additional shape to which returned shapes must also be glued A method that parallels the AutoConnect feature is Page. Open <install folder>\Demos\Vol3\Getting Data from Drawings\Connections API. CategoryFilter. In the sample code above the method only returns shapes that are in the category “Square” which is designated in the shape’s User. outgoing connections.msvShapeCategories cell. CategoryFilter: Specifies category of shapes returned. 2. This creates a shape.GluedShapes(Flags. Open <install folder>\Demos\Vol3\Getting Data from Drawings\Connections API. 4.5. Shape). 8) For i = 1 To 5 Set lastDrop = _ ActivePage. Try it! SplitConnector 1. Set connector = ActiveWindow. Volume 3: Programming with the Visio Object Model 120 .vsd. Shape 2 is inserted between shape 1 and shape 3 and the existing connector is split. Open <install folder>\Demos\Vol3\Getting Data from Drawings\Connections API.SplitConnector(ConnectorToSplit.Selection(1) Set ovShape = ActiveWindow. 2. space.Shape Dim i As Integer Set lastDrop = ActivePage.DropConnected(ActiveDocument.Try it! DropConnected 1. Six Process shapes are dropped and connected on the page. use Page. Select page DropConnected and follow the directions on the page. This overrides usage of the default Dynamic Connector.DropConnected to drop several Process shapes Dim lastDrop As Visio. Select page SplitConnector and follow the directions on the page.Masters("Process"). _ lastDrop.vsd.Masters("Process"). Sub DropConnected() 'use Page. To drop a new shape on a connector and split the connector. visAutoConnectDirDown) Next End Sub     ObjectToDrop: The shape to be added to the page TargetShape: The existing shape from which to align. Pass it the connector to split and the shape to drop. and connect PlacementDir: The direction from TargetShape in which to place ObjectToDrop . All rights reserved.Drop(ActiveDocument. 2. Connector: The connector to use (optional). The example drops shapes using visAutoConnectDirDown.Selection(2) 120 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Try it! AutoConnectMany 1.vsd. 0. This method automatically draws multiple connections in the specified directions between the specified shapes. PlacementDirs(). ovShape)   ConnectorToSplit: The connector to split. The selected shapes are connected and repositioned from left to right. Units) and specify the end of the connector to disconnect.SplitConnector(connector. and the units. It returns the number of shapes connected.25. Try it! Disconnect 1. visInches End If     ConnectorEnd: The end of the connector to disconnect OffsetX: The x-distance that the connector end is moved away from the shape OffsetY: The y-distance that the connector end is moved away from the shape Units: The units of measure for the assigned offset values To add many connections quickly.AutoConnectMany to create connectors between shapes 121 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.25.AutoConnectMany(FromShapeIDs().25 inches in each direction. OffsetX. the offset. OffsetY. Must be a routable 1-D connector. All rights reserved. Must be a 2-D shape. Volume 3: Programming with the Visio Object Model 121 . ToShapeIDs(). Public Sub AutoConnectMany() 'use Page.Set newConnector = ActivePage. Select page GluedShapes and follow the directions on the page to run macro ShapeDisconnect. Select page AutoConnectMany and follow the directions on the page. [Connector]). 0. If ovShape. Connectors can be unglued and the end of the connector moved away from the original glue position with a single method call.Disconnect(ConnectorEnd. use Page. 2. Shape: The shape to use to split the connector. Both ends of the connector are unglued and moved away from the connection points by . Open <install folder>\Demos\Vol3\Getting Data from Drawings\Connections API. 2.vsd. Open <install folder>\Demos\Vol3\Getting Data from Drawings\Connections API. Use Shape.Disconnect visConnectorBothEnds.OneD Then ovShape. DeleteEx(Flag) will delete additional shapes associated with a shape or selection. when the selection is deleted. Volume 3: Programming with the Visio Object Model 122 .If ActiveWindow.AutoConnectMany fromShapeIDs().ID placementDirs(i) = visAutoConnectDirRight Next ActivePage. 2.1 fromShapeIDs(i) = ActiveWindow.Selection.Count . Open <install folder>\Demos\Vol3\Getting Data from Drawings\Connections API. Try it! DeleteEx 1. Select page DeleteEx and follow the directions on the page. placementDirs() End Sub     FromShapeIDs(): An array of identifers of the shapes from which to draw a connection ToShapeIDs(): An array of identifers of the shapes to which to draw a connection PlacementDirs(): An array of constants that represent the directions in which to draw the connection Connector: The connector to use (optional). toShapeIDs(). All rights reserved.Selection(i + 1). The selected shapes are connected and repositioned from left to right. This overrides usage of the default Dynamic Connector.ID toShapeIDs(i) = ActiveWindow.vsd. such as connectors and unselected container members.Selection(i). 122 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Count < 1 Then MsgBox "Select at least two shapes in the order they are to be connected" Exit Sub End If Dim fromShapeIDs(10) As Long Dim toShapeIDs(10) As Long Dim placementDirs(10) As Long Dim i As Integer For i = 1 To ActiveWindow.Selection. The flag must be a bitwise combination of the following constants.When the option to heal connections is chosen the two hanging connectors resulting from the shape delete are merged into one. Volume 3: Programming with the Visio Object Model 123 .visDeleteHealConnectors  Flag: can specify that unselected connectors. or callouts are to also be deleted.DeleteEx VisDeleteFlags. ovShape. Not the third example on this page. shapes within a container. All rights reserved. It is not possible to heal the connectors in this case because there are two incoming connectors and two outgoing connectors and therefore the result is indeterminate. o visDeleteNormal=0 – match the deletion behavior that is in the user interface o visDeleteHealConnectors=1 – delete connectors that are attached to deleted shapes o visDeleteNoHealConnectors=2 – do not delete connectors that are attached to deleted shapes o visDeleteNoContainerMembers=4 – do not delete unselected members of containers or lists o visDeleteNoAssociatedCallouts=8 – do not delete unselected callouts that are associated with shapes 123 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. can be accessed through the Selection property of the Window object. The order of items in the collection follows the order in which the corresponding shapes are selected in the drawing window. The easiest way to get the Selection object is to access the selection in the current active window: Dim oSelection as Visio. Volume 3: Programming with the Visio Object Model 124 . The first shape selected is the first item in the collection. All rights reserved.ActiveWindow.Selection Set oSelection = Application. then they are put in the selection in front to back order. If the shapes have been selected by dragging out a selection rectangle.Selection One very good use for a Selection object is to allow users to indicate the shapes they want to work with. with the forward-most shape being the first shape in the selection.Getting a Selection Object Getting a Selection Object  Get the Selection property of a Window object  Similar to Shapes collection   It has Item and Count properties Order reflects order selected in the drawing  Does not include shapes sub-selected in a group  Can add and remove selected shapes  Keep it current ! The Selection object. You can also create a Selection object through automation as a means of working with a subset of shapes on the page. 124 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. or set of shapes selected in a window. Volume 3: Programming with the Visio Object Model 125 . but the changes won’t be reflected in your program unless you get another Selection object. After you get a Selection object. 125 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. For this reason. the user can change the selection. All rights reserved. it’s best to get a Selection object just before you plan to use it.Probably the most important thing to keep in mind about a Selection object is this: It’s not bound to the selection in the drawing window. One thing to remember about the Windows collection is that it may grow or shrink by more than one item at a time. you can probably assume that the active window is a drawing window. but more often you’ll be interested in a particular kind of window. visAnchorBarBuiltIn etc…  SubType (visDrawing) can be visPageWin. visMasterWin. If your program has just run an instance of Visio and created a drawing. depending on other actions. it is always good to make sure. Volume 3: Programming with the Visio Object Model 126 . which includes all of the drawing. Many of a Window object’s methods are only relevant in a drawing window. Not surprisingly. ShapeSheet. visStencil. you may also want to check its SubType property to make sure you have the right kind of drawing window. the ActiveWindow property returns the active window. For a drawing window. All rights reserved. You can iterate through a Windows collection in the usual way. visIcon. visMasterGroupWin An Application object has a Windows collection.Type <> visDrawing Then Exit Sub ‘not a drawing window End If  Type can be visDrawing. the subtype property returns the same value as the type property. You can check the Window object’s Type property to find out what kind of window it is. Here are some ways to utilize a Window object’s properties and methods:  Use the Activate method of a Window object to make it the active window 126 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. stencil.Working with Windows and Selected Shapes Working with Windows and Selected Shapes  Getting the active window Set oWindow = Visio. However. Note: If the type property of a Window object returns any value other than visDrawing. visSheet. visPageGroupWin. and icon edit windows that are open in the instance.ActiveWindow  Checking a window’s type If oWindow. All rights reserved. Volume 3: Programming with the Visio Object Model 127 .   Get the document displayed in the window by getting its Document property Change the magnification with the Zoom property Get shapes selected in a drawing window by getting the Selection property 127 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. (Rows are indexed starting with the row index constant as the base. You can do this using section.vsd. row. but iterating through each of the Control section rows and getting the same cell from each one is easier using CellsSRC. and cell indexes. You can also use these indexes to see if the shape has a particular section. row.X cell in the 4th row Set oCell = _ oShape. or use them to add sections to a shape. However. CellExists. All you have to do is increment the row offset instead of constructing a cell reference string.Getting Cells with CellsSRC Getting Cells with CellsSRC  What if the cell you need to reference does not have a unique name?  Use CellsSRC to get a cell by section. RowExists. All rights reserved. Controls. as you’ll see later in this session.X3 cell. 128 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.CellsSRC(visSectionControls. CellsSRCExists You used the Cells property in the last module to get cells by name. sometimes you might want to iterate through rows or cells. From your student CD. row. or even sections such as in a shape with multiple Geometry sections. Try it! CellsSRC 1. so you need to add an integer offset for the second and subsequent rows. visCtlX)  See also SectionExists. This is almost always the preferred way to get a particular cell. _ visRowControl + 3. the cell object is set to the Controls Section. Volume 3: Programming with the Visio Object Model 128 . and index  In this example. or cell.) This might seem like a lot of work to get a single cell. open <install path>\Demos\Vol3\Getting Data from Drawings\Collections. The example on the slide uses CellsSRC to get the Controls. 3. Select one of the shapes on the drawing page and run the macro View > Macros > Sample_Code.SampleCode. All rights reserved.2. Open the Immediate window (also known as the Debug window) in VBA. 129 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.PrintGeometry. The macro prints all cell formulas from the Geometry section to the Immediate window. Volume 3: Programming with the Visio Object Model 129 . page. All rights reserved.     DistanceFrom property of the shape returns the distance between two shapes SpatialRelation property describes the relationship between two shapes SpatialNeighbors property of a shape returns shapes meeting relationship criteria (For an example. Volume 3: Programming with the Visio Object Model 130 . or master returns shapes near a point Visio offers several properties for determining shape proximity.vsd) 130 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.vsd) SpatialSearch property of shape. or master returns shapes near a point (For an example.Determining Shape Proximity Determining Shape Proximity   Visio provides shape properties to help you determine a shape’s proximity to other shapes DistanceFrom property of the shape returns the distance between two shapes  SpatialRelation property describes the relationship between two shapes  SpatialNeighbors property of a shape returns shapes meeting relationship criteria  SpatialSearch property of shape. page. see Spatial Relation Office. see Which Shapes are in View. and click the Relationship button. 4. visSpatialContain. Open <install folder>\Demos\Vol3\Getting Data from Drawings\Spatial Relation. 3. Move the small square so it overlaps the large square. 131 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Demonstration: Shape Relationships 1. 5. Note: Before you establish the shape relationship. or if one is inside the other. Move the small square so it is within the bounds of the large square. and click the Relationship button.vsd. both shapes need to be selected. but this time. It can determine if two shapes overlap or touch. and click the Relationship button. Volume 3: Programming with the Visio Object Model 131 . visSpatialContainedIn. change the shape selection order. visSpatialTouching = visSpatialOverlap The SpatialRelation property is used to determine the relationship between two shapes. Move the small square so its edge touches the edge of the large square.SpatialRelation SpatialRelation  Use to determine relationship between two shapes  The SpatialRelation property returns one of visSpatialOverlap. Repeat step five. 2. 6. Lab 3. 132 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved.4: Calculate the Area of a Shape Lab 3.4: Calculate the Area of a Shape  Open Shape Area. Volume 3: Programming with the Visio Object Model 132 . Look for a Shape property that calculates area based on shape geometry.vsd  Add code to calculate the area of a shape’s:   Alignment Box  Geometry Loop through the Shapes collection to calculate the total area of all selected shapes Points to Consider Area based on width and height (parameters of shape alignment box) will be larger than area based on geometry. Shapes. What would be an advantage of using the ActivePage property? What would be a disadvantage? 2. 3. such as in the geometry section. The OpenEx method has an additional parameter that is use to specify how the document is to be opened. 2. 133 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.g. it only works if the active window is a drawing window. Under what circumstances would you use CellsSRC? 4. Pages. e.Review: Getting Data from Drawings Getting Data from Drawings I: Conclusion  Iterating through a Collection  Getting Information from Documents. The ActivePage property is a quick way of getting a page without going through a document object. Use CellsSRC when a section has an non-fixed number of rows or when the number of cells in a row can vary. What is the difference between Open and OpenEx? 3. Use the shape’s Type property to test whether it is a group. However. Volume 3: Programming with the Visio Object Model 133 . and ShapeSheets  Getting the Selection Object Questions 1. as read-only. The Open method opens a document as the original. 4. All rights reserved. How would you find out whether a Shape object represents a group shape? Answers 1.. 134 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 134 . Managing Events 135 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 135 . Beyond the ShapeSheet. such as when it is moved or resized. All rights reserved. When something happens to a shape.You will first look at handling basic events through the management of ShapeSheet cells. programmable event mechanism. 136 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. You will also get an introduction to the Visio event object model and learn how to use Visual Basic for Applications to create code behind events. and EventDrop) in which formulas can be placed. the ShapeSheet has an Event section that has event cells (TheText. More directly. events can be handled through Visual Basic for Applications as code behind events. These cells evaluate whenever the event occurs.Learning Objective Even though you can respond to user events through the ShapeSheet. You can detect these changes in the ShapeSheet and cause another action to occur as a result. EventXFMod. This uses the underlying Visio object model to create and respond to events. EventDblCick. Volume 3: Programming with the Visio Object Model 136 . some cell values change. This Event object model allows the programmer to set up event handling for a larger set of events. Visio has a more robust. In this section you will see how your solution can respond to ShapeSheet events. Keep in mind that events can occur as a result of a user action or as a result of a program being run that controls Visio. All rights reserved. A dictionary definition of an event is “an occurrence or incident. an event occurs as a result of an action  Solution becomes aware of the change  Solution does something in response to this change Events can occur as a result of a user action or as a result of a program being run that controls Visio Before diving into code behind events. 137 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 137 .” As a programmer.Introduction Introduction   In Visio. you should be clear about what is an event. you want to know when these “events” occur and do something in response to the event. especially one of significance. Cell Dependencies Cell Dependencies  A formula may depend on other cells    PinY =(BeginY+EndY)/2 EndY =PAR(PNT(Sheet. Because of the dependency that has been established.2!Connections. in turn. In the slide example. Instead it establishes a dependency network so that it only recalculates cells that have the potential to change.X1 Value of Connections. All rights reserved.2!Connections. the dependency network is implied   PinY depends on EndY. This creates intercell relationships or cell dependencies. the PinY cell is recalculated.X1 changes and forces EndY and PinY to recalculate Within the formula of a cell can be references to other cells. which depends on Sheet. Sheet. EndY.2!Connections. Note: The Visio product engine does not recalculate all cells whenever a shape changes. PinY depends on BeginY and EndY. 138 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.X1. when the value of the connection point changes. If the value of the EndY cell changes.2. the value of the EndY cell is recalculated. depends on a connection point in Sheet. These dependencies are implied by the cell names used in the formulas.Y1)) In this example. Volume 3: Programming with the Visio Object Model 138 . In the slide. All rights reserved. 139 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. In these examples the final result of the User-defined or Scratch cell is irrelevant. the first example runs an add-on whenever the trigger cell changes. However. DependsOn creates a cell reference dependency on the cells specified in the list of trigger cells. the developer’s use of DependsOn is not limited to these types of examples. you can force cell dependencies by using the DependsOn function. Volume 3: Programming with the Visio Object Model 139 . The function always returns FALSE (the value 0) and thus has no effect on the final value of the cell when used in this fashion. The second example will reset “Cell” to some formula or value whenever a trigger cell changes. A typical use of the DependsOn function is to cause some action to occur whenever a cell’s value changes.Force Dependencies with DependsOn Force Dependencies with DependsOn  Force cell dependencies by using the DependsOn function  Creates a cell reference dependency on the cells specified in the list of trigger cells  Typically used in a User-defined or Scratch cell   =RunAddon("string") + DependsOn(trigger cell) ‘runs an add-on whenever the trigger cell changes =Setf("Cell".formula) + DependsOn(trigger cell) 'resets “Cell” to some formula or value whenever the trigger cell changes In addition to creating intercell dependencies through the use of another cell’s name. Color) =DependsOn(FillForegnd)+Setf(“Prop. you would like the shape data field to hold the current value.Color”. Volume 3: Programming with the Visio Object Model 140 . 140 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Color. Suppose you want to set a shape’s color from the shape data dialog.Color. In these cells place the formulas: =DependsOn(Prop. In addition. All rights reserved. Prop. It is not sufficient to just display the FillForegnd cell in the shape data dialog by referencing it from Prop. A change to Prop.DependsOn Example Here is a more practical example.Color)+Setf(“FillForegnd”. has been created to hold the value to be displayed in the shape data dialog. The second changes the value displayed in the shape data dialog whenever the user changes the shape’s color using other user interface tools. if the user does change the shape’s color through the user interface. A shape’s color is kept in its FillForegnd cell.Prop. but don’t want to interfere with the user’s ability to change a shape’s color using the normal user interface tools.Color would overwrite this formula. Assume that a shape data cell.FillForegnd) The first resets FillForegnd whenever the user changes color though the shape data dialog. The solution lies in creating two User-defined cells. Note that the shape data field is updated. Volume 3: Programming with the Visio Object Model 141 . Note that the shape’s fill color updates. Display the shape data window. 2. 4.Using this method insures the information in each place is the most current. Data > Shape Data Window.vsd. 3. open <install path>\Demos\Vol3\Managing Events\DependsOn Example. Tryit! DependsOn 1. All rights reserved. From your student CD. 141 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Change the shape data value. Note: The Visio product engine allows circular references in situations like this and prevents the cells from being recalculated infinitely. Change the shapes fill color through the user interface. vsd. Example 1 a. Choose drawing page SetAtRef b. Example 2 a. 2. Note that there are 3 examples on 3 separate pages in the drawing. 3. but it gives greater control over what action is to be taken when the cell change occurs. Data >Shape Data Window. open <install path>\Demos\Vol3\Managing Events\SetAtRef Example. c. Note the SetAtRef formulas in the shape’s Width and Height cells. Display the shape data window. The SetAtRef function redirects any changes to the Width and Height cells to go to the corresponding shape data cells. Demonstration: SetAtRef 1. Modify the shape’s Width or Height by using any of the UI tools or by modifying the shape data fields. Volume 3: Programming with the Visio Object Model 142 . Choose drawing page SetAtRefExpr 142 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. d. This example is similar to the DependOn example we looked at earlier except that the cells being controlled are the Width and Height cells.SetAtRef ShapeSheet Function The SetAtRef ShapeSheet function creates a cell dependency just as we saw in the DependsOn example. All rights reserved. From your student CD. Example 3 a. The ShapeSheet formulas are in the Child shape’s PinX and PinY cells. The grid size is defined in User cells. All rights reserved. in this case a 1 inch by 1 inch grid. Choose drawing page Associate without glueing b. and SetAtRefEval together to create a shape that snaps to a fixed grid size. SetAtRefExpr. Example shows use of SetAtRef. View the ShapeSheet to see the formulas. 4. Volume 3: Programming with the Visio Object Model 143 .b. This example uses SetAtRefExpr to force the shape to snap to a custom grid. 143 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. This currently does nothing and has been in the product since its earliest days. or orientation on the page is changed (EventXFMod) The shape is dropped (EventDrop) Multiple shapes are dropped on the page at the same time (EventMultiDrop) You will see an Event cell called TheData. 144 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. These cells can be used to program events triggered when:      The text is changed (TheText) The shape is double-clicked (EventDblClick) The shape’s position. size.Use the ShapeSheet to Manage Events The Event section cells of the ShapeSheet provide the next level of event management for the Visio developer. Volume 3: Programming with the Visio Object Model 144 . However. then code!  However. your solution may require more robust event functionality and easier maintenance  In this case. putting capabilities into the ShapeSheet is preferred to writing code. if you need a more robust and expandable solution.shapes are part of the Visio drawing file. All rights reserved. Volume 3: Programming with the Visio Object Model 145 .Use Formulas Over Code Use Formulas Over Code  Putting formulas into Visio cells is the most fundamental way to incorporate event handling into a Visio solution  Do not put code behind events when putting formulas behind cells suffices  Shapes first. while add-ons are not! 145 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. use an add-on! This completes our discussion of handling events through the ShapeSheet. The ShapeSheet offers a rich set of features and functions that make the development of code behind events unnecessary. Shapes are easily transferred when drawing files are exchanged. But remember . writing event handling code in an add-on may be easier to maintain. As you have seen several times in this class. All rights reserved. Take a look at how Visual Basic and Visual Basic for Applications have helped programmers set up event handlers. 146 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. such as the ShapeAdded event when a shape is added to a Visio document and the Click event of a button on a form when the button is pressed. Volume 3: Programming with the Visio Object Model 146 . It utilizes this event model to allow you to put code behind events. Always keep in mind that Visual Basic for Applications uses the underlying Event Object Model defined in the Visio Type Library to respond to events.Visual Basic for Applications Code Behind Events Visual Basic for Applications Code Behind Events  Events are defined as part of the type library  Objects have events defined for them and an event applies only to specific object types   The ShapeAdded event fires for a page when a shape is added to the page Can use code behind events in Visual Basic Objects have events defined for them. You cannot stop the deletion. when the BeforeSelectionDelete event is triggered. Volume 3: Programming with the Visio Object Model 147 . You cannot programmatically stop the event from occurring. Certain events are only available on particular source objects.Supported Events There are many supported automation events in Visio. you can only respond to the AfterModal event on an Application source object. For example. the selection passed to the event handler is committed to be deleted. All rights reserved. For example. 147 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. One key point about the Before events is that they are just notifications that the event is about to happen. at the document level. the event fires only when a shape is added to that page. the ShapeAdded event will fire any time a shape is added to any page in any open drawing in the application. as many events are sourced by several objects     Page. or at the application level. can be sourced by different objects. The number of events your code will process can be very different depending upon which object you choose as the source object for your event. The ShapeAdded event can be detected at the page level. All rights reserved. Volume 3: Programming with the Visio Object Model 148 . such as the ShapeAdded event.Hierarchical Event Sets Hierarchical Event Sets  Pick the source object that makes the most sense.ShapeAdded Fires when shape added to page Document. For example. If the page object is used as the source object.ShapeAdded Fires when shape added to any page in document Application. 148 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. at the application level. but not when a shape is added to any other page in the application.ShapeAdded Fires when shape added to a document open in application Both the VBA Object Browser and the Developer Reference Help list the events that each object sources Some events. You can determine which objects source an event by using either the Object Browser in Visual Basic for Applications or the Developer Reference help from the Visio Help menu. Visio has implemented a class known as ThisDocument.Built-In Document Events Like other Microsoft Office applications that contain Visual Basic for Applications. 149 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. In the right-hand drop down list box. A large number of events have already been provided. 4. open the Visual Basic for Applications code window. Try it! Add Code Behind Events for ThisDocument 1. In the Project Window. Volume 3: Programming with the Visio Object Model 149 . The Document_ShapeAdded event procedure is created. In a blank drawing. Go back to the Visio drawing and add a shape to the page. right-click ThisDocument and choose View Code. 3. This will trigger the ShapeAdded event and execute the Msgbox statement above. 5. In the code window for ThisDocument. choose Document. which means you have the ability to use the Visual Basic code framework and write your own procedures associated with any of these events. Add the code: Msgbox “Shape added to the document” 6. 2. choose ShapeAdded. in the left-hand drop down list box. Volume 3: Programming with the Visio Object Model 150 .150 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Use the Visual Basic for Applications keyword WithEvents to declare an object variable for the Visio object whose events you want to handle. Demonstration: WithEvents 1. open the Visual Basic for Applications code window.ActivePage at the time of the binding. All rights reserved. Assigning Visio.Page 151 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. this declaration gives the oPage variable the capacity to handle events when bound to a particular instance of a page.Page In addition to the usual access to the page object’s properties and methods. In the General Declarations section of ThisDocument.ActivePage Visual Basic for Applications supports the keyword WithEvents that allows you to set up event handling for any source object.ActivePage to oPage enables oPage to source events for the page represented by Visio.WithEvents Keyword WithEvents Keyword  Can use the “WithEvents” keyword to set up code behind events for any source object  Need to “bind” the WithEvents variable to a live object to get event handling to work  For example Dim WithEvents oPage as Visio. For example: Dim WithEvents oPage as Visio.Page Set oPage = Visio. Volume 3: Programming with the Visio Object Model 151 . 2. add the code: Dim WithEvents oPage as Visio. In a blank drawing. Click the Design Mode button twice to toggle from Design to Run mode. The message box should be displayed each time a shape is added to the page. 3. In the oPage_ShapeAdded event procedure. 6. Add shapes to the new drawing page. add the code: Msgbox “A Shape was added to Page: ” & oPage. add the code: Set oPage = Visio. and back. In the Document_RunModeEntered event procedure.Note that oPage is added to the left-hand drop down list box in the code window and you now have access to the events that a page object can source.Name 5. All rights reserved. 152 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.ActivePage 4. Volume 3: Programming with the Visio Object Model 152 . Move and size the control as needed. add the following code. You can do this by right-clicking and choosing CommandButton_Object > Control Properties. 2. From the Developer tab. All rights reserved. Volume 3: Programming with the Visio Object Model 153 . The drawing must be in Run Mode for the control’s events to fire and allow the user to interact with the controls as she would in a typical Windows application. by using the selection handles. You can do this. Open a Blank Visio drawing. choose Insert and choose a CommandButton. MsgBox “I am a live control!” 153 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Visio has a Design Mode and a Run Mode to allow you to work with the controls. 4. 3. Edit the control by setting its properties. 5. In the Click event for the command button. as with any shape. or by editing the control’s properties from the VBA properties window. In Design Mode you can place controls in the drawing and set their properties. Note that the name of the control has been added to the code window in the left-hand drop down list box. Try it! Add a Control to a Visio Drawing 1.Controls You do have the ability to add controls to your Visio drawing. Volume 3: Programming with the Visio Object Model 154 . 154 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved.6. Put the drawing in Run Mode (Developer tab and toggle the Developer Mode switch) and click the button. one or more of the Before events will fire after the Query event has fired Query events triggered only by actions from the UI – not through automation Query events give you a way to cancel the event action before it occurs. you would include the QueryCancelSelectionDelete event in your event sink. Here are some of the Query events that Visio provides:  QueryCancelConvertToGroup  QueryCancelDocumentClose  QueryCancelMasterDelete  QueryCancelPageDelete  QueryCancelSelectionDelete  QueryCancelUngroup  QueryCancelQuit 155  QueryCancelWindowClose Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Once you sign up for this event. Then.Query Events Query Events  Query events give you a way to cancel the event action before it occurs  If any event handler returns True. Query events are triggered only by actions from the UI – not through automation. you can add code to respond to it. the action will be performed   In most cases. if a user selects a shape on the page. if you have shapes in your custom solution that you do not want the user to delete from the page. For example. the operation is canceled  If all handlers return False (don't cancel). you can cancel the delete action. All rights reserved. and notify the user. Volume 3: Programming with the Visio Object Model 155 . and presses the delete key to delete it. 156 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 156 . All rights reserved. the QueryCancelSelectionDelete event is called. the events are scoped to the page QueryCancelSelectionDelete True (Cancel) False (Don’t Cancel) SelectionDeleteCancelled Shape is not deleted. BeforeSelectionDelete & BeforeShapeDelete Shape is deleted. This time. Volume 3: Programming with the Visio Object Model 157 . From the Quick Access Toolbar. Open the Visual Basic Editor and review the code. as it occurs in Visio. choose Undo (or use the shortcut. 3. to cancel the deletion. Repeat step 5. All rights reserved.vsd 2. 7. and the BeforeSelectionDelete and BeforeShapeDelete fire. Select one of the shapes and click the command button. Open <install folder>\Demos\Vol3\Managing Events\Query Events. and press the delete key on your keyboard. Select another shape on the page. Note: Try it! Query Events 1.Query Events (Continued) Query Events (Continued)  In this example. 4.Delete method. This is the event sequence for the QueryCancelSelectionDelete event. The Before events fire if the Query event is not cancelled. but choose the No button on the message box for a different result. 6. 157 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Click the Yes button on the message box. This calls a simple Selection. Ctrl-Z). 5. which may cause the value of the cell to change again. and this can cause additional events to fire. Was the event caused by user or by some other event handler? This situation can cause loops responding to self-caused events. Sometimes your event handler modifies the drawing. This causes another CellChanged event. your program can distinguish events it caused from those it did not cause  Either the MarkerEvent event context string or sequence number can be used to correlate QueueMarkerEvent calls with MarkerEvent events Marker events may be used to ignore events caused by other events. a client program causes the MarkerEvent to fire by invoking the QueueMarkerEvent method. 158 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. The MarkerEvent passes both the context string and sequence number to the MarkerEvent. Either the context string or sequence number can be used to correlate QueueMarkerEvent calls with MarkerEvent events. event handler. All rights reserved. Unlike other events that Visio fires. Volume 3: Programming with the Visio Object Model 158 . This way.Marker Events Marker Events  Sometimes your event handler modifies the drawing  This can cause additional events to fire  Was event caused by user or by some other event handler?  Can cause loops responding to self-caused events  By using the MarkerEvent event in conjunction with the QueueMarkerEvent method. your program can distinguish events it caused. The classic example is when the CellChanged event resets the value of cell. from those it did not cause. You need to be able to distinguish between the original event and those that are generated by the event manager. vsd. see the sample file. and search the Visio Developer Reference’s Automation section for the MarkerEvent event and the QueueMarkerEvent method.For more information on Marker Events. 159 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Marker Events. Volume 3: Programming with the Visio Object Model 159 . All rights reserved. When EnterScope fires. see the files Undo Scope I. These methods start and end a transaction for Visio’s Application object. All rights reserved.vsd in the Demos student files.vsd and Undo Scope II. This textual description is then accessible in the MoreInfo argument of the VisEventProc. you should call the EndUndoScope method as soon as you are finished with the actions that comprise the scope. Volume 3: Programming with the Visio Object Model 160 . Together. these methods and events can be used to produce results similar to using Marker events. For more information on Scoping methods. These methods in turn cause the event procedures EnterScope and ExitScope to fire. 160 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. it records extra information in the EventInfo property of the Application object. Note: If you call the BeginUndoScope method.Scoping Methods Scope Events  Visio also provides the scoping methods BeginUndoScope and EndUndoScope to set a scope range  These cause the event procedures EnterScope and ExitScope to fire  Together these can be used to produce results similar to using marker events  Wrap your operations with these scope methods to know whether the events you receive are the result of action that you initiated Visio also provides scoping methods BeginUndoScope and EndUndoScope to set a scope range. Lab 3. All rights reserved.5: Create a Shape Area Calculator Points to Consider Use ActivePage for your page reference. Volume 3: Programming with the Visio Object Model 161 . Make sure the area that you add to the total is for shapes only. 161 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. This might be useful when debugging. 4. To start Visio without automation events and without VBA: 1. However. This works fine when you are through with development and are ready to distribute your solution. Volume 3: Programming with the Visio Object Model 162 . 5.EventsEnabled property. It is sometimes necessary to build a model to contain run-time data to support your drawing. and then restart Visio. Enter the Trust Center (File > Options > Trust Center > Trust Center Settings…) Click Macro Settings. Click to select the Disable all Application Add-ins check box. Click Add-ins. 7. Exit Visio. It can be done through the Trust Center or through the object model by setting the Application. But how does this model get reconstructed when a drawing is closed and then reopened? The DocumentOpened event can be used to make data persist. 162 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. it can be a nuisance during the development process to always be opening and closing the drawing in order to reinitialize data. Start Visio normally. 2. 6.Other Considerations You can actually shut event handling down altogether. Click OK. 3. All rights reserved. and then click Disable all macros without notification. it is much easier to initialize your run-time data during the development process by just switching to Design Mode and then back to Run Mode. 163 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Instead of DocumentOpened. Volume 3: Programming with the Visio Object Model 163 . However. All rights reserved. use RunModeEntered to initialize run-time data. When a document is opened. both the DocumentOpened and the RunModeEntered events fire. Set up event management for any source object. ThisDocument 3. Questions 1. What does the WithEvents keyword allow you to do? Answers 1. Here are some questions based on the material you just covered. All rights reserved. 164 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. 2. Under what circumstances would you want to use Automation event handling over ShapeSheet event handling? 2. by utilizing ShapeSheet event section cells. Volume 3: Programming with the Visio Object Model 164 . Automation event handling is preferred when a more robust solution is required. beyond what can be accomplished in the ShapeSheet.Review: Managing Events In this module you have seen how to handle events in Visio by using simple cell dependency techniques in the ShapeSheet. What is the name of Visio’s pre-defined base class? 3. and by using the WithEvents keyword in Visual Basic for Applications. The GraphicItem and GraphicItems objects are new for Visio 2007.Automating Data Graphics In this module we will take an in-depth look at data graphics. Note: Modifications made using the Data Graphics within the ribbon will override any manual modifications made to the grouped shape. Module Objectives After completing this module you will be able to:  Work with data graphics with the Visio user interface to add text and data bar callouts  Understand how data graphics are managed by Visio and where information about them exists in the Visio object model  Understand key ShapeSheet cells required by data graphics  Customize data graphics with the Visio user interface to add additional graphic items to data graphics 165 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. such as its position. Data graphics and data graphic items are maintained as masters in the Visio object model (albeit hidden except through the Drawing Explorer window). most easily by copying and modifying existing data graphic items. the data graphic master and the shape are grouped. The Shape object has a DataGraphic property that holds the reference to the data graphic applied to the shape. When these masters are modified the changes are then reflected throughout the drawing just as when a master is modified in the Document Stencil. and the GraphicsItems object is a collection of the individual items that make up the data graphic. Therefore. Volume 3: Programming with the Visio Object Model 165 . There are several built in text and data bar callouts as well as several built in icon sets. These callouts and icon sets can be modified and new ones can be created. Data graphics can be customized. All rights reserved. When a data graphic is applied to the shape. The GraphicsItems collection has been added as a property to the Master object. The GraphicItem holds the detailed information about a data graphic item. when working with data graphics you are working with Visio master objects. The implementation of data graphics beginning with Visio 2007 primarily utilizes the existing environment and objects of Visio 2003. You can then work with the elements of the group just as in previous versions of Visio or you can modify the data graphics within the Data tab of the ribbon. Volume 3: Programming with the Visio Object Model 166 . Modify data graphic items to fine tune their behavior within the drawing environment  Create icon sets  Customize and manage data graphics with automation code  Manage data graphics in the drawing environment by making data graphics available for new drawings 166 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Where appropriate. methods. Text. data-bar. These will be covered as they are needed. 167 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. formatting. The data can be refreshed from the external source and the graphics can update automatically based on the values stored in the data. there are bits of sample code sprinkled throughout this lesson which illustrate how to use these features programmatically. and communicate status. and icon set callouts and use color-by-value to visualize data  Create new text. and properties related to creating and managing data graphics in Visio. and graphics are combined to help users identify issues. Data Graphics lets you present information in a concise. properties.Lesson 1: Data Graphics Concepts Microsoft Visio offers tools for visualizing information. This lesson covers that full range of options for creating and customizing Data Graphics. and icon-set callouts  Manage Data Graphics objects in a document  Go beyond the basics and customize your own data graphic items Overview of Objects / Methods / Properties Included in this section is a description of the objects. geometry. Data can be connected from external sources and linked to individual shapes. and methods that come into play when developing solutions with data graphics. Lesson Objectives After completing this lesson you will be able to:  Create new data graphics and customize existing data graphics  Apply text. understandable format. Volume 3: Programming with the Visio Object Model 167 . illustrate patterns in data. All rights reserved. Data Graphics can be expressed in many different ways to give the user a wide variety of options for visualizing his data. A variety of graphics can be applied to the shapes to display information about the data they contain. There are other objects. data-bar. The relationship of the data graphic objects to other portions of the Visio object model is shown in the graphic below. Methods GraphicItem object GetExpression SetExpression Description Returns the current expression for the primary key column corresponding to the specified field. Volume 3: Programming with the Visio Object Model 168 . against which shape data is evaluated. Sets the value of the expression string that is part of a GraphicItem object's rule. A GraphicItems collection of these make up a single Data Graphic which is held in Visio in the form of a hidden Master on a stencil.Data Graphics A GraphicItem is responsible for a single adornment such as a data bar or text callout shown on a Data Graphic. Master object DataGraphicDelete Description Deletes the Master object of type visTypeDataGraphic from the Masters collection of the document. The master is of type visTypeDataGraphic. All rights reserved. GraphicItems object AddCopy Description Adds a copy of a GraphicItem object to the GraphicItems collection. Masters object AddEx Description Adds a master of the specified VisMasterTypes object to the 168 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Description See GraphicItem object. All rights reserved. For example.Masters collection. Volume 3: Programming with the Visio Object Model 169 . If set to True. the name you want to apply to a graphic item. or whether to apply the GraphicItem object's own HorizontalPosition setting and Vertical Position setting (when set to False). hides the text of the primary shape when a data graphic master is applied. Description Determines whether the data graphic is visible in the Data Graphics task pane. Gets or sets an expression that stores extra data needed for your program. as VisGraphicPositionHorizontal. as VisGraphicPositionVertical. The default is False. Not used by Visio. or the Shape object. the Selection object. Gets or sets the vertical position of the graphic item relative to a container or shape. as VisGraphicPositionRelativeTo. Gets or sets whether a GraphicItem object inherits the DataGraphicHorizontalPosition property setting and DataGraphicVerticalPosition property setting of the data graphic master to which it belongs (when set to True). Gets or sets whether the graphic item is positioned relative to a container or to a primary shape. based on the 169 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Properties GraphicItem object DataGraphic HorizontalPosition PositionRelativeTo Tag UseDataGraphicPosition VerticalPosition GraphicItems object DataGraphic Master object DataGraphicHidden DataGraphicHidesText DataGraphicHorizontalPosition Description Returns the Master object of type visTypeDataGraphic that is the parent of the GraphicItem object. the GraphicItems collection. Gets or sets the horizontal position of a data graphic relative to the shape it is applied to. Gets or sets the horizontal position of a graphic item relative to a container or shape. DataGraphicShowBorder DataGraphicVerticalPosition GraphicItems specified VisGraphicPositionHorizontal value. To modify any data graphic. or that occupy the same position as the data graphic of which they are a part. right-click the data graphic and choose Edit Data Graphic… 170 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Gets or sets the vertical position of a data graphic relative to the shape it is applied to. All rights reserved. Returns the GraphicItems collection of the Master object. Read-only. Creating Data Graphics Masters Data graphics can be added to a drawing at any time. Within the task pane completely new data graphics can be created using the command New Data Graphic. To create a data graphic from an existing data graphic. Basics of creating a Data Graphics Master A new data graphic can be created easily using the Visio interface that is presented in the Data tab (Data > Data Graphics). right-click the data graphic and choose Duplicate. Gets or sets whether a border appears around GraphicItem objects whose UseDataGraphicPosition property is set to True. Volume 3: Programming with the Visio Object Model 170 . They may already be part of a drawing if the template used to create the drawing contained data graphics or if shapes dropped on a page had a data graphic associated with them. Data graphics can be created from scratch or can be copied from existing data graphics and then modified. based on the specified VisGraphicPositionVertical value. All rights reserved. Display the Document Stencil and note which masters are displayed.vsd 2.Try it! 1. 171 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 171 . From the Samples folder open Viewing Data Graphics. Thus recording anything that happens in the data graphics task pane is not possible. Does it show in the Document Stencil? Does it show in the Drawing Explorer? Viewing a data graphics master Once a new data graphic has been created. In Visio use File > Options > Advanced to check the number of Undo levels. that is used to control the display of the master in the stencil window. which shows every master regardless of the Hidden property value. Public Sub AddEx_Example() ‘Create an empty data graphic master Dim vsoMaster As Visio. Set the number to at least 30.vsd in the Sample folder has the following sample code in it for creating a data graphic master. However. Run the macro “MakeAllMastersShow”. Open the VBA window. 3. it can be viewed in the Drawing Explorer window. All masters. Create a new data graphic (Data > Data Graphics > Create New Data Graphic…). Display the Drawing Explorer window and note which masters are displayed. Volume 3: Programming with the Visio Object Model 172 . 5. this property is ignored by the Drawing Explorer. Try it! 1. Run the macro “ListMasters”. Note the data graphics masters in the Document Stencil and then Undo (Ctrl-Z) the results of running the macro to again hide the data graphics masters.3. 4. The file Working with Data Graphics. along with their Hidden property are displayed in the Immediate window. Are they the same? 4. Don’t look for it in the Document Stencil because the data graphics master is “hidden”. All rights reserved. This changes the value of the Hidden property of all masters to False so that they will show in the Document Stencil window. the Hidden property.Master 172 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. There is a property of the master object. 2. Make sure the Immediate window is displayed. Creation with automation Note: When Visio’s macro recorder is turned on the Data Graphics menu is deactivated. Give it a meaningful name that you will recognize. 2. 173 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Run the macro (View > Macros > InterestingMacros.AddEx(visTypeDataGraphic) Debug.Masters. The code for DuplicateDataGraphic is below. 86. Sub DuplicateDataGraphic() 'Copy the data graphic named "DGDisposition" ActiveDocument. These callouts are placed on or next to a shape that contains data. 3. 4. but other shape information and custom expressions can also be displayed. 121 End Sub Creating Data Graphics Items Overview of Data Graphics A data graphic is a collection of data presented in a diagram either as a set of graphical widgets or by formatting shapes that contain data.vsd from the Samples folder. A new master can be seen in the Drawing Explorer window.Print vsoMaster.Set vsoMaster = Visio. Run the macro DuplicateDataGraphic to copy this data graphic. The AddEx method makes it hidden automatically.Masters.ActiveDocument.Name End Sub Try it! 1. 5.Drop _ ActiveDocument. The new data graphic shows in the Data Graphic task pane. The data displayed is typically Shape Data. The empty data graphic also shows in the Data Graphic task pane. referred to as the target shape in this document. The name of the new master is displayed in VBA’s Immediate window.AddEx_Example).Item("DGDisposition"). All rights reserved. Open Working with Data Graphics. but does not show in the Document Stencil. The widgets are known as callouts. Volume 3: Programming with the Visio Object Model 173 .Masters. There is a data graphic called DGDisposition included in this file. as listed in Table 1. Visio provides three types of callouts. These are two separate entities. A fourth way of displaying data in a shape is by using Color by Value. This method applies conditional formatting to the shape itself rather than displaying information in a callout. Volume 3: Programming with the Visio Object Model 174 . such as the amount filled in a progress bar.Note: Don’t confuse the data graphics term callout with the new Callout shapes that are introduced with Visio 2010. Data-bar callouts Display data by modifying some visual aspect of the callout. Icon-set callouts Display data by using icons that appear or disappear based on conditional statements. Table 1. Figure 2. Data Graphic applied to regular shape 174 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Data Graphics callout types Type Description Text callouts Display data as text. data-bar. When you apply a data graphic. and icon-set callouts available with Visio. Data graphic shapes usually appear on top of any existing subshapes that are included in target shapes. Data Graphic applied to pivot node A data graphic consists of the set of callouts and Color by Value rules used to display data on a shape. However. 175 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Visio recognizes a shape as a data graphics callout if the topmost shape in the master contains the userdefined cell User. These are shown in the graphic below. All rights reserved. You apply data graphics in the Data Graphics task pane. once one of these callouts is added to a data graphic it is added to the Masters collection.Figure 3. but a data graphic can consist of many callouts and Color by Value rules. they do not show in the Masters collection of the Drawing Explorer window. As built in callouts. Text callouts and Data bar callouts There are eight built-in text callouts provided with Visio. the target shape becomes a group (if it is not already a group) and the data graphic shapes are added as subshapes of that group. Each shape can have only one data graphic applied at a time. a data graphic is a set of special shapes added to a target shape that contains the data to be displayed. Create Data Graphics Item with the Visio user interface There are many built-in text. More Information: On the drawing page.msvCalloutType. Volume 3: Programming with the Visio Object Model 175 . All rights reserved. 176 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 176 .There are eleven built-in data bar callouts in Visio. Most of them are shown in the graphic below. Volume 3: Programming with the Visio Object Model 177 . Once in the Masters collection of the drawing they can be edited and renamed to form a customized callout. 8. 2. In the Drawing Explorer window click the Text callout and change its name to My Text callout. they show in the Masters collection in the Drawing Explorer window. Once they are added. Under Details set Label to “Width”. Right click My Text callout and choose Edit Master shape. Create a new blank drawing. 4. Select new Item. Try it! 1. For Data field: choose More Fields… and then select Geometry and Width. All rights reserved. 12. Select the Text callout. 5. For Displayed as: choose Text. 3. Draw a rectangle and apply the data graphic to it. 10. Moving the shape should do it or reapply the data graphic).These callouts can be added to any data graphic. 11. 177 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. The New Data Graphic dialog is displayed. Data Graphic and Text callout. Change the line color and the text color in the master. Under Details > Value Format choose the browse button and then General and check Show Units. The New Text dialog is displayed. Close the master editing window. 7. Working with Text callouts and Data bar callouts are very similar. Close the dialog. In the Drawing Explorer note that two new masters are added. It will display the shape’s width. Create a new data graphic (Data > Data Graphics > Create New Data Graphic…). (Note: you may have to force a redraw in the drawing for the results to be seen. 9. 6. ).msvCalloutField holds the value of the data element being displayed. but don’t rename it. Choose any field for the data then choose Text. If you use one in a data graphic and modify it as was done above. Right click and choose Edit Master Shape. you will see two versions of the callout in the callout list. The first user-defined cell is shown below. The Type field controls the type of data (boolean. string. Close the Edit Data Graphic dialog. Volume 3: Programming with the Visio Object Model 178 . Note that the My Text callout is in the list as well as the original built-in Text callout. Format specifies list elements. The last row Prop. Note that the first seven Prop. In the master drawing window right click the shape and choose Show ShapeSheet.msv… rows correspond to the elements in the Details section of the New Text dialog we saw when editing the data graphic. 16. All rights reserved. Select the My Text callout master in the Masters collection of the Drawing Explorer window. Note: The built-in callouts cannot be changed. The Shape Data rows define the presentation in the Details section of the New Text dialog. In the Data Graphics work area choose Edit Data Graphic and choose New Item. etc. the one you modified and the original built in version. In the same ShapeSheet look at the Shape Data section. 15. Note that the callout type is set to “Text Callout”. 14. list. 178 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.13. It is best to rename a callout if it is being modified so that it can be more easily identified in the callout list. The Label specifies the label displayed. A very important column. Create a new data graphic. such as its Width or a user-defined cell. Put a custom formula in a callout It is easy to modify a data graphic to display Shape Data from a shape. Note that it is very similar to the dialog for a Text Field and it is used in exactly the same way. 4. For this reason. The Custom formula field at the bottom becomes active. Try it! 1. It is also possible to display other information about a shape. not seen in this figure. the Invisible cell should always be set to True to hide these rows from the user. It is even possible to display calculated data that is derived from several data elements. To create and display a custom formula choose More Fields… in the Data field section of the Text or Data bar callout. From here one can create calculated fields and format the data using the Format function. is the Invisible column. Note that there are several other categories and each of them contains several fields that can be chosen. 5. All rights reserved. 2. Note that Visio uses Shape Data rows in callouts in highly specialized ways and that these rows are not intended to be used as standard Shape Data properties. 3. Add a New Item… For Data field choose More Fields… Choose Custom Formula. The following dialog is presented. Enter into the Custom formula field 179 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. In the image below Geometry is chosen as a category and then Width is chosen as the Field name. The real power in this dialog comes from the last Category Custom Formula. Volume 3: Programming with the Visio Object Model 179 . Shape Data rows are used to define the fields to be displayed when editing a data graphic. Visio recognizes a shape as a data graphic through the user-defined cell User.msvCalloutType. Important: The names of the Shape Data rows used to display fields in a callout must begin with Prop. Format is a function that takes a value and formats it based on a formatting string which in this case is the string “0. Add a field to a data graphic In this lesson we will add a new field to an existing data graphic that will be used to control the fill color of the header bar within the data graphic. Width divided by Height is commonly referred to as the aspect ratio. In the New Data Graphic dialog set the Callout position to Left and Above Shape.="Aspect Ratio = "&Format(Width/Height. 9. This says to display a number to one decimal place. Select OK to close the dialogs. Let’s take this formula apart from the inside out. 8. For Displayed as: choose Text and choose callout Heading 3. Draw a rectangle and apply the data graphic. 10. Select OK to close this dialog.msvCalloutProp… 180 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation."0. You can define properties for text callouts or data bars to expose in the Edit Item dialog.0”.0") 6. Volume 3: Programming with the Visio Object Model 180 . 7. Width and Height are references to the shape’s Width and Height cells. “Data Bar” for a data bar callout and “Icon Set” for an Icon set callout. All rights reserved. Resize the rectangle and observe that the aspect ratio value changes. This is set to “Text Callout” or “Heading” for a text callout. On the left side of the formula is the constant string “Aspect Ratio” followed by & which is the concatenation operator for putting strings together. Try it! Start from the data graphic used in the last section to display the aspect ratio in a Heading 3 callout.Format)+2) This formula returns the values 2. Volume 3: Programming with the Visio Object Model 181 .” This will be added automatically. Choose Yes to update My Heading.msvCalloutPropColor. 8. 1. 2. Right-click the shape and choose Show ShapeSheet. In the Drawing Explorer window rename the Heading 3 callout to My Heading.msvCalloutPropColor. Don’t type “Prop. In the Drawing Explorer window right-click My Heading.Prop. and then select the shape and choose Show ShapeSheet. Close the ShapeSheet and close the master drawing window. Close the dialogs for editing the data graphic. 181 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Right-click My Heading and choose Edit Master Shape. 9. You should now see the new row Heading Color and be able to choose between the colors Red. and Blue when used in the FillForegnd cell. 12. 6.  Label = “Heading Color”  Prompt = “List”  Type = 1  Format = “Red. In the ShapeSheet for the My Heading master add a row to the Shape Data section. 5. Set the FillForegnd cell in the Fill Format section to =GUARD(LOOKUP(Prop. Fill in the following cell values for the new row. 10. Force a refresh by changing the Callout to something different and then back again. choose Edit Master Shape. Edit the Data Graphics (Data > Data Graphics > Edit Data Graphic…) by changing the color in the field Heading Color.Blue”  Value = Index(1. and Blue. The changes may not update automatically. Check what has been done so far in the Data Graphics task pane. Edit the data graphic and edit the Text callout and look for the new properties.Format)  Invisible = True Close the ShapeSheet and the master drawing window. 7. 4.msvCalloutPropColor. Below is the result when the color Red is chosen. Green.  Name the row Prop. and 4 which correspond to the colors Red. 3. Green. Choose Yes to update My Heading. 3.Green. All rights reserved.Prop. 11.msvCalloutPropColor. or 4. 4. Sub AddUserCellsForIconSet() 'Add the user-defined cells required for an icon set to the currently 182 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.msvCalloutIconCount tells Visio how many icons the callout supports. A second user-defined cell named User. This cell should have an integer value of 1. or 5. Icon-set callouts are different from text callouts and data-bar callouts because the icon-set callout does not use the data-field value directly. A third user-defined cell named User. depending on a value provided by the Data Graphics feature. the formula evaluates to an integer of 0. Visio recognizes a shape as a data-graphics callout if the topmost shape in the master contains the userdefined cell User.msvCalloutIconNumber receives the formula from Visio that determines which icon to display. In the Edit Icon Set dialog box. Icon set callout user defined cells The code sample below will add the three user-defined cells and set their values. Volume 3: Programming with the Visio Object Model 182 . All rights reserved.msvCalloutType whose value is set to "Icon Set" (quotation marks required). 2.Icon-set callouts You can use existing icon sets or create your own either as Visio geometry or by using image files. you can define a set of conditional statements for icon-set data that determines which icon should be displayed. An icon-set callout is a shape that can display up to five different images. From the conditional statements. This formula evaluates to -1 when none of the user's conditional statements are true. Otherwise. Visio creates a single ShapeSheet formula that returns a number that corresponds to a particular icon. Figure 4. 3. 3. 1. 2. vsd 2. Volume 3: Programming with the Visio Object Model 183 .msvCalloutIconNumber".Cells("user. "msvCalloutType".CellExists("User.Selection.msvCalloutIconCount").msvCalloutIconNumber"). visTagDefault If Not (. If Not (. don't add it again. fExistsLocally)) _ Then .'selected shape If ActiveWindow.Selection(1) 'Check to see if the cell already exists. "msvCalloutIconCount". fExistsLocally)) _ Then .CellExists("User.Count = 0 Then MsgBox "Select a shape before using this macro" Exit Sub End If Dim fExistsLocally As Boolean fExistsLocally = False With ActiveWindow. Select the shape just created and run the macro AddUserCellsForIconSet 183 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. 3. fExistsLocally)) _ Then .AddNamedRow visSectionUser. Use the drawing tools to create a shape on the page. _ visTagDefault 'Set the values into the cells .Formula = """Icon Set""" .CellExists("User. If so. Open from the Samples folder the file Working with Data Graphics.Result(visNumber) = 0 End With End Sub Try it! 1.msvCalloutType".Result(visNumber) = 5 .msvCalloutIconCount". "msvCalloutIconNumber".msvCalloutType").AddNamedRow visSectionUser.AddNamedRow visSectionUser.Cells("user. _ visTagDefault If Not (.Cells("user. All rights reserved. Table 2. 3. 2. Icon set callout geometry section The NoShow cell in each geometry section controls the visibility of the section. and 4 (displaying the numbers 1. you should hide the callout shape when User. Check the ShapeSheet to verify that the user cells were added 5. All rights reserved.4. and you can show or hide the geometry in those subshapes independently. and 5). you must hide all of its geometry. Table 2 lists the complete formulas for the NoShow cells. A shape can have multiple geometry sections in it. To hide a shape completely. Similarly. Figure 6.msvCalloutIconNumber cell. Using geometry A common way to draw an icon is by using shape geometry. depending on the value you set in the User.msvCalloutIconNumber is -1. Figure 6 shows a geometry section. Figure 5 provides an example of an icon-set callout that has two geometry sections. although it would be possible to use this state to display another graphic. and you can show or hide each section independently. The square is shown for icon values 1 and 3 (displaying the numbers 2 and 4). Figure 5. and images. Volume 3: Programming with the Visio Object Model 184 . text. Icon set callout geometry example The circle is shown for icon values 0. a shape can be a group containing additional subshapes. Icon set callout NoShow formulas Cell Formula 184 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Running this macro again on this same shape will still work because the macro checks to see if the cells already exist before attempting to add them. By convention. User. Put the userdefined cells for the icon set into the group shape.User. You can perform these manipulations either in Visio or in another graphics editor. draw a rectangle to the final callout size you want. When working with images.msvCalloutIconNumber=0. and lock its aspect ratio.NoSh ow IF(OR(User. Resize the image strip until it is exactly 5 times the width of the rectangle (or a different multiple if there are fewer icons in the set). Volume 3: Programming with the Visio Object Model 185 .msvCallout IconNumber=3).TRUE) Geometry2.User. such as a bitmap or a metafile.TRUE) Note that when User. All rights reserved. Figure 7. Icon set callout image example To create this icon set. it is easier if all the pictures are the same size.msvCalloutIconNumber=1.NoSh ow IF(OR(User. the images should be combined into an image strip—a single picture that contains the images arranged in an evenly spaced row. In this case.FALSE.FALSE. the callout shape must be a group shape that contains the image or images as subshapes.msvCalloutIconNumber is -1.msvCallout IconNumber=2. Then add the image strip to the page.msvCalloutIconNumber cell. Figure 7 shows an example of an icon set based on images. You can show or hide the images by specifying the value in the group's User. such as Paint.Geometry1. Also. both formulas evaluate to TRUE and no geometry is shown. 185 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.msvCalloutIconNumber=4). Convert the rectangle to a group and add the required user-defined cells for the icon set. Using image files Another way to show an icon is by using a picture image. Volume 3: Programming with the Visio Object Model 186 . and the rest is cropped out of view. Icon set callout image example: Step 2 The final step is to tie the image strip to the group's icon number. This is the group shape that contains the images. You can delete or permanently hide the rectangle's geometry section. crop the image strip down to the width of the rectangle. Figure 10. The formula in the ImgOffsetX cell refers to Sheet. All rights reserved. In the ShapeSheet of the image strip. Only a portion of the picture is visible in the shape. This cell moves the image based on the icon value of the group. Icon set callout Foreign Image Info section 186 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Icon set callout image example: Step 1 Using the Crop tool. Figure 9.Figure 8.5. the Foreign Image Info section controls the size and position of the picture. Align the image strip on top of the rectangle and add it to its group. The ImgOffsetX cell controls what portion of the image is seen. The new Icon Set is displayed along with the other icon sets. Return a data graphic assigned to a shape Through automation you can get the data graphic assigned to a shape.vsd from the Samples folder. Apply a data graphic to a shape You can also set the data graphic for a shape through code. Select a shape that has a data graphic assigned to it and run the macro WhichDataGraphicAssigned from the Tools menu. View the code. 3. For bitmaps. the image quality may degrade. those created as enhanced metafiles. 4.vsd. the icons will have a white border around the image. Try it! 1. Open the file Working with Data Graphics. Try it! 1. 2.vsd from the Samples folder. The data graphic assigned to the shape is displayed in a message box. if the image does not completely fill the frame. the icon doesn’t look so good. 3. 187 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. An example of creating the icon set described above is covered in this drawing on page “The making of an icon set”. Second. then the background must be of some color (let’s assume white). All rights reserved.vsd in the Samples folder there is VBA code for the following. If the user puts a color on the page other than white. Volume 3: Programming with the Visio Object Model 187 . Try it! 1. Edit a data graphic and add a new graphic item.Note: There are significant differences when working with image strips created as bitmaps vs. The information is in the DataGraphic property of the shape. 2. But what about doing some these same tasks or accessing the information about data graphics and graphic items through automation? In the file Working with Data Graphics. Using enhanced metafiles instead of bitmaps for the image strip creates a much better looking icon set. Open Working with Data Graphics. Choose the icon set (its name is not displayed) in the New Icon Set dialog. Open Working with Data Graphics. Working with data graphics using automation Data graphics can be managed through the Visio user interface. Image strips created as enhanced metafiles have a transparent region around the shape and the image quality does not degrade. When these images are applied in an icon set. Go to the page named Data Graphics.2. and 3) close the copy. 2. This runs the procedure SetDGToNextInList which finds the current data graphic assigned to the shape and then searches all of the data graphics in the document to find the next data graphic. Interrogate Graphic Items You can interrogate properties for graphic items. This will write information about the data graphic and each of the graphic items that make up the data graphic to VBA’s Immediate window. Open Working with Data Graphics. View the code. It then assigns this data graphic to the shape. 4. 6. This runs the procedure SetDGToNextHorizontalPosition which increments the horizontal position of the data graphic. Try it! 1. All rights reserved. View the code. Set information into a data graphic item 8. Select a shape that has a data graphic assigned to it. This requires that 1) the master be Opened (which creates a copy). Set information into a data graphic 5. Go to the page named Data Graphics. 7. On close the changes are copied back to the master and the update happens in the drawing. Note: Editing a data graphic in the Data Graphic task pane is equivalent to editing the master in the Drawing Explorer window. 3. Right-click one of the shapes and choose Set to next DG. View the code. Run the macro ListDataGraphic. 3. 188 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. 2) edits are made to the copy. To do the equivalent operation in code you must edit the master. Right click one of the shapes and choose SetDGToNextHorizontalPosition. On the page named Data Graphics make sure there is a data graphic assigned to one of the shapes.vsd from the Samples folder. Volume 3: Programming with the Visio Object Model 188 . There is also a procedure SetDGToNextVerticalPosition. 11. This is equivalent to editing the graphic item and checking the checkbox Use default position. edit the copy. The details fields come from the Shape Data rows in the master. Callout Name For text callouts and data bars. 10. 189 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. This macro steps through each of the graphic items for the data graphic assigned to the shape and sets the property UseDataGraphicPosition to True. We therefore need to open the master. editing a graphic item is equivalent to editing a master. Guidelines for constructing data graphic callout shapes Use of common design practices helps ensure consistency and ease of use for callout shapes. View the code Note: Like editing a data graphic. Icon sets are only displayed graphically. Setting the Shape Data cells through automation is equivalent to opening the Edit Item dialog and changing details values. Edit this data graphic and edit the item within it so that it does NOT use the default position of the data graphic (uncheck the box Use default position) and then reposition the Text callout or Data Bar callout. the name assigned to the callout master is the name displayed in the Callout drop-down list in the Edit Item dialog. Volume 3: Programming with the Visio Object Model 189 . and close the master. Get or set the property DataGraphicHidesText. Select the shape that has the data graphic just modified and run the macro ResetGraphicItemsToDefaultPosition. Get or set the property DataGraphicShowBorder. Set data field as in the Edit Item dialog. Other things to do with a data graphic There are two check boxes in the Edit Data Graphic dialog   Show border around items at default position. Use the SetExpression method of the GraphicItem. Hide shape text when data graphic is applied. All rights reserved. Other things to do with a data graphic item   Set details as in the Edit Item dialog.9. place GUARD expressions in the Width cell or in the Height cell in the callout. To help your users understand how your callout displays information. both the width and height remain fixed. as shown in Figure 12. The master shape also appears in the Data Graphics viewing area as part of the data graphic thumbnails. includes a margin to inset the geometry of the callout. All rights reserved. but the Height cell value is determined by the callout. This may make the geometry or graphical images in the callouts appear crowded. In general. choose an appropriate sample data value for the shape. discussed previously. in the first example. Controlling callout size Visio applies special formulas to your callout shape to control its size and position relative to the parent shape in the drawing. To specify a fixed size or a size controlled by logic within the callout. Also in Figure 11. Callout sizing examples Controlling margins Callout shapes are often stacked together or aligned along the edges of the parent shape. or in both cells. Figure 12. Volume 3: Programming with the Visio Object Model 190 . the Width cell value is matched to the width of the parent shape. in the second example. Figure 11. Callout margin example Geometry sections 190 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. In Figure 11.Sample Values Visio uses the callout master shape as a thumbnail in the Edit Item dialog. these formulas size the callout to match the width and height of the parent shape. It is often helpful to build a margin into the callout shape's geometry or image strip. The icon set example. Volume 3: Programming with the Visio Object Model 191 . There are many scenarios where it is desirable to maintain separate formatting for the shapes and the callouts. a user-defined cell named Margin was created to specify the spacing to be used.In this example. Visio automatically pushes that formatting to all sub-shapes as well. This is an example of changing the text size in callouts. The default text size for the flowchart shapes and the text callouts is 8 points. You can do this by multiplying the fixed dimension by the value of the DropOnPageScale cell. The data graphic has two text callouts displaying the Cost and Duration shape data fields. Figure 13. Visio 191 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. However. a data graphic is applied to the three process steps. Callout margin example user-defined section Protection cells When you design callout shapes. Data Graphics callouts are designed to prevent this automatic propagation. you must decide what you want to allow your users to manipulate in the callout after they apply it to a parent shape. In the flowchart above. Normally when you apply formatting to a group shape. When you use fixed dimensions in a shape. include a factor for the page scale so that the shape is usable in scaled drawings. The Protection section in the ShapeSheet enables you to lock down specific behaviors or properties in the callout shape. What happens if we do a Select All and change the text size to 12 points? The flowchart shape text has increased in size. but the callout text has not. just those pushed from groups. Volume 3: Programming with the Visio Object Model 192 . This is controlled by the group selection behavior property found in the Developer > Behavior dialog. Data Graphics callouts work this way. If the Selection property is set to Group Only. You can directly select (or sub-select) a shape and still format it. All rights reserved. the master callout can be edited to effect global callout changes. Cell Explanation LockAspect Useful for icon sets if the Width cell and the Height cell are not protected with the Guard function. The following table shows Protection section cells useful for controlling callout behavior. Not all Visio shapes allow selection of sub-shapes. As was shown earlier.2007 introduced a new protection on shapes to prevent group formatting from propagating to subshapes. LockFormat Prevents users from making formatting changes to the callout. 192 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. you will have to right click the shape and choose Group > Open Group to make any formatting changes. LockCustProp Prevents users from deleting Shape Data properties from the callout. Group formatting protection does not prevent all formatting changes on a shape . each callout should be a single shape. the datagraphics shapes are far more complex than the shapes that constitute the drawing itself. but try to keep the total number of shapes to a minimum. memory. Another performance factor is the time required for Visio to add new ShapeSheet cells to the callout when you use it in a drawing. Callout user-defined cells used by data graphics Row Value User. Performance. This affects the performance of the document. and file size is the number of shapes per callout. Ideally. If an average callout shape includes two subshapes and an average data graphic includes three callouts. For some drawing types.LockGroup Prevents users from deleting subshapes that make up the callout. If you must combine multiple callout shapes into a group. and file size Because data-graphics callouts are Visio shapes and can contain complex graphics.visDGCalloutItem blank 193 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. You can individually show or hide each geometry section based on the configuration of the callout. Visio adds nine shapes to the document every time you apply a data graphic to a target shape. ensure that the group itself is used for its geometry or text. such as flowcharts. avoid creating groups nested inside other groups. LockFromGroupFormat Prevents formatting changes made by users to the target shape from also being applied to the callout. they can significantly affect the size and responsiveness of a Visio drawing. Table 3. Shapes support multiple geometry sections. Also. Including these cells in the callout master shape saves time and file size. memory. All rights reserved. so an additional shape is often not necessary. Table 3 lists named rows that you must add to callout masters. LockThemeColors Prevents color themes from changing the formatting of the callout. Visio generates several additional user-defined cells to implement some of the data graphics behavior in the callout. The most important factor that influences performance. The file size and memory requirements for a drawing that contains data graphics might be an order of magnitude larger than those of a drawing without data graphics. Additional shapes are necessary when a callout needs multiple formats or pieces of text. LockThemeEffects Prevents effect themes from change the formatting of the callout. Direct formatting of the callout shape is still allowed. Volume 3: Programming with the Visio Object Model 193 . Target shape user-defined cells used by data graphics Row Value User.visDGDefaultPos blank User.visDGOldColors blank User. they require Visio to fully compose and lay out the shape text each time the function is evaluated. you can add some of the named rows listed in Table 4 to target masters. Volume 3: Programming with the Visio Object Model 194 .visDGCBVFill blank User. Table 4. you can reduce the time needed to apply data graphics to shapes.visDGStackHeight blank If you design target shapes to work with data graphics.visDGDisplayFormat blank User.msvThemeColors blank User.User. 194 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.msvThemeEffects blank By pre-creating the user-defined cells needed by data graphics. One final performance issue to be aware of is the use of the ShapeSheet functions TEXTWIDTH and TEXTHEIGHT. However. These functions calculate the geometric boundary of shape text—which is useful information for precisely arranging text and geometry together. so use them sparingly.visDGDefaultPos blank User. All rights reserved. These functions are very expensive relative to other ShapeSheet expressions. Then copy the shape and paste it into the other document. but not in the Drawing Explorer. Check the masters collection after pasting the process shape. apply the data graphic to a shape in the current drawing. the masters collection will look something like this:  Bubble callout  Data bar 2 195 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. but the data graphic remains available in the second document. Create a new drawing that has no data graphics in the template. 5. and it copies the callouts used by the data graphic. There shouldn’t be any in the second drawing. As masters. 4. Open a drawing from the Visio Samples. they have a Hidden property that is set to True. 2.Managing Data Graphic Masters Where are they stored and how do you see them? There are a number of built-in data graphics. Try it! 1. 3. Paste it into the second drawing. and icon sets. Look at the Masters in the Drawing Explorer for each drawing. these data graphics. Once assigned to a shape. These do not show anywhere in the user interface except in the data graphics viewing area on the ribbon. File > New > Sample Diagrams > Process Improvement. callouts. For example. Making a data graphic part of a document The built-in data graphics are always included in any Visio document. and icon sets are added to the masters collection of the drawing and can be seen using the Drawing Explorer window. Depending on the shape chosen there may be several masters added. File > New > General > Basic Diagram. This action copies the data graphic definition to the other document. Other data graphics can be added and saved with a document. Add a data graphic to a document To copy a data graphic from one document to another. callouts. All rights reserved. You can then delete the shape from the first document. Volume 3: Programming with the Visio Object Model 195 . In the first drawing select a process shape that has a data graphic applied to it. This prevents them from be displayed in the Document Stencil window. Check the Data Graphic task pane to verify this. Visio also places a copy of the data graphic and any callout masters in the stencil. Open a drawing from the Visio Samples. Make a master with a data graphic already applied. There should be no shapes left on the drawing page. To build a data graphic into a master shape. All rights reserved. This method is useful for diagrams in which data graphics are an integral part of the drawing and in which each shape can use the same data graphic to display information. Make a data graphic part of a template The process above can also be used to add any data graphic to a template. Open the template for editing. you remove the association that the shape had with its previous master. Choose Samples Diagrams and then open Process Improvement. One additional option is to pre-associate a data graphic with a master shape. 8. apply the data graphic to a shape on the page and then drag the shape to a stencil to create a master. Check the Document Stencil. 2. Delete the Process shape from the Document Stencil. so building the data graphic into the template is the best approach. File > New. Check the Masters collection and the Data Graphics task pane. Process  Process 2  Status icons  Text callout 6. Visio makes a new master from this union of shape and data graphic. Within the new document delete the process shape. by doing this. and save the template. The Data Graphics remain. Note that. Drag one of the process shapes that has a data graphic applied to it into the blank stencil 196 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. The Masters collection and the Document Stencil are unchanged meaning that the data graphic is still part of this drawing. Try it! 1. Create a new stencil. Volume 3: Programming with the Visio Object Model 196 . 3. When a drawing is created from the template the data graphic will show in the Data Graphics task pane. More Information: It is not possible to define a data graphic in a central location for use in all documents. 7. The Process shape should be there. add the data graphic. 6. Drag the master from the new stencil into the new basic diagram drawing. The data graphic is there! 8. 5.4. Volume 3: Programming with the Visio Object Model 197 . Hidden masters and removing hidden information Normally. All rights reserved. 197 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Create a new drawing that has no data graphics in the template. Note that it is a group shape and that each of the data graphic items are also members of the group. However. To protect a hidden data graphic (or any master) from removal by the RHI tool. The Remove Hidden Information tool will then ignore this master and NOT remove it. Use the Drawing Explorer to review the shape. create a user-defined cell User. Check the masters collection and the Data Graphic task pane.msvRHIPreventRemoval to the master’s PageSheet and set its value to 1. unused masters can be removed using the Remove Hidden Information tool of Visio. File > New > General > Basic Diagram. Tile the windows so that both windows can be seen. some custom solutions include data graphic masters in the document and the solution depends on these graphics being present. 7. How to add shape data The basic techniques of adding shape data have not changed. The data linking features of Visio automatically add shape data fields for each field in a record being linked to a shape if that shape data field does not already exist in the shape. Lesson Objectives After completing this lesson you will be able to:  Distinguish between Shape Data used to define Data Graphic fields and Shape Data used to store general information within a shape. This data is used to control the graphical output of the shape. although the menus changed with Visio 2007 from Custom Properties to Shape Data. If the data was to be viewed visually. Previously. in addition to serving as the repository of data associated with shapes. consider the timeline shapes that hold information about the timeline in shape data. Shape Data is also used to define fields in data graphic callouts. the shape needed to be programmed to do something with the data.  Understand the relationship of Shape Data and Data Graphics and use Shape Data to define the property fields of text callouts and data bar callouts Shape Data Management With the advent of data graphics and data linking in Visio 2007 the Shape Data section of the ShapeSheet takes on additional responsibilities. 198 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Beginning with Visio 2007.Lesson 2: Related Topics Data Graphics heavily utilizes Visio’s Shape Data features. The custom solution developer must recognize that there while be Shape Data fields created by the end user and also Shape Data fields created for use by Data Graphics. This data could be viewed through the Shape Data window and reports could be generated from it using the Reports tool. As an example. These fields control the display of the prompts in the Edit Item dialog. Volume 3: Programming with the Visio Object Model 198 . it was used mostly as place to store extra data to be associated with a shape. and the Define Shape Data command on the shortcut menu in the Shape Data window is disabled. This cell is available only through the ShapeSheet.msvCalloutField.Define Shape Data dialog The Shape Data dialog still exists with the revised interface of Visio 2010. Note that Visio uses Shape Data rows in callouts in highly specialized ways and that these rows are not intended to be used as standard Shape Data properties. Design the callout to make use of the information in this row in whatever way is desired. A value of TRUE does not prevent a user from changing the value of a shape data item or changing the Shape Data section in the ShapeSheet window. or modify shape data in the user interface using the Define Shape Data dialog box or the shortcut menu for the Shape Data window. It is not displayed in the user interface in the Protection dialog. Effect of LockCustProp cell in Protection section There is a Protection section cell named LockCustProp that affects the user’s ability to add shape data through the user interface. When the cell has a value of True the Define button does not appear in the Shape Data dialog box. Volume 3: Programming with the Visio Object Model 199 . you should set the Invisible cell value in these Shape Data rows to TRUE to hide these rows from the user. Relationship of shape data and data graphics Visio places the data to be displayed in a Shape Data row named Prop. For this reason.   Right-click in the Shape Data window and choose Define Shape Data Right-click a shape (or selection) and choose Data > Shape Data The ShapeSheet Shape Data fields can be created in the ShapeSheet window by adding rows to the Shape Data section and filling in the values for each of the cells in the row. There are a couple of options for viewing the dialog. Shape Data sets Shape Data Sets allow the copying of a group of shape data fields in mass from one shape to another. All rights reserved. delete. Text and Data Bar callout Shape Data cells 199 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Figure 14. This feature is available as a right-click menu of the Shape Data window. This cell determines whether the user can add. msvCalloutField cells written by Visio Cell Value Label Not set by Data Graphics. Type Not set by Data Graphics. not set by Data Graphics. If data field is not a Shape Data property. You can define additional properties for text callouts or data bars to expose in the Edit Item dialog. If data field is a Shape Data property. LangID of target shape. Table 5. not set by Data Graphics. Volume 3: Programming with the Visio Object Model 200 .msvCalloutField row when the callout is used in a data graphic. Invisible Not set by Data Graphics. not set by Data Graphics.Visio puts the following information into cells in the Prop. Ask Not set by Data Graphics. TRUE recommended. 200 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. LangID of Shape Data property. Format of Shape Data property. If data field is a Shape Data property. These properties enable you to configure the callout in special ways. Calendar of Shape Data property. You specify the data field to be shown in the callout when you include the callout in a data graphic. LangID If data field is not a Shape Data property. All rights reserved. Format If data field is not a Shape Data property. Value Reference to data field value. Calendar If data field is a Shape Data property. Label of Shape Data property. Prompt Not set by Data Graphics. Prop. SortKey If data field is not a Shape Data property. If data field is a Shape Data property. TRUE recommended. For List control types. Type Not used. Prompt Control type of property (defined below). semicolon-delimited list of choices. Custom callout property cells written by Visio Cell Value Value Property value. 201 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Custom callout property cells read by Visio Cell Value Label Property label to be displayed in dialog boxes. Invisible Not used by Data Graphics. Volume 3: Programming with the Visio Object Model 201 .You define custom callout properties by creating additional Shape Data rows that have names beginning with the prefix Prop. Format For Field control types. Visio puts the following information back into these cells in the property rows.msvCalloutProp. optional default value for the property. All rights reserved. Custom callout property cells Visio interprets these cells in the property rows in the following ways. Ask Not used. Table 6. Figure 15. For String control types. Table 7. format of data field or empty if field is not a Shape Data property. SortKey For Field control types where data field is a Shape Data property. Calendar For Field control types where data field is a Shape Data property. Other cells might be interpreted in different ways. Calendar of data field. Volume 3: Programming with the Visio Object Model 202 . For Format control types. Visio supports a variety of input controls in the Edit Item dialog. LangID For Field control types where data field is not a Shape Data property. The Prompt cell specifies the control to be displayed. Calendar of data format picture. LangID of target shape. All rights reserved. depending on the control type. Custom callout property control types Control Type Prompt cell value Control used in dialog box String "String" Text box Number "Number" Text box requiring numeric input List "List" Drop-down list box with choices supplied by the Format cell Boolean "Bool" Drop-down list box with yes and no choices Date "Date" Text box with date picker Field "Field" Data-field drop-down list box Data Format "Format" Text box with Data Format button 202 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. LangID of data format picture. Table 8. For Format control types. Label of Shape Data property. LangID of Shape Data property. For Field control types where data field is a Shape Data property. Custom callout property examples Field controls offer the same choice of fields as the data-field drop-down list box. Visio places the formula NA() in the property's Value cell. If you select [Not Used]. 203 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Figure 16. All rights reserved. with the addition of a [Not Used] choice. Volume 3: Programming with the Visio Object Model 203 . you will be able to:  Create a new data graphic item from an existing shape  Add the data graphic item to a new data graphic  Apply the data graphic to a shape  Change the display size of a data graphic item on a shape Exercise 1: Create a Pie Chart data graphic item Scenario You need to include a pie chart in a data graphic.  Lab files needed: o ScheduleBuilder.vss What You Will Learn After completing this lab. Tasks 1. Volume 3: Programming with the Visio Object Model 204 . Create a new blank drawing. All rights reserved. Estimated time to complete this lab: 60 minutes Before You Begin To complete this lab.  Visio 2007 or higher installed and configured. but the standard data bar items do not include a pie chart. you will need:  Participants should have completed the Try This! Sections of this module before completing this lab.6: Data Graphics During this lab.Lab 3. you will create a data graphic item to represent a pie chart and then create two data graphics to test the data bar item. 204 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. You will have to create a new pie chart data bar data graphic item. Open the ShapeSheet for the Pie Chart group shape. not by user choice. Set its value to “Data Bar”. a.Slices. Close the Master editing window and save the changes. They have Theme formulas that reference the different accent colors of the Theme. It has the basic pie chart features needed.msvCalloutField and set the following column values: Label=No Formula 205 Value=0 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Enter a value for each slice. Drag the New Pie Chart shape to the page. There are User-defined cells that calculate normalized values for the cells. It is limited to 5 sections. The New Pie Chart shape should show as a new data bar option to choose from.2. Change the name of Prop. Add a new graphic item of type Data Bar. These User-defined cells are referenced from the group’s subshapes. Edit the New Pie Chart master from the Document Stencil window. The value is “normalized” to be a percentage of the total of the five slices. This is a modified version of the Pie Chart shape from the Charts and Graphs stencil. 3. 7. Note: The shape is “themed”. Volume 3: Programming with the Visio Object Model 205 . Open the stencil from the Labs folder (from the Shapes window More Shapes > Open Stencil and then traverse to the Labs folder and open ScheduleBuilder. All rights reserved. 5. You don’t need to create one from scratch because we’ll start with a variation of an existing Visio Pie Chart shape and turn it into a data bar item. Check if it worked. 6. Open the ShapeSheet for the New Pie Chart group shape. In the Data Graphics task pane create a new Data Graphic. A basic pie chart shape is needed. Browse through some of the subshapes of the group and look at the FillForegnd cells. Turn this shape into a data bar data graphic item by editing the master in the Document Stencil. b. Look at the User-defined section and the Shape Data section.Pie1 to Prop. Add the User-defined cell User. Now you need to set up the fields that are to be displayed on the data graphic by turning the existing shape data fields into data graphic fields. This will be driven from the data graphic.vss. In the Shape Data section delete the row Prop. 4. Note that there are Shape Data cells to contain the values for each slice. Use the RMA commands to set Number of Slices and Slice Sizes.msvCalloutType. Pies. In the User-defined section delete the row User. Delete the Actions section from the ShapeSheet. This is no longer needed. g. Volume 3: Programming with the Visio Object Model 206 . Prop. Close the master window and save the changes.Pie5 to msvCalloutPropField3.Pie4. Set Displayed as: to be Data Bar.Invisible=True c. and msvCalloutPropField5 respectively. Choose a Data field. Select the New Pie Chart graphic item. f. Value. You should see Pie2 through Pie5 in the Details section and the values are displayed as [Not Used].msvCalloutPropField2 and set the following column values: Prompt=”Field” Value=0 Invisible=True d.Pie3. The New Item dialog should look like the following. Check if it worked. Any field will do for the moment so choose More Fields…>Geometry>Width. and Invisible fields the same as msvCalloutPropField2. Change the name of Prop. e. Prop. Set the Prompt. 8. This is no longer needed. Change the name of Prop. msvCalloutPropField4. In the Data Graphics task pane create a new Data Graphic. 206 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved.Pie2 to Prop. From the Immediate Window type: activedocument.Masters("New Pie Chart").9. You can create a macro for this or use the Immediate Window in VBA. Exercise 2: Test the New Pie Chart data graphic item Scenario To test the new graphic item you will link a shape to a row in an external data set and then create a data graphic and apply it to the shape. 207 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Hidden=true The master can still be seen from the Drawing Explorer window. Make the new master graphic item hidden. All rights reserved. Volume 3: Programming with the Visio Object Model 207 . but not from the Document Stencil. 5. 7. Close the master editing window and save the changes. 12. All rights reserved. Set the callout position of the data graphic item to Center and Middle. The Sections data will appear in the External Data window.5 inches. 8. It should now appear in a fixed size of 0. 11. Open the ShapeSheet and set these formulas into the Width and Height cells. Set the Data Field to 9. Specify the Sections worksheet in the Excel file. Choose Data > Data Graphics > Create New Data Graphic . Note that a default data graphic is assigned to the shape. 2. Accept all defaults to finish the wizard. 6. Does the data graphic appear the right size for the shape? By default it scales to the size of the shape.xls from the Labs folder. 4. The data graphic will not update on the shape automatically so apply the None data graphic and then reapply the new data graphic. Rename this data graphic to “DG Pivot” 208 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Apply the data graphic to the shape. This is the number of students in grade 9. From the Drawing Explorer window edit the New Pie Chart master.5 in*DropOnPageScale) Height=Guard(Width) 10. Set the following: Pie2=10 Pie3=11 Pie4=12 Leave Pie5 unchanged. 9. Choose Data > Link Data to Shapes and choose the file ScheduleBuilder. Set Displayed as to Data Bar and set the Style to New Pie Chart. Width=Guard(0. Add a New Item. Draw a rectangle on the page and link it to the first row of data.Tasks 1. 3. Volume 3: Programming with the Visio Object Model 208 . You will use the data graphics just created in the next module. Set the callout position to Right – Bottom. 2. a. Scenario Create a new data graphic based on “DG Pivot” and add a data bar item. 209 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. 8. Draw a rectangle b. You should see something similar to the image below. Set the Displayed as field to Data Bar and set the Style to Data Bar 3. 3.Exercise 3: Add a data bar to the Data Graphic that totals the 9th. 7. 9. Close the Data Graphic dialog. and 12th grade slots for a class section. Link it to a row of data c. Tasks 1. Choose Data > Data Graphics. All rights reserved. Save the drawing. Set the Label to “Total”. Add a New Item. Under Data Fields choose More Fields… and then Custom Formula. Apply the data graphic d. 4. Set the Maximum value to 35. Volume 3: Programming with the Visio Object Model 209 . Edit “DG Section”. 6. Right click the data graphic and choose Duplicate. Create a duplicate of “DG Pivot”. 10th. Rename the new data graphic “DG Section”. 11th. In the Custom formula text field enter ={9}+{10}+{11}+{12} 5. Volume 3: Programming with the Visio Object Model 210 .msdn.aspx 210 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Additional Resources – Data Graphics Building Data Visualization Solutions with Visio 2007 A PowerPoint presentation giving an overview of the features of Visio 2007 from the Visio Developers conference in January.microsoft. All rights reserved. 2006. http://office.com/documents/uk/msdn/download/devcon/Session_D3_Microsoft_Office _Visio_2007_New_Data_Visualisati.com/en-us/visio/HA101829791033. These are just the slides. http://www. No notes are included.msdn.com/eric_rockey/archive/2005/12/14/503483.microsoft.mspx Data Graphics: visualizing data on your diagram A high level review of applying and modifying data graphics http://blogs.aspx Q&A: With Microsoft Office Visio 2007. Every Picture Tells a Richer Story While a picture may be worth a thousand words.com/presspass/features/2006/sep06/09-19visio2007. http://download.com/wmorein/archive/2006/06/15/632742.ppt Demo: Let data tell its story with data graphics An online demo showing the new features of Visio 2007.microsoft.aspx Visio 2007: Customizing Data Graphic Items Creating a custom data graphic item http://blogs. having the right pieces of data associated with that picture can be invaluable to IT professionals and business managers in making better-informed decisions. microsoft.aspx Custom Formulas in Data Graphics Nice example of creating a custom formula in a data graphic http://blogs.com/visio/archive/2007/03/06/custom-formulas-in-data-graphics.microsoft.com/en-us/library/aa468596. http://blogs.aspx 211 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.msdn.aspx About Displaying Data Graphically http://msdn2.com/en-us/library/aa342323. All rights reserved.com/visio/archive/2007/01/02/customizing-data-graphics.msdn. http://blogs. Volume 3: Programming with the Visio Object Model 211 .com/wmorein/archive/2006/07/14/665997.Visio 2007: More on Customizing Data Graphic Items: Icon Sets Shows constructing and icon set including what is required in the ShapeSheet.msdn. Several good examples and specific how to do it! http://msdn2.aspx Building Custom Data Graphics for Visio 2007 A very good article by Mark Nelson on creating and customizing data graphics. The author also tells you how to solve the problem.aspx Customizing Data Graphics Provides good insight on why trying to apply formats to data graphics through the user interface gives unexpected results. What are the four types of data graphic items that can be displayed in a data graphic? 5. True or False. a custom formula can be displayed in a data graphic item. which method is used to set the custom formula? 8. What two places in the Visio drawing environment can you see a data graphic? 3. What new objects are added to the Visio object model to support data graphics? 2. What is a way to make a data graphic always be part of a drawing? 14. 4. A good way to learn about automating data graphics is to use the macro recorder. Additional fields can be added to a callout by adding rows to Shape Data. Data graphic masters that are callouts have what user-defined cell to describe what type of callout they are. All rights reserved.Review: Automating Data Graphics Questions 1. Since Shape Data is used to create data graphics fields. How can you add a data graphic from one drawing to another drawing? 15. What distinguishes a data graphic master from other masters in the masters collection? 6. True or False. Volume 3: Programming with the Visio Object Model 212 . Instead of referencing just a Shape Data row. how do we prevent these fields from being displayed in the Shape Data window? 212 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. What property of the shape is set to assign a data graphic? 11. Data graphics are not very expensive in terms of size and performance in a drawing. What three user-defined cells are required for the icon set callout? 10. You can edit the data graphic master directly using automation. 13. 7. True or False. What naming convention is required to enable the data in these rows to be displayed as “Details” in the Edit Item dialog? 9. In the object model. 12. Then it will exist in all drawings created from the template. False. 8. The macro recorder will not work with data graphics. 6. When applied to many shapes in a drawing you can quickly double. 10. The Data Graphic task pane and the Drawing Explorer window 3. The DataGraphic property. 13. “Data Bar”. If the macro recorder is started. This copy can then be modified and when the master is closed the changes are pushed back to the master. False. or “Icon Set”. Data graphics can be very expensive because a data graphic can be made up of several masters. or more the size of the drawing. The data graphics master is hidden so that it does not show in the Document Stencil and the master type is visTypeDataGraphic. Copy a shape that has the data graphic applied and then delete the shape. User. 4. which creates a copy.msvCalloutType. 14. Volume 3: Programming with the Visio Object Model 213 . User. 11. Text callout. All rights reserved. the Data Graphics task pane is immediately closed and cannot be opened until the macro recorder is turned off. 213 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. icon set callout. 7. The Shape Data row name must start with msvCalloutProp… 9. 15. Shape Data rows have an Invisible cell which is set to True in the ShapeSheet. Add the data graphic to a template. 5. and color by value. The data graphic will remain as part of the drawing.msvCalloutType which has values “Text Callout”.msvCalloutIconCount. You most Open the data graphic master. GraphicItem and GraphicItems 2.msvCalloutIconNumber. False. User. User. data bar callout. triple. “Heading”. 12.Answers 1. SetExpression of the GraphicItem object. Volume 3: Programming with the Visio Object Model 214 . and methods that control data linking  Link shapes to records within the data  Manage the links programmatically  Refresh the data  Detect and react to changes in the data on refresh 214 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. refresh data. properties. Using programming techniques to add datarecordsets. Module Objectives After completing this module you will be able to:  Add data to Visio programmatically from different data sources  Describe the objects. add data graphics. All rights reserved. Each of the actions that can be performed through the user interface can also be performed programmatically.Managing External Data Sets A key feature of Visio is the ability to pull external data from a variety of data sources into the Visio environment and link shapes from the drawing to this data. and detect and respond to changes after refresh are the topics of this module. create and link shapes. The linking process updates a shape to import data into existing Shape Data fields. and adds new fields as needed. but uses simple rectangle shapes and data graphics to display the organizational information on the shapes. Volume 3: Programming with the Visio Object Model 215 . The key to using these methods is setting up the connection string and the command string. These tools utilize heavily and also enhance the preexisting Shape Data features (formerly Custom Properties) of Visio that allow any data to be associated with Visio shapes. This example adds datarecordsets. At the end of this lesson we will review an example that is more extensive than the simple code snippets in the Help files. AddFromConnectionFile. and events of the new objects  Create datarecordsets programmatically from different data sources using different Add methods  Manage the DataConnection object to modify the connection string Overview of Objects / Methods / Properties Big changes occurred to Visio 2007 in the area of data support. The command string is used to specify what part of the data is desired. The final solution is an organizational chart created from data in an Excel file. There are also new tools for displaying data associated with shapes (data graphics). adds shapes. The connection string identifies the data’s location of the data and any security information needed for accessing the data. There are three variations of the Add method for creating a new datarecordset: Add. adds and modifies a data graphic. and AddFromXML.Lesson 1: Data Link Concepts The first part of managing linked data is getting connected to the data. All rights reserved. 215 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Lesson Objectives After completing this lesson you will be able to:  Identify the new objects added to Visio 2007 for managing data linking and where they fit in the object model  Identify the properties. and lays out the drawing. Visio now provides a general purpose tool for bringing data into the Visio environment and linking that data to shapes within the drawing (data linking and pivot diagrams). links the shapes to the data. methods. in each case as a result of a data recordset being refreshed. each pointing to a different data source. 216 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. The DataConnection object holds the information for making the connection to the data source. When data recordset rows are added. and when data recordset columns are added or deleted. This collection is empty until data is added to the drawing either through the user interface or through one of the automation methods that creates a DataRecordSet object. each column representing a field. The DataColumns is the collection of all of the columns. properties of the DataRecordsetChangedEvent object return arrays of the affected rows or columns. or deleted. The data in a DataRecordSet contains columns of data.Data Linking The DataRecordSets object is part of the Document. There may be multiple DataRecordSet objects within a document. Volume 3: Programming with the Visio Object Model 216 . The DataColumn object allows custom mapping of the column to a ShapeSheet cell. The relationship of the data linking objects to other portions of the Visio object model is shown in the graphic below. All rights reserved. changed. ADO description. Returns an array of data recordset row IDs that match the rows in the data recordset specified in the criteria string passed to the method. associates it with a new or existing DataConnection object. Sets the column name of the primary key column used during a refresh operation. Removes all conflict information from the drawing file. All rights reserved. Returns an array of column names when data row 0 is specified. 217 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 217 . Returns an array of values for each column in the specified data row. Description Returns an array of all the shapes in the data recordset that have refresh conflicts. and data recordset ID associated with an error that results from adding a new data recordset or refreshing the data in an existing recordset. Refreshes the data in a data recordset that has no data connection. and fills it with data from an OLEDB or ODBC data source by using the connection and query information stored in a specified ODC connection file. Returns an array of IDs of data rows that may have a broken link to a specified shape after a refresh operation. Refreshes the data in the data recordset. Adds a DataRecordset object to the DataRecordsets collection and fills it with data from an XML file. Gets the ActiveX Data Objects (ADO) error code. without requiring a DataConnection object.Methods DataRecordSets AddFromConnectionFile AddFromXML GetLastDataError DataRecordSet GetAllRefreshConflicts GetDataRowIDs GetMatchingRowsForRef reshConflict GetPrimaryKey GetRowData Refresh RefreshUsingXML RemoveRefreshConflict SetPrimaryKey Description Adds a DataRecordset object to the DataRecordsets collection. Returns the name of the primary key column of the data recordset. applies a data graphic to linked shapes. Volume 3: Programming with the Visio Object Model 218 . Links a single data-recordset row to a shape or to all shapes in a selection. applies a data graphic to linked shapes. Returns an array of the IDs of shapes in a selection so that you can link them to data.DataColumns SetColumnProperties Description Sets the properties of the specified columns to the values specified. Links an array of shapes to an array of data rows from a particular data recordset on a one-to-one basis. 218 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Optionally. Creates many shapes linked to data on the same page. Optionally. Sets the specified property (as VisDataColumnProperties) to the specified value. SetProperty Page DropLinked DropManyLinkedU GetShapesLinkedToData GetShapesLinkedToDataRow LinkShapesToDataRows Selection AutomaticLink BreakLinkToData GetIDs LinkToData Description Creates a shape linked to data on the page. Description Automatically matches shapes to data rows by comparing shape-attribute values with recordset-data-row values and finding the best match. Returns an array of shapes on the page linked to a specific data recordset. DataColumn GetProperty Description Returns the value of the data column property passed in as VisDataColumnProperties. Breaks the link between one or more shapes and the data row or rows to which the shape or shapes are linked. You can specify the column (field) in each row of data and the shape attribute upon which to base the comparison. by matching positions in the arrays. Returns an array of shapes on the page linked to a particular data row in a data recordset. which means that refreshing by interval never occurs. Optionally. Permits exporting data in XML format from Visio. Returns Nothing for a connectionless DataRecordset object. Determines whether a specified shape data item is linked to a particular data recordset. Minimum value is one minute. Links a single data-recordset row to a shape or to all shapes in a selection. All rights reserved.Shape BreakLinkToData GetCustomPropertiesLinkedToData GetCustomPropertiesLinkedColumn GetLinkedDataRecordsetIDs GetLinkedDataRow IsCustomPropertyLinked LinkToData Description Breaks the link between one or more shapes and the data row or rows to which the shape or shapes are linked. Returns the ID of the row to which a shape is linked in the specified data recordset. Gets the XML string describing the data recordset following the ADO XML schema. Volume 3: Programming with the Visio Object Model 219 . Properties DataRecordset CommandString DataAsXML DataColumns DataConnection LinkReplaceBehavior RefreshInterval Description Gets or sets the command string used to query the data source. Returns the name of the column in the specified data recordset that is linked to the specified shape-data field. 219 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Read-only. Contains all the rows in the data recordset with Visio row IDs prepended to them. Default value is 0. Returns the DataConnection object associated with the DataRecordset object. Read-only. Returns the DataColumns object associated with the DataRecordset object. Gets or sets the refresh interval for the data recordset in minutes. Returns an array of indices of shape data linked to a particular data recordset. Gets or sets how existing links between shapes and data rows are handled during application of the Selection. Returns an array of the IDs of data recordsets linked to a shape.AutomaticLink method. applies a data graphic to linked shapes. RefreshSettings TimeRefreshed DataConnection ConnectionString Timeout DataColumn DataRecordset DisplayName Gets or sets refresh settings for the data recordset. Read-only. Read-only. Readonly. Description Returns the DataRecordset object associated with the parent object. Description Gets or sets the connection string used to access an existing DataConnection object or to create a new DataConnection object. Returns an array of the IDs of rows in the data recordset whose type content was changed or deleted as part of a refresh operation. Returns the DataRecordset object associated with the parent object. Read-only. DataRecordsetChangedEvent DataColumnsAdded DataColumnsChanged DataColumnsDeleted DataRecordset DataRowsAdded DataRowsDeleted Application Description Returns an array of the IDs of columns added to the data recordset as part of a refresh operation. Returns an array of the IDs of columns deleted from the data recordset as part of a refresh operation. as a combination of VisRefreshSettings values. All rights reserved. Returns an array of the IDs of columns in the data recordset whose type changed as part of a refresh operation. Volume 3: Programming with the Visio Object Model 220 . Read-only. Description 220 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Default is 15 seconds. Gets or sets how long (in seconds) to attempt to establish a data connection before terminating the attempt and generating an error. Gets or sets the display name for the data column in the External Data window and the label for the associated text box in the Shape Data dialog box for the linked shape or shapes. Returns an array of the IDs of rows added to the data recordset as part of a refresh operation. Returns the date and time of the last refresh operation. Read-only. All rights reserved. To connect your Visio drawing to a data source programmatically. Data sources you can connect to include Microsoft Office Excel worksheets. such as an Oracle database. SelectedDataRowID Data Sources The Data Selector wizard enables the Visio user to connect to external data sources and bring that data into the Visio environment. use the new additions to the Visio API for data connectivity which include the following objects and their associated properties. and events:       DataRecordsets collection object DataRecordset object DataConnection object DataRecordsetChangedEvent object DataColumns collection object DataColumn object 221 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Window Description SelectedDataRecordset Gets or sets the DataRecordset object that is selected on the active tab of the External Data window. Gets or sets the row ID of the selected row displayed on the active tab of the External Data window. Microsoft Office Access databases. methods.DataFeaturesEnabled True if data features are enabled for the current instance of Visio. Volume 3: Programming with the Visio Object Model 221 . Read-only. and other OLEDB or ODBC data sources. Microsoft SQL Server databases. Microsoft SharePoint lists. Document Description DataRecordsets Returns the collection of DataRecordset objects associated with the Document object. When you add a DataRecordset object by connecting to an data source. Visio abstracts the connection in a DataConnection object. You can also add a DataRecordset object by using an XML file that conforms to the ActiveX Data Objects (ADO) XML schema as the data source. you can refresh the data in the drawing to reflect those changes. An example of using this technique to create a DataRecordset is presented later in this material. which is empty until you make a connection to a data source. Each Visio Document object has a DataRecordsets collection. however. 222 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. To connect a Visio document to a data source. The resulting DataRecordset object is said to be connection-less. It cannot update the data in the source. and the DataRecordset object is said to be connected. You cannot. If data in the source changes. All rights reserved. The connection between a data source and a DataRecordset object goes only one way—from the data source to the Visio drawing.Figure 17. each of which is mapped to a corresponding column (field) in the data source. make changes in the data in the drawing and then push those changes back to the data source. Volume 3: Programming with the Visio Object Model 222 . you add a DataRecordset object to the DataRecordsets collection of the document. Data objects as they appear in the user interface. Visio can only read the data source. A DataRecordset object has a DataColumns collection of DataColumn objects. DataConnection Debug.Jet OLEDB:System database="".XLS.MaxScanRows=0.0.IMEX=1.Data Source=C:\Program Files\Microsoft Office\OFFICE12\Samples\1033\ORGDATA.Excel 12. Try it! 1.Jet OLEDB:Create System Database=False.0.DataRecordset Dim iCount As Integer iCount = ActiveDocument. the data is displayed in the External Data window. Public Sub GetDataConnectionObject() 'Displays the connection string from the DataConnection object 'for the most recently opened datarecordset Dim vsoDataConnection As Visio.Jet OLEDB:Encrypt Database=False. Use the Data Selector wizard (Data > Link Data to Shapes.DataRecordsets..Jet OLEDB:Don't Copy Locale on 223 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Count Set vsoDataRecordset = ActiveDocument.DataConnection Dim vsoDataRecordset As Visio.Jet OLEDB:Registry Path="".xls data from the Samples folder.Print vsoDataConnection. 3.Jet OLEDB:New Database Password="".Information is stored in the DataConnection object An easy way to discover what information is required in a connection string is to use the macro recorder within Visio.ACE.Jet OLEDB:Global Bulk Transactions=1.) to import the data in Orgdata.ConnectionString End Sub Sample connection string for Excel data source: Provider=Microsoft..Jet OLEDB:Database Locking Mode=0.Mode=Read. Open from the Samples directory Working With DataRecordsets. When the import is finished.Extended Properties="HDR=YES.12. The code and the connection string are listed below.vsd.Jet OLEDB:Global Partial Bulk Ops=2. All rights reserved.User ID=Admin.". Run the macro to display the DataConnection object (View > Macro > InterestingMacros.Jet OLEDB:Engine Type=35. The connection string is displayed in the Immediate window. Volume 3: Programming with the Visio Object Model 223 .DataRecordsets(iCount) Set vsoDataConnection = vsoDataRecordset. 2. Accessing different data sources only requires a modification to the connection string used that describes the location of the data.GetDataConnectionObject).OLEDB. xls.Persist Security Info=True. "Org Data") 3. Try it! 1.DataRecordsets. 2.net/ShapingFuturez. strCommand.ID.Compact=False. Set vsoDataRecordsetTwo = ActiveDocument. Sample connection string for SQL Server: Provider=SQLOLEDB.Add The Add method adds a DataRecordset object to the DataRecordsets collection by connecting to and retrieving data from an ODBC or OLEDB data source. All rights reserved.Jet OLEDB:Compact Without Replica Repair=False.Add( _ vsoDataRecordset. The first time the Add method is used. "Org Data") 224 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. _ strCommand. The second time the Add method is used the DataConnection object previously created is passed as the parameter to the Add method.DataConnection.Add( _ strConnection.vsd run the macro View > Macro > InterestingMacros.Data Source=localhost\sqlexpress. 0. Volume 3: Programming with the Visio Object Model 224 . This creates another DataRecordset from the same data in ORGDATA.1.AddDataRecordsetFromConnectionObject.Integrated Security=SSPI.xls.DATABASE=http://name.Jet OLEDB:SFP=False. Upon completion of this first Add the DataRecordset object is created and its DataConnection object is established. The macro will create two DataRecordsets from the sample data in ORGDATA. View the code for this macro. the connection information is passed as a string.Jet OLEDB:Support Complex Data=False Sample connection string for SharePoint list: PROVIDER=WSS.LIST={05F6AF30-326C4932-83C1-35BF2015F718}. From the file Working with DataRecordsets. Set vsoDataRecordset = ActiveDocument. 0.officeisp.DataRecordsets.Initial Catalog=WhitePaperSamples Add a DataRecordset DataRecordsets. This DataConnection can be used to create more instances of the same data.odc file used for this example was created with the Data Connection Wizard in Excel. there will be a DataConnection object containing the connection information for the data used to create the DataRecordset (except for connectionless DataRecordsets).odc file can be created in different ways including using tools in SharePoint and tools in Access and Excel.odc) is done with the AddFromConnectionFile method of the DataRecordsets object.odc file exists pass the path of the . 0.DataRecordset strFile = "C:\Documents and Settings\System Admin\My Documents\" & _ "My Data Sources\Northwind Employees. All rights reserved.odc file in the first parameter of the method similar to the code presented below.odc" strName = "Data from ODC" Set vsoDataRecordset = _ ThisDocument. strName) End Sub Note: An . If an .AddFromConnectionFile Creating a DataRecordset from an Office Database Connection file (. 225 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Public Sub AddFromConnectionFile_Example() 'Create a DataRecordset from an . Volume 3: Programming with the Visio Object Model 225 .odc file using the 'AddFromConnectionFile method Dim strFile As String Dim strName As String Dim vsoDataRecordset As Visio. DataRecordsets. The .DataRecordsets.AddFromConnectionFile( _ strFile.Tip: Anytime a DataRecordset exists. 2. Visio never refreshes a data recordset you created by using the AddFromXML method automatically.vsd to create a DataRecordset based on the new .odc file just created. they are referred to as a connection-less data source. you must call the DataRecordset.Try it! (optional) 1.odc file.odc file is saved.AddFromXML_Example. This can point to any Excel file or easily accessible database such as Northwind. Volume 3: Programming with the Visio Object Model 226 . Note the path where the .mdb. From the file Working with DataRecordsets run the macro View > Macro > InterestingMacros. View the code.RefreshUsingXML method. DataRecordsets.RefreshInterval property. In contrast with data recordsets created by using the Add or AddFromConnectionFile methods. <xml xmlns:s='uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882' xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882' xmlns:rs='urn:schemas-microsoft-com:rowset' xmlns:z='#RowsetSchema'> <s:Schema id='RowsetSchema'> <s:ElementType name='row' content='eltOnly' rs:updatable='true'> <s:AttributeType name='c1' rs:name='Cities' 226 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. regardless of the setting of the DataRecordset. Note: Because DataRecordsets created using AddFromXML have no DataConnection object. data recordsets created by using the AddFromXML method are not associated with a DataConnection object. Try it! 1.AddFromXML Adds a DataRecordset object to the DataRecordsets collection. Following is the XML data used to create the DataRecordset. Use Excel to create an . The macro will create a DataRecordset from the XML data defined within the macro. All rights reserved. and fills the resulting data recordset with data supplied in the form of an XML string. 2. Modify the macro AddFromConnectionFile_Example in the file Working with DataRecordsets. What's more. Compare this to the VBA code to see how the XML data is put into a string. To refresh the data in such a data recordset. modifies the data graphic that displays the organizational data. Run the macro GetDataConnectionObject. This macro is a simple example of using GetRowData and GetDataRowIDs and writing the information to the VBA’s Immediate Window. starting with the number 1. Use GetDataRowIDs to retrieve a subset of IDs within the DataRecordset that satisfy a given criteria string. based on the order of the rows in the original data source.DoItAll. All rights reserved. you must use these data row IDs. drops shapes on the page and links them to the data records. drops connectors on the page and glues them between the employee and its Reports_To shape. Visio uses data row IDs to track the rows when they are linked to shapes and when data is refreshed. Accessing data in the DataRecordset When you import data. A sample of how to use these methods is included in the following demonstration code. to each data row in the resulting datarecordset. Run the macro View > Macro > BuildOrgMacros. This will trip the error handler when checking for the DataConnection object and display a message in VBA’s Immediate window. Try it! 1. Two important methods for retrieving information from DataRecordsets include GetDataRowIDs and GetRowData. 2. If you want to access data rows programmatically. Make sure a datarecordset exists and then run the macro GetDataRecords. Visio assigns integer row IDs. Use GetRowData to retrieve all columns of data within a given row.rs:number='2' rs:nullable='true' rs:maydefer='true' rs:write='true'> <s:datatype dt:type='string' dt:maxLength='255' rs:precision='0'/> </s:AttributeType> <s:extends type='rs:rowbase'/> </s:ElementType> </s:Schema> <rs:data> <z:row c1='Seattle' /> <z:row c1='Redmond' /> </rs:data> </xml> 3. 227 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. and then lays out and resizes the page. This macro builds an organizational chart. It creates a DataRecordset. Volume 3: Programming with the Visio Object Model 227 . This is enough information to give us the “from shape” and “to shape” so that we can add and glue the connectors. Look at the code in the macro AddDataRecordSet. _ lngNameRowIDs(0). GetRowData is used to extract the fields from a row in the form of an array of variant data. It also sets the primary key field of the datarecordset. This macro is used by the DoItAll macro and sets up the DropManyLinkedU method to add a shape linked to each record in the datarecordset.3. 5. Look at the code in the macro AddAndGlueConnectors. All rights reserved. The data in the Reports_To field is used to construct a criteria string which is then passed to the method GetDataRowIDs to retrieve the ID of the record within the datarecordset of that employee. Each record contains the data for one employee and in that record is the “Reports_To” field which gives us the name of the person they report to.Add method to create the datarecordset.ID. The key segment of code follows. This macro utilizes GetRowData and GetDataRowIDs to extract the needed information.GetDataRowIDs(strCriteria) 'Find the shape linked to this data row ActivePage. Note that it uses the DataRecordSets. An example criteria string is “Name = ‘Joseph Goldberg’” Given the ID of this record we use GetShapesLinkedToDataRow to find the shape on the page that is linked to the row in the datarecordset. Look at the code in the macro DropManyLinkedShape. 228 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.GetRowData(ShapeRowID) strReportsTo = varRowData(2) 'Find the datarecordset row that has this "Reports_To" data 'in the "Name" field strCriteria = "Name = '" & strReportsTo & "'" lngNameRowIDs = vsoDataRecordset. Volume 3: Programming with the Visio Object Model 228 . This macro is used by the DoItAll macro. Note that the data graphic is added at the same time the shapes are created. lngShapeIDs 6. 4. 'Get the shape id of the "Reports_To" shape varRowData = vsoDataRecordset. The macro ModifyDataGraphicMaster modifies the default data graphic applied to the shapes to add another text callout that displays the employee’s “Title” information.GetShapesLinkedToDataRow vsoDataRecordset. Volume 3: Programming with the Visio Object Model 229 . 229 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. We will explore the other macros in this file later in this module. This macro applies the Layout method to arrange the drawing and resizes the drawing page so that the entire organization chart fits on the page.7. The final step is in LayoutAndResize. All rights reserved. Datarecordsets can be refreshed. The steps of creating the shapes. the next step is to link shapes to its rows. When a datarecordset is refreshed. After the data is refreshed the code checks for conflicts in the data and for additions and deletions to the data. These changes can lead to conflicts with the linking that was previously established. Volume 3: Programming with the Visio Object Model 230 . A shape can be linked to only one row within a single datarecordset. but it can be linked to multiple datarecordsets – one row in each. All rights reserved. it may change. Multiple shapes can be linked to the same row. and adding a data graphic can be done in a single step. Visio provides tools for detecting these conflicts and detecting changes to the datarecordset so that your program can react appropriately to the changes. linking the shapes. They can be refreshed on demand or they can be refreshed automatically at prescribed intervals.Lesson 2: Managing Data sets After creating a datarecordset. Lesson Objectives After completing this lesson you will be able to:  Link existing shapes to rows in a datarecordset  Add shapes to a drawing and link them at the same time  Link many shapes to a row in a datarecordset  Link shapes to rows in multiple datarecordsets  Automatically link shapes  Add data graphics to linked shapes  Discover existing links  Break links  Manage refresh  Discover and manage conflicts after refresh 230 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. At the end of this lesson we will review a macro that refreshes the datarecordset for the organization chart created in the previous lesson. vsd. An example of using DropLinked follows.DropManyU methods in that they create additional shapes at a specified location on the page. All rights reserved. However. you can use the Page. Creating shapes linked to data When you want to create shapes that are already linked to data. dblY. In the file Working with DataRecordsets. True)       vsoMaster is a reference to the master that is being dropped on the page dblx. View the code in DropLinkedShape. you can link the shapes in the drawing to data from that source programmatically. lngRowID. run the macros AddFromXML_Example (although any open datarecordset will do) and then DropLinkedShape.DropLinked(vsoMaster. on a drawing page that either does not contain any shapes or contains shapes other than the ones you want to link. _ lngDataRecordsetID. Volume 3: Programming with the Visio Object Model 231 .DropManyLinkedU method to create one or more additional shapes already linked to data. 2. Set vsoShape = ActivePage. These methods resemble the existing Page. but they also create links between the new shapes and specified data rows in a specified data recordset.Linking data to shapes After you connect your Visio drawing to an external data source. or.DropLinked method and the Page. you cannot link shapes to multiple rows of data in the same recordset. You can link existing shapes to data. dblX.Drop and Page. one shape at a time or many at a time. you can create shapes and link them to data simultaneously. You can link one or more shapes to a single row of data in a data recordset or to multiple rows of data in different data recordsets. dbly define the drop location and correspond to the created shape’s pin location lngDataRecordsetID is the ID of the datarecordset being linked to lngRowID is the ID of the row within the datarecordset being linked to the last parameter (True) is a Boolean that specifies whether a data graphic is to be applied to the shape automatically vsoShape is a returned reference to the created shape Try it! 1. 231 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. y coordinates that determine the drop locations for the new shapes vsoDataRecorset. alngShapeIDs)        avsoMaster is an array of shapes to be dropped. The complete code can be viewed in the macro DropManyLinkedShape.ID.An example of DropLinkedManyU was covered in an earlier example. vsoDataRecordset. one per record in the datarecordset dblxy is an array of x.DropManyLinkedU(avsoMaster. vsoShape.ID.ID is the ID of the datarecordset being linked to lngRowIDs is an array of row IDs within the datarecordset that determine the row that each shape is linked to the next to last parameter (True) is a Boolean that specifies whether a data graphic is to be applied to the shapes automatically alngShapeIDs is an array of IDs for the created shapes lngReturned is a returned value specifying the number of created shapes Linking existing shapes to data Link a single shape to a single row To link a single shape to a single row LinkToData method of the shape as shown below. True. but it can still be linked to a different row within a different datarecordset. The core piece of code follows: 'Create one shape record for each record in the datarecordset lngReturned = ActivePage. _ dblXY. 232 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved.ID is the ID of the datarecordset being linked to lngRowID is the ID of the row within the datarecordset boolAddDataGraphic is a Boolean specifying whether a data graphic is to be applied automatically to the shape Link a shape to multiple datarecordsets A single shape can be linked a single row within a single datarecordset.LinkToData vsoDataRecordset. lngRowID. Volume 3: Programming with the Visio Object Model 232 . _ lngRowIDs. boolAddDataGraphic The following information is needed:     vsoShape is a reference to the shape to be linked vsoDataRecordset. you can optionally specify whether to apply an existing data graphic to linked shapes. The LinkShapesToDataRows method links shapes to multiple data rows. The LinkToData method of the Selection object links multiple shapes to a single row. the Selection. Link multiple shapes to multiple rows The Page. Let’s set up an example for matching multiple columns and let’s use the record macro feature of Visio to create the code. Volume 3: Programming with the Visio Object Model 233 . All rights reserved. alngDataRowIDs. the shape at position 1 in the shape array is linked to the data at position 1 in the data row array. it indicates that the shape is not linked to the data row. boolAddDataGraphic To link shapes. After you run the method. alngShapeIDs.LinkShapesToDataRows method is similar to the Selection.ID.To link a shape to rows in multiple datarecordsets apply the LinkToData method multiple times. Visio skips that shape and goes on to the next shape in the selection. to determine if all shapes in the selection are actually linked to the data row. when you call the method. Link multiple shapes to a row in a datarecordset This is the same as linking an individual shape except the LinkToData method of the Selection object is used. once for each datarecordset. Note that it must be the same attribute for all shapes.AutomaticLink method provides a way to link a selection of existing shapes to multiple rows of data.LinkToData method because it links multiple shapes. If Visio cannot establish a link between a shape and the data row. call the Shape. Visio will usually succeed in linking a row to a shape unless the shape is already linked to data and the link-replacement-behavior setting for the datarecordset specifies that the link should not be replaced. The help file for the AutomaticLink method gives a coding example for setting up an automatic link where a single column to be matched is specified. 233 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.GetLinkedDataRow method on each shape in the selection.LinkShapesToDataRows vsoDataRecordset. Note that the matching array positions must correspond. and one for data rows. Automatically link shapes and data rows If you are unsure about the correspondence between shapes and data rows. If that method fails for any shape. ActivePage. As a result. pass the LinkShapesToDataRows method a pair of arrays: one for shapes. for example. but you know a match exists between a specific attribute of every shape and the data in one column in the data recordset. Again. 3.AddDataRecordset to create a datarecordset from ORGDATA. 10. All rights reserved. 9.Try it! 1. Click Next and Finish.AutomaticLink 41. Choose Data Column = Name and Shape Field = Name. Right-click in the External Data window and choose Automatically Link. The last portion of the code should look similar to the following. ColumnNames1(0) = "Name" FieldTypes1(0) = visAutoLinkCustPropsLabel FieldNames1(0) = "Name" ColumnNames1(1) = "Title" FieldTypes1(1) = visAutoLinkCustPropsLabel FieldNames1(1) = "Title" Application. 11. 8. On the first page choose Selected Shapes and then Next. Turn on the macro recorder. Then click the and button. field types. This will add shape data fields to the rectangles. 6. ColumnNames1. 7. 234 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Selection. The last parameter returns an array of shape IDs of the linked shapes. _ FieldTypes1.ActiveWindow. This will link the three selected shapes. In this case we are specifying that multiple columns and fields must match before the shapes can be linked. Choose Data Column = Title and Shape Field = Title. Drop three rectangles on the page and link them to the first three records in the datarecordset. The Automatically Link wizard is presented. visAutoLinkReplaceExistingLinks. Open Working with DataRecordsets.xls. for example to replace existing links with new ones. FieldNames1. _ IDsofLinkedShapes1 We are passing to the method arrays for column names. Unlink the three shapes. 2. 5. These enumerated values provide options to customize the method.vsd and run the macro BuildOrgMacros. Select the three shapes. Use values from the VisAutoLinksBehavior enumeration. and field names. 4. The penultimate parameter specifies the auto link behavior. Volume 3: Programming with the Visio Object Model 234 . Stop the macro recorder and look at the code. A note on the use of IDs in Visio Visio keeps unique IDs for shapes. such as deleting a datarecordset or deleting the Shape Data item in a shape that is linked. and rows within the datarecordsets. returns an array of shape IDs on a page linked to the datarecordset Page.GetCustomPropertyLinkedColumn – given a datarecordset ID and a shape’s Shape Data row ID. Shape IDs are reused when one shape is deleted and then another shape is added. actions in the user interface can cause links to be broken. Shape IDs Shape IDs are unique to the page. Regardless of how the link was broken.ShapeDataLinkDeleted event is fired.GetShapesLinkedToData – given a datarecordset. returns the name of the data column linked to this shape data row Shape.Discovering links Discovering information about links is very straight forward. Shape UniqueIDs Unique IDs are GUIDs. datarecordsets.BreakLinkToData and the Selection. the Shape. All rights reserved. Volume 3: Programming with the Visio Object Model 235 .GetLinkedDataRow – given a datarecordset.GetCustomPropertiesLinkedToData – given a datarecordset ID. The sample code in the Visio help files gives examples using these methods.given a datarecordset ID and a shape’s Shape Data row ID. They are unique within the scope of the application. returns whether that Shape Data item is linked Breaking links Breaking links through automation is handled with the Shape. Some key methods include:        Page. 235 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.BreakLinkToData methods. returns an array of Shape Data row IDs that are linked to the data columns in the datarecordset Shape. returns the ID of the row the shape is linked to Shape.GetLinkedDataRecordsetIDs – returns a list of IDs of all datarecordsets that are linked to by this shape Shape.IsCustomPropertyLinked . In addition.GetShapesLinkedToDataRow – given a datarecordset and a row ID. returns an array of shape IDs on a page that are liked to that row Shape. Visio uses the row IDs assigned to the rows in the data recordset. a shape does not have a unique ID. By default. when Visio refreshes linked data. To identify these rows.ID value will NOT be the same as the position of the DataRecordset within the DataRecordsets collection. and so on. but they may not run consecutively depending on recent refresh operations. it must determine which rows in the linked data recordset or recordsets were added. the DataRecordset. the data recordset reflects those changes. Then. depending on whether you designated primary keys for the data recordset when you created it. A shape acquires a unique ID only if you set its UniqueID property. There is no index value for a DataRecordset. the second is assigned row ID 2. Volume 3: Programming with the Visio Object Model 236 . Row ID 5 is removed from the data recordset. in a five-row data recordset. Row IDs within a DataRecordset Rows of data within a DataRecordset generally have unique IDs starting with a value of 1. As a result. Accordingly. shapes linked to row ID 5 lose their links. when Visio refreshes the data recordset connected to that data source. you can use two methods of the Page object.To convert between shape IDs and unique IDs. or removed since the last time the data was refreshed.ID property. and shapes linked to row ID 4 now get data from the row previously in the fifth position. changed. DataRecordset IDs DataRecordsets have unique IDs accessible via the DataRecordset. 236 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Because shapes are linked by their shape IDs to specific data rows. when data is refreshed. Visio can assign these row IDs two ways. data rows can be added or removed from the original data source. These ID values are not reused if a DataRecordset is closed. For example. Visio assigns row IDs to all the rows in the recordset based on the existing order of the rows in the data source. no other shape in any other document will have the same ID. the first row in the recordset is always assigned row ID 1. row order in the data recordset may change. if the fourth row in the data source is removed. Refreshing Data Recordsets That Do Not Have Primary Keys When you create a data recordset. All rights reserved. If a Shape object has a unique ID. Generally. As a result. the fifth row in the data recordset becomes the new fourth row and is assigned row ID 4. Subsequently. ShapeIDsToUniqueIDs and UniqueIDsToShapeIDs. All rights reserved. its rows retain the same row IDs they had before the refresh operation. Refreshing Data Recordsets That Have Primary Keys You can help prevent these broken or mismatched links by assigning primary keys to data recordsets. 'Turn off automatic refresh vsoDataRecorset.RefreshInterval = 2 To turn off automatic refresh set the refresh interval to zero. However. Volume 3: Programming with the Visio Object Model 237 . or in Visio linking shapes to rows other than the ones to which you want them linked. Note that row IDs are never recycled for a given a data recordset. Primary keys are often ID values. Managing Refresh DataRecordsets can be refreshed programmatically using the DataRecordset.Refresh method. it is essential that you make the primary key column value (or set of values for multiple primary key columns) unique for each row. When a datarecordset is created it does not refresh automatically.As you can see. To enable automatic refresh set its refresh interval to some value greater than zero. Calling this method executes the query string associated with the datarecordset and then updates the linked shapes with the data returned by the query. As a result. 'Set the refresh interval to 2 minutes vsoDataRecorset. The value in the primary key column for each row uniquely identifies that row in the data recordset. to get consistent results when you refresh data. datalinked shapes remain linked to the correct row. not assigning primary keys to data recordsets when you create them can result in broken links between shapes and data. Because Visio links shapes to data rows by ID—shape ID to row ID—and because row IDs remain the same after a refresh operation. A primary key identifies the name of the data column or columns that contain unique identifiers for each row.RefreshInterval = 0 237 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. when you refresh or when Visio refreshes a data recordset that includes primary keys. but you can set any column or combination of columns to be the primary key. Volume 3: Programming with the Visio Object Model 238 . or when a shape is linked to a row in the data source that has been deleted. If the shape would be linked to multiple rows. All rights reserved. an empty array is returned. If a data row has been deleted and a shape was linked to it. Visio displays the Refresh Conflicts task pane in the UI. the link is removed and the user is presented with the duplicate data and prompted for how to deal with it. Use GetMatchingRowsForRefreshConflict to retrieve all of the rows in the datarecordset that match with this shape.RefreshSettings = visRefreshNoReconciliationUI Identify changes and resolve conflicts When a datarecordset is refreshed conflicts are displayed in the Refresh Conflicts task pane. If a new data row is added that is not a duplicate. there is no conflict. If a new data row is added that is a duplicate of a previous row that was linked. From the user interface the new record is apparent by looking at the External Data window and noting the unlinked records. By default RefreshSettings=0. GetMatchingRowsForRefreshConflict. GetAllRefreshConflicts This method returns an array of shapes that are linked to data rows in a datarecordset that have nonresolved conflicts after a datarecordset is refreshed. 'Don’t display refresh conflicts in the Refresh Conflicts task pane vsoDataRecorset. If no conflicts exist.If calling Refresh results in conflicts. unless you set the RefreshSettings property to include the visRefreshNoReconciliationUI (=2) enumerated value. that shape is displayed and the user is prompted for what to do with it. The automation model provides tools to handle each of these scenarios. 238 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. you should reconcile refresh conflicts programmatically by using the GetAllRefreshConflicts. As a developer. the link is removed and the conflict is presented in the Refresh Conflicts task pane. and RemoveRefreshConflict methods. Conflicts can result when a single shape is linked to more than one row in the same data source. DataRecordsetChanged event and DataRecordsetChanged object Retrieving conflict information is great for when changes to the datarecordset results in conflicts. It returns an array of row IDs from the datarecordset that each match the shape in conflict. All rights reserved.xls and then using the Refresh method. The following changes are made to the organizational data: 239 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.vsd from the Samples folder. Conflicts can also occur when a previously data-linked row from the data recordset is removed. and data rows that have been added or deleted. when a new row is added the user may want to add a new shape that is linked to the new rows. changed.vsd has a macro that will Refresh a datarecordset and then check for and process changes using the methods and events just described. This macro refreshes the Org Data datarecordset by modifying the connection string to point to a modified version of the Excel file OrgDataModified.RefreshDataAndResolveConflicts. the method returns an empty array. Some of the code is not bullet proof. Volume 3: Programming with the Visio Object Model 239 . 2. there is a way to retrieve this information programmatically. Run the macro BuildOrgMacros. If you already have the file open. Within the DataRecordsetChanged event you have access to the DataRecordsetChanged object which contains a wealth of information about what has changed in the datarecordset including data columns that have been added. but this does not help when new rows are added to the datarecordset. the list of matching rows can be retrieved with this method. 1. 4. For example. Run the macro BuildOrgMacros. Fortunately. but it does illustrate how to use the methods. RemoveRefreshConflict Once a conflict has been dealt with it can be removed from the list by using the RemoveRefreshConflict method of the shape. it is best to close it and then reopen it. 3. or deleted.GetMatchingRowsForRefreshConflict When a shape is potentially linked to multiple rows in a datarecordset after a refresh.xls file. Try it! The sample code in Working with DataRecordsets. Use the DataRecordsetChanged event to detect that the datarecordset has changed. This builds the organization chart we saw earlier using the OrgData. Open Working with DataRecordsets. When this occurs.DoItAll. The original Toby Nixon shape is deleted and a new shape is added. but because the Toby Dixon record is new. 7. the connector has to be changed to point to the correct “Reports_To” shape c. The resolution of the conflicts is handled in the event procedure vsoDataRecordsets_DataRecordsetChanged which is in the ThisDocument module. The event code does not fire immediately after the Refresh method so if you have some code in the event procedure and some code following the Refresh method. If a row has been deleted. When the second new Fred Taylor shape is processed it is ignored because it is a duplicate. this test does not work in VBA. The IsEmpty function is designed to work with variables of type Variant and does not reliably return information for other data types. The datarecordset and the shape data are updated on the refresh. Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. If duplicate rows are created which have a corresponding shape. 6. New rows added to the datarecordset are handled next. There is no conflict created by this change. the shape is linked to one of the rows and the other row is ignored. Look at the event procedure code. If a new row is added which does not represent a duplicate. 5. Warning for VBA users implementing code samples from Help files Below is the code sample provided in the Help file for GetMatchingRowsForRefreshConflic. Conflicts are handled first using GetAllRefreshConflicts and then processing the conflict list. The record for Toby Nixon is changed to Toby Dixon. b. Note that after the call to GetAllRefreshConflicts and to GetMatchingRowsForRefreshConflic there is an If test that uses the function IsEmpty to test for an empty array being returned by the methods. Note: It is best to put the resolve conflicts code inside the event procedure. All rights reserved. Volume 3: Programming with the Visio Object Model 240 . Only the refresh code is here. The record for Meng Phua is changed to report to Toby Dixon. All resulting changes in the drawing are in the lower right hand area of the drawing page. a new shape is added to the drawing and linked its “Reports_To” shape. Look at the code for RefreshDataAndResolveConflicts. Unfortunately. A new record is added for Fred Taylor who reports to Toby Dixon and a duplicate record for Fred Taylor is also created. the corresponding shape is deleted. 9. A new shape is added for Fred Taylor. In the code this is handled as one deleted record and one added record. you won’t be able to determine which code is executed first. It returns False even when 240 the array has no data. 8. If both records are added at the same time there is no conflict because there is no shape linked to these rows.a. ActiveDocument. All rights reserved. vsoShapeInConflict.Count Set vsoDataRecordset = Visio.Shape Dim intRowCount As Integer Dim vsoShapeInConflict As Visio.Shape Dim alngRowIDs() As Long Dim lngvsoRowID As Long intRecordsetCount = Visio.Refresh vsoShapes = vsoDataRecordset.Print "No conflict" Else For intShapeCount = LBound(vsoShapes) To UBound(vsoShapes) Set vsoShapeInConflict = vsoShapes(intShapeCount) alngRowIDs = vsoDataRecordset. All of these samples will be problematic in VBA.Print "For shape:".DataRecordsets(intRecordsetCount) vsoDataRecordset.ActiveDocument." Else For intRowCount = LBound(alngRowIDs) To UBound(alngRowIDs) 241 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 241 .There are several similar methods that return arrays and similar code samples that use IsEmpty to test these arrays.DataRecordset Dim intRecordsetCount As Integer Dim intShapeCount As Integer Dim vsoShapes() As Visio.DataRecordsets.Name.GetAllRefreshConflicts If IsEmpty(vsoShapes) Then Debug. "Row deleted. Public Sub GetMatchingRowsForRefreshConflict_Example() Dim vsoDataRecordset As Visio.GetMatchingRowsForRefreshConflict(vsoShapeInConflict) If IsEmpty(alngRowIDs) Then Debug. but not always. Volume 3: Programming with the Visio Object Model 242 . If using UBound does not work the only reliable alternative is to create an error handler to trap and process the error. but we can detect that the data could not be found and then fail as gracefully as possible. You can isolate your program from the data by using a data connection file and using the AddFromConnectionFile method.Name. 242 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Changing data locations Sometimes data locations change or network connections are lost. "Row ID of row in conflict:". Is there a way to build some resiliency into your code so that if your access to the data changes your program does not fall over? Let’s examine some common scenarios: 1. but you don’t know where it is. The third variation is when the data becomes unavailable unexpectedly such as when a network connection is lost or if the data is moved. the UBound function will work and return a value of -1 if the array is empty. If the data changes location you may have to change the connection string in your code to point to the new location. the connection file is updated with the new location. We’ve already seen that the connection string can be changed and the datarecordset refreshed so straightforward to build this kind of change into your code. 2. in some cases the UBound function will throw a ‘subscript out of range’ error. Connect to the data via a connection file with the assumption that the connection file stays in a fixed location and if the data moves.Print "For shape:". In this scenario we can’t reconnect to the data.lngvsoRowID = alngRowIDs(intRowCount) Debug. However. All rights reserved. vsoShapeInConflict. lngvsoRowID Next intRowCount End If Next intShapeCount End If End Sub Alternatives to using IsEmpty Sometimes. 3. Refresh Exit Sub ErrorHandler: Debug. An error handler must be written to trap the error. This will fail if the file cannot be reached vsoDataRecordset. This property is used to set a timeout interval (default is 15 seconds).To detect a failed connection use the Timeout property of the DataConnection object. An example follows showing a portion of the subroutine which refreshes a datarecordset and displays the error message when an error occurs: 'Set the connection string into the DataConnection object to point to 'the desired data vsoDataRecordset. Err.Timeout = 15 'Refresh the data.Description End Sub 243 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.DataConnection.DataConnection. Volume 3: Programming with the Visio Object Model 243 . All rights reserved.ConnectionString = strConnection 'Set up error handler to catch the timeout error On Error GoTo ErrorHandler vsoDataRecordset. If the interval elapses without success an error is raised.Print "Error: ". delete one or more records and modify one or more records 5. You will use automation code to: 1.xls o Completed Visio drawing created in lab 3.7: Data Linking During this lab. (DropSectionShapes) 4. Fix the error in finding and loading the Section DataRecordset from an external Excel data file. 2. Volume 3: Programming with the Visio Object Model 244 .6 (a completed file is provided) What You Will Learn After completing this lab. you will be able to:  Attach to an external data set via automation code  Automatically link shapes to rows in a DataRecordset 244 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.  The following files are needed to complete this lab: o Lab Module 3 Start. Fix a problem in the linking/refresh conflicts logic that is preventing the conflict resolution from working properly.vsd o ScheduleBuilder. Refresh the Section DRS after changing the Excel file to add one or more records.Lab 3. Estimated time to complete this lab: 90 minutes Before You Begin To complete this lab. you will recreate a portion of the ScheduleBuilder program.vss o ScheduleBuilder. (LinkSelectedInstructors) 3. Drop and link the Section shapes to rows in the Section DRS. you will need:  Participants should have completed the Try This! Lessons of this module before completing this lab. All rights reserved.  Visio 2007 or later installed and configured. In the process you will also fix some program errors that exist in the lab version of the file. Link the Instructor shapes to rows in the Teacher DRS. vsd. 2. Start Visio and open the file Lab 3. Exercise 2: Link the Instructor shapes to rows in the Teacher DataRecordset Scenario The Instructor shapes must be linked to their respective rows in the Teacher DRS in order to later drop the Section shapes properly. Tasks 1. The following error message appears. It is incomplete. Recode the CreateLink procedure to load the DataRecordset properly. Select Debug and review the comments in the code. 245 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.8 Start.8 Start. Tasks 1. Look at the macro LinkSelectedInstructors.vsd. All rights reserved. You must diagnose the error and repair the code. The error appears when trying to connect to an Excel file. Drop multiple shapes onto a drawing and link them to rows in a DataRecordset  Manage Refresh of external data and resolve refresh conflicts Exercise 2: Connect to an external data set Scenario There is an error when opening the drawing Lab 3. Volume 3: Programming with the Visio Object Model 245 . Tasks 1. It is incomplete. Tasks 1. Your task is to figure out why and make the necessary changes. Exercise 3: Drop and link the Section shapes to the rows in the Section DataRecordset Scenario The macro DropSectionShapes will drop a Section shape for each record in the Section DRS. You will find that the updates are not happening properly. 2. Read the comments in the macro and complete the code. You find that the conflicts are not being refreshed correctly. Refresh the DataRecordset from the user interface. Look at the event procedure sectionRecordset_DataRecordsetChanged. Volume 3: Programming with the Visio Object Model 246 . and manage changes required by the data Scenario Change the Excel file containing the Section data so that some new records are added. This event procedure listens for changes to the DRS and then evaluates and processes the changes.2. Exercise 4: Change the external data. deletes Section shapes for any deleted records. Find the macro DropSectionShapes. 246 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. refresh the drawing. and some existing records are changed. It adds new Section shapes for each new record added. All rights reserved. Read the comments in the code and complete the macro. some existing records are deleted. http://msdn2. Volume 3: Programming with the Visio Object Model 247 .microsoft.aspx Integrating Visio 2007 and Microsoft SQL Server 2005 Learn how you can integrate Microsoft Office Visio 2007 with Microsoft SQL Server 2005.com/en-us/library/aa395290.com/en-us/library/aa395291. http://msdn2. http://msdn2.com/en-us/library/bb267248.com/en-us/office/aa905478.microsoft.Additional Resources – External Data What’s New for Developers in Visio 2007 (Part 1 of 2) This article introduces new features of interest to developers in Microsoft Office Visio 2007 and explains how to use them. Author: Saul Candib.aspx Visio Developer Portal http://msdn2.aspx Integrating Visio 2007 and Access 2007 Use Automation code to create a Visio drawing from data defining the contents of a drawing and the connectivity between shapes stored within Access tables.aspx 247 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.microsoft. Author: Saul Candib.microsoft.com/en-us/library/aa722522.microsoft.aspx What’s New for Developers in Visio 2007 (Part 2 of 2) This article describes all new objects and members of the Visio 2007 VBA object model and newly deprecated existing members. http://msdn2. to create datadriven diagrams from stored SQL data. All rights reserved. All rights reserved.com/downloads/details.aspx About Linking Shapes to Data http://msdn2. header files. Volume 3: Programming with the Visio Object Model 248 . http://www. As of this writing the 2010 Beta version was the latest version available.Visio 2010 Beta: Software Development Kit The Microsoft Office Visio Software Development Kit (SDK) contains the latest documentation.microsoft.aspx 248 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.microsoft.com/en-us/library/aa342321. samples. libraries and tools that you need to develop custom solutions for Microsoft Visio.aspx?displaylang=en&FamilyID=1cdbb7e7-6bd4-488f91bd-7bd732dbf378 About Connecting to Data in Visio http://msdn2.microsoft.com/en-us/library/aa342322. 9. What are the three methods of the DataRecordsets object for creating new datarecordsets? 2. The DataRecordsetChanged event will fire immediately following the Refresh method. Where can the command string be found in the object model? 5. True or False. GetAllRefreshConflicts can be used by the programmer to discover all changes that occur during a refresh operation. 8. 10. True or False. How does a programmer reliably detect when a shape link has been broken. the shapes are created and linked at the same time. how is the primary key set? 6. 249 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. 11. When creating and linking shapes using the DropLinked and DropManyLinkedU. 12. either through programmatic actions or through user actions. True or False. A shape can be linked to multiple datarecordsets with a single command.Review: Managing External Data Sets Questions 1. All rights reserved. How does the programmer control display of the Refresh Conflicts task pane? 13. True or False. Which property of the DataConnection object is key to catching errors thrown when a data source cannot be reached? 7. True or False. When adding a datarecordset.LinkToData method multiple times. What is different about the datarecordset created using the AddFromXML method? 3. Volume 3: Programming with the Visio Object Model 249 . Where can the connection string be found in the object model? 4. To link multiple shapes to a single row you can use the Shape. but a data graphic has to be added as a separate step. added.RefreshSettings = visRefreshNoReconciliationUI False. 4. Put any conflict resolution code or code that looks for datarecordset changes inside the event procedure. 9. 10. 7. 8. Use the SetPrimaryKey method of the DataRecordset object. and AddFromXML It is a connectionless datarecordset.LinkToData to do it in one step. There can be a time lag between the Refresh and the firing of the event which means code following the Refresh may execute before code in the event procedure. The primary key is set as a separate step from the Add. When the interval is exceeded and error is thrown. Use the DataRecordsetChanged event and DataRecordsetChanged object to get additional data on records added or deleted and columns changed. This only gives information on conflicts. 6. 2. 11. False False. Use the ShapeDataLinkDeleted event. or deleted. 3. 250 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. True. 5. Set the Timeout property. but use the Selection. vsoDataRecorset.Answers 1. All rights reserved. The LinkToData method must be called once for each datarecordset. This will work. The DataRecordset object. Volume 3: Programming with the Visio Object Model 250 . 12. False. It is in the DataConnection object which is part of the DataRecordset object. Add. AddFromConnectionFile. 13. The reader may find differences between the discussion in the final version when the RTM version of the SDK is released.Visio Software Development Kit (SDK) This module covers all aspects of the Visio 2010 SDK. All rights reserved. Hopefully those differences will be minor. creating code. Little of the documentation has been updated and some sample files have not been released and therefore are not covered. Module Objectives After completing this module you will be able to:     Understand all of the parts that make up the Visio SDK Use the tools delivered with the SDK to aid in manage events and publish solutions Use the sample code from the code library in your own programs Use the sample applications as examples for creating add-ins and add-ons for Visio 251 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. sample applications. The SDK is made up of code samples. tools. Note: At the time of this writing the Visio 2010 SDK was still in beta. Volume 3: Programming with the Visio Object Model 251 . and documentation to support developers creating shapes. and delivering their own custom solutions on Visio. All rights reserved. or you can search and select the desired code item from the Search Results tab. 252 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. The provided sample applications can be used to experiment and to become acquainted with features. samples.  Sample applications. The SDK also includes wizards to set up new Visio add-ons and Component Object Model (COM) add-ins in Microsoft Visual C#©. header files. These tools include the Persistent Events. then point to Microsoft Office Visio 2010 SDK. The Visio 2010 SDK includes:  Microsoft Office Visio Code Samples Library. and procedures. Solution Publishing. Volume 3: Programming with the Visio Object Model 252 . point to Microsoft Office 2010 Developer Resources. click the Start button. Print ShapeSheet. libraries.Lesson 1: Setup / Overview The Microsoft® Office Visio® 2010 Software Development Kit (SDK) contains the latest documentation.  Documentation The documentation includes the full set of Visio references and articles. You can use the Code Samples Library to view and copy many reusable classes. and then click Microsoft Office Visio Code Samples Library. click Start > All Programs > 2010 Microsoft Office Developer Resources > Microsoft Office Visio 2010 SDK. A database of Visio code samples. Customization and extensibility tools are provided to increase your productivity and reduce development time. Microsoft Visual C++® and Microsoft Visual Basic®.  Tools. These sample applications are written both to demonstrate aspects of developing on the Visio platform and to be used as a starting point for your custom applications. Visio SDK 2010 Contents To open the Visio 2010 SDK.NET. and tools that you need to develop custom solutions for Microsoft Office Visio 2010. and Event Monitor tools. In the Code Samples Library. you can select a code item from the tree-view Explorer window. To open the Code Samples Library. functions. Microsoft Visual Basic® . Volume 3: Programming with the Visio Object Model 253 . for selected code samples or tools to run properly.NET Flowchart sample application Software requirements Visio 2010 Visio 2010 Visio 2010 Visio 2010 Microsoft Visual Studio 2005 Microsoft Visual Studio 2008 Visio 2010 Microsoft Office Excel 2007 Microsoft Office Word 2007 (to embed the drawing into a Word document) Visio 2010 Excel 2007 Word 2007 (to embed the drawing into a Word 253 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.You do not need to have the Microsoft Office Visio 2010 application installed on your computer to be able to install the Visio 2010 SDK. To uninstall the SDK at any time In Control Panel. click Add or Remove Programs. however. Locating the SDK Files By default. Table 2. Visio is required. click Microsoft Office Visio 2010 SDK.0 Flowchart sample application Microsoft Visual Basic . Visio 2010 SDK software requirements for tools and samples Tool or sample Persistent Events tool Event Monitor tool Print ShapeSheet tool Visio Solution Publishing tool Microsoft Visual Studio 2005 Visio Addin wizard Microsoft Visual Studio 2008 Visio Addin wizard Microsoft Visual Basic 6. All rights reserved. the Visio 2010 SDK is installed in the following folder: C:\Program Files (x86)\Microsoft Office\Office14\visSDK\ for the 32 bit version of the Visio SDK. Software Requirements for Visio 2010 SDK Tools and Samples Although you do not need to have Visio 2010 installed on your computer to be able to install the Visio 2010 SDK. and then click Remove. the following tools and samples will not run correctly unless the following software dependencies are met. 0 Visual Studio .1 or Microsoft .NET Framework 2.0 Visual Studio .NET 2005 or Visual Studio 2008 (to build the sample code) Visio 2010 Microsoft . Visual Studio 2008. 254 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 254 .0 Visual Studio .NET Framework 1. All rights reserved. See Visio 2010 SDK Samples located in the Samples folder in this SDK for more information about specific requirements.NET Framework 1.NET 2005 or Visual Studio 2008 Visio 2010 Excel 2007 Word 2007 (to embed the drawing into a Word document) Microsoft .NET Framework 2.NET Framework 2.NET Framework 2.NET Framework 1.NET Framework 1.NET 2005.NET 2003 or Visual Studio 2005 Visio 2010 Excel 2007 Word 2007 (to embed the drawing into a Word document) Visual Studio .C# Flowchart sample application C++ Flowchart sample application TreeView sample application Office Plan sample application Visio 2010 Code Samples Library document) Microsoft .1 or Microsoft . or Visual C++ 6.0 (Service Pack 3 or later) Visio 2010 Microsoft .1 or Microsoft .NET 2005 or Visual Studio 2008 Visio 2010 2007 Microsoft Office System Known Issues and Notes  Some sample applications and code samples in the Visio 2010 Code Samples Library require the installation of Microsoft Office applications or Visio 2010 solutions and wizards.0 Visual Studio .1 or Microsoft . units of measure. geometry. methods. and properties are provided. and events. Shape Data was called Custom Properties. they both refer to the concept of attaching user data to Visio shapes. and about extending the functionality of Visio with macros.aspx?FamilyID=220549b5-0b07-4448-8848dcc397514b41&DisplayLang=en. In versions of Visio previous to Visio 2007. you must have administrative rights in Visual Studio. Details about the Save as Web Page methods. and information about common ShapeSheet tasks. these terms are used interchangeably. date and time values.com/downloads/details. Detailed information is provided for the XML for Visio schema. the ShapeSheet interface and the XML schema documentation. text. properties. This reference provides details on Visio objects. objects.microsoft. Save as Web Page Reference Provides an overview of using the Save as Web Page API with Microsoft Office Visio 2007. and COM (Component Object Model) add-ins. There is also an example of a Microsoft Visual Basic example of the Save as Web Page object model. Documentation This documentation contains reference material describing the Visio 2010 Automation Interface. All rights reserved. A sample Microsoft Visual Basic for Applications (VBA) macro is also provided. strings. the Visio type library. Details on each section. working with sheets and formulas. add-ons. XML Reference Provides an overview of XML for Visio. the Save as Web Page Interface. row. Volume 3: Programming with the Visio Object Model 255 . and cell in a ShapeSheet spreadsheet and details on functions you can use in formulas are provided. loading XML files created outside Visio. enumerations. 255 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Visio 2007 Automation Reference Provides an overview of Automation in Visio. including information about working with formulas. ShapeSheet Reference Provides an overview of the ShapeSheet spreadsheet in Visio.  Microsoft SQL Express 2005 is available as a free download at the following URL: http://www.  In order to compile SDK samples in Visual Studio running on the Microsoft Windows Vista operating system. It includes information about the Visio object model. inheritance. In the Visio 2010 SDK. such as adding and deleting ShapeSheet sections and referencing cells from formulas. Visio 2010 SDK folders Folder name \Docs \ \Libraries\ \Samples \ Description References and articles Support files Sample applications that demonstrate how to use the Visio programming model Development. customization. embedding custom XML data.h . and errors and warning messages.  Vaddon.h . You can choose to use no helpers.h – contains the prototype for the event call back function (VISEVENTPROC) along with the class definitions for VEventHandler and CVisioAddonSink. Volume 3: Programming with the Visio Object Model 256 .  Ivisreg. units of measure. Containers Folders Installed with the Visio 2010 SDK The following table describes the folders that are installed with the Visio 2010 SDK. All rights reserved.  Helpers. or nonMFC helpers or MFC-aware helpers.h .contains the definition of a superclass for Visio add-ons.contains helper functions for launching the Visio application.h. and extensibility tools Wizards to simplify developing Visio applications \Tools \ \Wizards\ Docs folder  visSDK.chm – entry point into help files for Visio 2010 SDK Documentation Libraries  CPP folder – C and C++ files o Include  AddSink. solution-publishing.contains the definitions of helper classes to be used with the wrapper code in Visiwrap. Table 9. 256 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.round-tripping XML data.  Visio. 257 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.  Vexe. It also provides an add-on 'manager' superclass called VAddon. All rights reserved.This file provides implementations for the routines prototyped in vao.tlb – Visio 2010 Save as Web type library o VisOCX.c .  Vdllmain.contains a set of wrapper classes and their implementations for the Visio automation API Source       AddSink.chm file with many examples of common tasks done in Visio through automation.h.contains helper functions for starting Visio and getting access to the IVisioApplication interface.c .contains the implementation of helper classes to be used with the wrapper code in Visiwrap. Volume 3: Programming with the Visio Object Model 257 .contains implementation of Visio's Advise Sink event handling.this ALWAYS GENERATED file contains the definitions for the interfaces  Visio_i. Directions are provided on how to copy code directly from the help file into your project. It allows VAddonderived classes to be compiled into an EXE with no additional effort. Helpers.h . Vaddon.implements the standard Windows message loop and window procedure for EXE based VAddon subclasses.h .tlb – Visio 2010 Drawing Control type library Samples The Samples folder contains the Code Samples Library folder which contains a . You can use VAddon as the base class for Visio add-ons.cpp .contains an implementation of DllMain for Win32 VSL's.contains definitions that define the interface between Visio and VSLs.h.o  Vao.provides the entry point for a Visio VSL.cpp . Vao.h . TypeLib folder – contains the following type library files o Visio.this ALWAYS GENERATED file contains the IIDs and CLSIDs  Visiwrap.tlb – 2010 type library o SaveAsWeb.cpp .cpp .cpp .c . Ivsireg. Volume 3: Programming with the Visio Object Model 258 . TreeView . The code is available in C++. and publishes the drawing to the Web or to a Microsoft Office Word document.msi) file for publishing Visio content. OfficePlan . or lets you print ShapeSheet data for all document styles.shows how you can use the Microsoft® Visio® 2010 Drawing Control to create an application that takes advantage of the drawing features of Microsoft Visio 2010 in a Microsoft Windows Form. Solutions Publishing – tool that provides a user interface that lets you generate entries to insert in the PublishComponent table in a Windows Installer (. or a page. VB. written in Microsoft Visual Basic® . Note: 258 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. and VB . The sample application can be used to select furniture from an inventory list and plan the space for a conference room or office. The sample application provides a summary view of a drawing that has many shapes and which therefore can be hard to view on the page. Each of these tools is covered in more detail later in this module.It also contains three complete projects:    FlowChart . Persistent Events .shows how to create a hierarchical drawing and its accompanying tree view in Microsoft® Office Visio® 2010.provides a user interface that lets you add persistent events in an active Visio document and modify existing persistent events. C#. Tools This folder contains Help files and for using a set of tools provided with the Visio 2010 SDK:     Event Monitor – tool that monitors events that are fired by an instance of Visio and reports events based on options you select in the Event Monitor user interface. All rights reserved. Print ShapeSheet .NET.provides a user interface that lets you print ShapeSheet data for one or more shapes. The sample application is a Visio COM add-in.shows how to create a Component Object Model (COM) add-in that automates the creation of a flowchart drawing from a Microsoft Office Excel® spreadsheet.NET. The code for this application is in C#. uses command bars in the Visio user interface. a document. Note: The final Visio 2010 SDK is expected to have a new VSTO Add-in Sample Application that uses a "ClickOnce" post-deployment action to install Visio template and stencil files and also samples for API functionality added in Visio 2010. You can take advantage of the full Visio object model (API) and you can pick the 259 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Visio Drawing Control type library The Visio Drawing Control can be used to embed the full functionality of the Visio drawing surface into your applications. Note: TypeLibs Included The Microsoft® Visio® 2010 Software Development Kit (SDK) provides type libraries for three application programming interfaces (APIs) that Microsoft Office Visio 2010 exposes. These wizards create a shell add-on or add-in project in Microsoft Visual Studio® . The Flowchart sample uses this interface to save Visio drawings as web pages. in Microsoft Visual Basic® . Save As Web type library The Save As Web interface is not covered in this class. Microsoft Visual C#®.tlb SaveAsWeb. This tool is covered in more detail later in this module. one for Visual Studio 2005 and the other for Visual Studio 2008.NET 2003.Wizards The Visio 2010 SDK contains two add-in wizards. Volume 3: Programming with the Visio Object Model 259 . The following type libraries are included in the TypeLib folder.NET.tlb VisOcx. and Microsoft Visual C++®. but there is a good example of how to use it provided in the Flowchart sample program in the SDK. to help speed the development process and demonstrate suggested practices for developing Visio add-ons or Component Object Model (COM) add-ins.tlb Contents Visio type library Save as Web type library Microsoft Office Visio Drawing Control type library Visio type library An overview of the Visio type library was given in the beginning of Volume 3 of this course. the path to which is SDK\Libraries: Library Visio. All rights reserved. and Microsoft Visual C++. Use of the Visio Drawing Control will be covered in the next module of this course: Module 5: Visio Drawing Control Changes from Visio 2010 SDK The following are changes to the SDK since the 2003 version.aspects of the Visio user interface you want to expose to better integrate Visio seamlessly into the user interface of your application.  Shape Studio has been removed Visual Studio 2005 and 2008 Add-in Wizards The Visio SDK installs wizards for creating Visio add-on projects in Microsoft Visual Studio 2005 and Microsoft Visual Studio 2008. These Wizards let you set up new Visio add-on projects in Microsoft Visual Basic . Once you have used the wizard to create a Visio project. Microsoft Visual C#. you can explore the project code and settings to learn more about how Visio add-ons should work. and create corresponding setup programs to install add-ons. 260 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 260 .NET. All rights reserved. They will not work with other versions of Visio. Volume 3: Programming with the Visio Object Model 261 .Microsoft Visual Studio 2010 also includes wizards to generate Visio 2010 VSTO add-in projects. The Visio projects that you create by using this wizard are compatible only with Microsoft Office Visio 2003 or later. 261 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. The Visio SDK is not required to use these wizards. open a stencil and build a simple flowchart. Follow the directions from the article How to Automate Visio with Visual Basic . When you use the wizard for the Visual Basic . Second. In the next steps we will build an add-on without the wizard and then build one with the wizard and contrast the two projects in Visual Studio. This add-on will start Visio. Imports Microsoft. We will contrast this with using the add-in wizard afterwards. Volume 3: Programming with the Visio Object Model 262 . you can create projects of the types listed previously as well as VSL add-ons. Depending on the programming language that you choose with this wizard. you can create projects of the following types:   Executable add-ons (EXEs) COM add-ins (DLLs) When you use the wizard for the C++ programming language. See the next step for details. you will need to add one line of code at the beginning of Module1 to work with the Visio 2010 PIAs. add the following line of code at the beginning of Module 1. Note: This example is a little out of date.NET or C# programming languages.Projects created by these wizards provide examples of recommended Visio development practices. Create a simple Visio add-on as a Windows Application.Interop 262 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Office. you can create different types of projects. Add a reference to the Visio 2010 type library instead of Visio 2002. you can explore the project code and settings to learn more about how Visio add-ons and add-ins should work. Once you have used the wizard to create a Visio project. 2. there are a couple of uninitialized variable warnings that should be fixed.Net listed in the Additional Resources section of this module. Try it! Create a project using the Windows Application template. To make this example work with the Microsoft Office PIAs. All rights reserved. Third. 1. exe file in the project bin folder. 2. Copy MyAddOn.exe to the desktop and make sure the add-ons paths in Visio is set to search this folder. In Visual Studio build the project. Close Visio. Give the Project and the Solution a name such as MyAddOn. Under Project Types choose Visual Basic. 5. From Visio modify the add-ons file path to include the Desktop. 4.Note: A finished example of this project is in the Samples folder for this course under the folder WindowApplication1. 6. This creates an . From Visio run the add-on from the Tools menu: Tools > Add-Ons > MyAddOn. 1. The addon will display the dialog below. All rights reserved. The default project displays the argument string that is passed to the add-on in a dialog box. Choose Next. We won’t change the default code. 5.exe file to the desktop. Try this! Create an add-on project using the Visio wizard for Visual Studio. 4. Create another project using the Visio add-in wizard. Under Templates choose Visio add-in or add-on. 8. Build > Build MyAddOn. 3. Restart Visio and run the add-on from the Tools menu. This starts the wizard. Choose File > New > Project… This opens the New Project dialog. 263 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Copy the WindowApplication1. Volume 3: Programming with the Visio Object Model 263 . 3. For the add-on type choose Create a Visio EXE add-on. You may have to restart Visio in order for the add-on to show in the Tools menu. Choose Next. Choose Finish to close the wizard and create the project. 7. exe") directly in the EventDblClick cell in the ShapeSheet.9. You can use the Format > Behavior dialog or enter the formula =RUNADDON("MyAddOn. Double click the shape. 264 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 264 . All rights reserved. Add a shape to the drawing and run the macro from the double click event of the shape. The add-on will display a dialog similar to the one below. but that is about it. but you can change this in the Project Properties window. Under Templates choose Visio add-in or add-on. Choose File > New > Project… This opens the New Project dialog. Close Visio and then start Visio. Under Project Types choose Visual Basic. The default project will display a message box when the add-in is loaded. Choose Next. Choose Next. 1.   The form is the startup for the application by default.Note: An add-on can be run when a cell formula is evaluated. In Visual Studio build the project. All rights reserved. Build > Build Solution. This adds the generated . When this happens. Visio automatically sends a command string to the add-on with the following information: /visio=instanceHandle /doc=docIndex /page=pageIndex /shape=NameID This information can be used by the add-on to access the shape that caused the add-on to execute. 9. 6. Select Load the add-in when the Visio application loads. For the add-on type choose Create a Visio COM add-in. 3. There is also no setup project created for us. 4. 7. The add-in loads when Visio starts and displays the message “MyAddIn connected”. This starts the wizard. 2. Give the add-in a meaningful name and description. Using Windows Application template The project is a bare bones project when it is created. Create another project using the Visio add-in wizard.dll to the Windows registry. In this example we completed the form and then added a module and code that launched Visio and built the drawing. Give the Project and the Solution a name such as MyAddIn. Choose Next. 8. A default form is created. Contrast the three projects in Visual Studio Let’s take a look at these three projects. Volume 3: Programming with the Visio Object Model 265 . 5. Choose Next. Try it! Create a COM Add-in project using the Visio wizard for Visual Studio. The developer has to do everything else. 265 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Choose Finish to close the wizard and create the project. 266 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.vb that serves as the startup location for the project. There is a setup project constructed by default. This module contains code that implements the interface for connecting to a COM add-in. In addition to this code. There is a setup project constructed by default.Using the Visio template to create an . Volume 3: Programming with the Visio Object Model 266 . the following is created as part of the project.EXE A default project is built with code that parses the command string that is sent to the add-on. Also created for this project:    A Connect.vb module. There is a default assembly created and default project resource strings. All rights reserved. When creating your own add-on this code can be deleted if it is not needed by the add-on. There is a default assembly created and default project resource strings. Whether a form is displayed is controlled by this code. Using the Visio template to create a COM add-in A default project is built with code that displays a message box when the add-in is first loaded.     There is a main procedure in VisioEXEAddon. There is a default application icon file. and other files to a Visio solution that you create Event Monitor The Microsoft® Visio® Event Monitor tool watches for events that are raised in an instance of Visio and logs all events of the types that you specify in the Event Options dialog box. All rights reserved. These tools can all be found in the SDK Tools folder. The Event Monitor reports all events that are sourced by the Application object. click Developer Reference. The Event Monitor. For the list of events that the Visio Application object can raise. except for events that are raised by keystrokes and targeted at an add-on window (the OnKeystrokeMessageForAddon event). QueryCancelSuspend. drawings. may not monitor and report the BeforeSuspend. and SuspendCancelled events. Persistent Events tool. The Event Monitor can help you determine which events to handle in your own solutions. or delete persistent events in drawings Use the Print ShapeSheet tool to write the ShapeSheet data to the Clipboard. depending on the order in which processes are suspended. see the Microsoft Office Visio Automation Reference. The Solution Publishing tool can be started from the SDK or from the Start menu. edit. template. the Event Monitor may be suspended before Visio and.Lesson 2: Tools The Visio 2010 SDK comes with a set of tools to aid developers in managing events and publishing solutions. The Event Monitor uses the AddAdvise method of the EventList collection of the Visio Application object to monitor and report events by the Visio Application object. 267 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. hence. Lesson Objectives After completing this lesson you will be able to:     Use the Event Monitor tool to track events fired in Visio Use the Persistent Events tool to add. or to the printer Use the Publish Components tool to bind stencils. (On the Help menu. even if you include them in the Events to monitor list. to a file. Volume 3: Programming with the Visio Object Model 267 .) Note: Because the Event Monitor runs in a separate process from Visio. and Print ShapeSheet can all be started from the Developer tab in Visio once the SDK is installed. ShapeAdded is the name of the event that fired. additional data about the event. When the Event Monitor starts. which is determined by the number of events that have fired since Visio was started. the Event Monitor reports the event firing as follows: 21365 | ShapeAdded Rectangle [/doc=1 /page=1 /shape=Sheet. Information within the 268 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. the ShapeAdded event fires. and the name of the shape itself. the Event Monitor starts a new instance of Visio. Visio gives each event a unique sequence identifier to distinguish between separate firings of the same event. For example. Volume 3: Programming with the Visio Object Model 268 . depending on the event and your Event Monitor settings. if you drag a Rectangle shape onto the drawing page. Within the brackets. Event types previously set to be ignored in the Event Options dialog box are not listed at startup. When there has been no activity in Visio for a time. All rights reserved. or if Visio isn't already running. the Event Monitor tool displays the index number within the Documents collection of the document in which the event fired.1] In this log entry:     21365 is the event sequence number. that is. The Event Monitor tool automatically connects to a running instance of Visio. that they are set to be monitored. the Event Monitor tool displays its name and. Rectangle is the name of the master of the shape that was added. When a monitored event fires. the log displays the following information:     The version of Visio that it has connected to or started The Microsoft Office Visio Type Library version number The process ID of the Visio instance The list of monitored event types and their status.To start the event monitor from Visio choose Developer > Event Montior. When all events in the Visio events queue have been processed. In the log window. Visio fires the VisioIsIdle event. the name of the page where the shape was added. Microsoft Visio fires the NoEventsPending event. When Visio has emptied its message queue. you will see these two events at the bottom of the list in the event window. and then passes that number as one of the arguments to the VisEventProc function you write to handle that event. 6. Draw a shape using one of the drawing tools. Start the Event Monitor from Visio. MustFlushScopeEnding. Close Visio. depending on how they are added. Control drag duplicate is 1184. Now it is easier to see some of the other events that fire when an action occurs in Visio. Duplicate a shape. Remove MouseMove from the list. From the Event Monitor choose Tools > Event Options. Volume 3: Programming with the Visio Object Model 269 . Connection to Visio has been terminated. Drawing shapes with the drawing tools gives unique commands for each tool used. Note that each of these actions causes a ShapeAdded event. Stop monitoring MustFlushScopeBeginning. 7. Demo: Use Event Monitor to track actions in Visio 1. Add a shape from a stencil. It lists the events being monitored and then lists results for each new event as it fires. Just be sure to test for performance as EnterScope gets called a lot! 10. 5. but ShapeAdded doesn’t tell you how a shape was added. then click Connect to Visio. How can we distinguish between these actions? 9. Copy and paste a shape. All rights reserved. There are still a lot of events firing when the mouse moves. click Tools. To restart Visio. 8. Note the message displayed in the monitor.brackets is displayed only if the Include additional event information box is selected in the Monitor Options dialog box. 4. Paste a shape is done with command number 1022. 269 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Duplicate is 1024. 2. 3. and NoEventsPending. Note that there are a lot of MouseMove events every time the cursor moves in the Visio window. Therefore it is possible to tell exactly how any shape gets created! Tip: This is really handy if you want to do something different for shapes added to a drawing. Note that there is always an EnterScope event that occurs for each of these actions and within the EnterScope event we can test the command ID that was just executed. Add a shape from stencil is done with command ID 1246 – Drop on Page. click Developer Reference). usually when users create a Visio document based on a template or open a Visio document or template. Many solutions that are a part of the Visio product persist events in their templates. The Persistent Events tool displays the list of events persisted in the active document or template and for each event. DocumentCreated is the name of the persistent event that fired. From the Event Monitor choose Tools > Connect to Visio. In the Event Properties dialog box. Visio is restarted and monitoring is resumed. and passes the argument /cmd=DocCreated to the add-on to indicate that DocumentCreated was the event that fired. and /cmd=DocCreated is the argument passed to the add-on by the event. calls the OrgC11 add-on. By persisting events in a document or template. OrgC11 is the universal name for the Organization Chart add-on in Microsoft Visio. you can make Visio run add-ons in response to user actions. When writing an add-on solution. shows the add-on that runs when that event fires and any arguments passed to that add-on. see the Microsoft Office Visio Developer Reference (on the Help menu. in 270 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. For addons to run and take the appropriate action. In the tool's list of persistent events for the active document. Whenever a new document is created based on the Organization Chart template. Volume 3: Programming with the Visio Object Model 270 . You can see evidence of this by opening a new or existing organization chart document (drawing) based on the Organization Chart template and then. For more information about persistent events in Visio. the DocumentCreated event is persisted in the Organization Chart template. About Using the Persistent Events Tool The Persistent Events tool provides a user interface that enables you to add and modify persistent events in the active Microsoft® ® Visio® Document object's EventList collection.11. For example. opening the Persistent Events tool. its action is to run the Organization Chart add-on. they must know which event fired. after making sure that this document is active. you'll see a row that contains the following data: DocumentCreated OrgC11 /cmd=DocCreated On this line. and when this event fires. All rights reserved. the DocumentCreated event fires. add persistent events that call your add-on in the Event Properties dialog box (which is accessible from the Persistent Events tool). 5. All rights reserved. 3. to change an argument string. Try it! 1. the value you enter in the Argument box gets passed to the add-on. type its name. 2. Optionally. Volume 3: Programming with the Visio Object Model 271 . pass an argument to the add-on. Note: Note: You must first install the new add-on before persisted events will run it. either select it from the list. or. If the add-on's name you type doesn't exist. 7. you may want your add-on to respond differently if a new document is created than if an existing document is opened. When the event you selected in the Event list fires. for example. This feature is useful if the add-on needs to handle different events differently. DocumentCreated DocumentOpened MasterAdded BeforeMasterDelete PageAdded BeforePageDelete ShapesDeleted The Universal name list box is populated with the names of all add-ons in the Add-ons collection of the Visio Application object. Note that the DocumentOpened and DocumentCreated events are persisted in 271 the organization chart template. 2. For example. The dialog below is displayed. 4. or to delete persistent events.the Event box. you can use it to inform the add-on which event called it. you can use the TraceFlags property of the Application object to view errors in the Immediate window. 6. you can select from the following list of persistable events sourced by the document object: 1. Start the Persistent Events tool: Developer > Persistent Events. Create a new organization chart drawing in Visio. To specify the add-on to run when the event fires. Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Visio doesn't display an error message. You can also use the Persistent Events tool to edit existing persistent events. for a new add-on. however. 3. and deleted by using the Visio object model. All rights reserved. Add a new persistent event for PageAdded and hook the event to the add-on created in the last section of this module. edited. Persistent Event information in the Visio object model Persistent Events can be added. MyAddon. The Event object has a Persistable property (read-only) and a Persistent property (read-write). The Target and TargetArgs properties contain the add-on name and the argument 272 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Set the Persistent property to True. Volume 3: Programming with the Visio Object Model 272 . This add-on displays the command string passed to it. You should see something similar to the dialog below. This will edit an existing PageAdded persistent event if it exists or add it if it does not. Run the macro PrintPersistentEvents. This drawing was created from an organization chart template so it already has some persistent events in it. Try it! 1. Volume 3: Programming with the Visio Object Model 273 . The Print ShapeSheet dialog is displayed below. or the current drawing page. This prints the persistent event information from the object model to the Immediate Window. The Event property of the Event object contains the event code. the code for PageAdded is visEvtAdd+visEvtPage.g. Print ShapeSheet The Microsoft® Visio® Print ShapeSheet tool provides a user interface that lets you print ShapeSheet spreadsheet information for one or more selected shapes. Start the Persistent Events tools and view the existing persistent events. Note: There is a known problem that causes an overflow error when working with event codes with values greater than &H8000. Open PersistentEvents. e. 4. To get around the problem pass the event code argument using the hex representation instead of the Visio constants. a file. To start the Print ShapeSheet tool. 273 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. View the code.. You can send the result to the Clipboard. 2. View the code. You can use the Print ShapeSheet tool to print data from various sections of the ShapeSheet and to search for cell references and dependencies in various formulas. the styles defined in the document. 3. Run the macro EditOrAddPersistentEvent. from Visio choose Developer > Tools > Print ShapeSheet.string. a Visio document. or a printer. All rights reserved.vsd from the Samples folder. Clipboard. 274 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. If there are grouped shapes on the drawing page and you want to print data for individual shapes within groups. Volume 3: Programming with the Visio Object Model 274 . and All Shapes. and Printer. All rights reserved. The default choices under Include sections will change depending upon the choice made.Under Sheet type: choose from: Selected shapes. select Include group subshapes. Page. Use this section to choose which ShapeSheet sections are to be captured in the output. Styles. Under Send to: choose from File. Sample output that was sent to a text file is shown below. Document. Note that both a cell’s value and it’s formula are included. Publish Component Beginning with Microsoft Visio 2003, you can publish your add-ons, templates, stencils and other files as components to be integrated with the Visio application. Publishing components is the preferred method of integrating add-ons and other content with Visio. It offers tighter integration with the Visio application, and better performance on add-on discovery. The publish component functionality enables developers to include a PublishComponent table in the Microsoft Windows Installer file that they create to install content (such as add-ons, templates, stencils, or other files). Each PublishComponent table entry contains information pertaining to how a specific file to be installed should be displayed in the Visio user interface. During installation, these entries are published to the Visio registry. Visio uses this information to display the add-on in its user interface, and install on-demand or repair the file as needed. Publishing Content Tip: The following content is derived from the Visio Insights blog produced by the Visio team at Microsoft. This is a great source of practical “how to” information. 275 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 275 Publishing a piece of content to Visio adds entry points to the user interface side-by-side with content created by Microsoft. For a stencil this translates into a menu entry added to the File > Shapes fly-out menu while for a template this means an entry in Visio’s startup screen (as seen below) and in the File > New fly-out menu. Method #1: Sharing Templates using Path Discovery The simplest way to publish a template to Visio is to use the Path Discovery method described below: 1. Copy your template and supporting stencils to a known location on a drive. 2. Add the location defined in step 1 to Visio’s “Template Paths”; this tells Visio where to find extra content to populate its startup screen. 3. Restart Visio – your template should appear in the (Other) category. 276 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 276 The advantages of this approach are:   It is simple. It is supported across most versions of Visio. It however has a few drawbacks:      Your users may be subjected to potentially long and error prone manual work. Your templates will always end up in the (Other) content category in the startup screen. You don’t have any way of repairing content on a user’s machine if it gets damaged. You cannot control which language of Visio will load your stencils and templates. This approach does not scale well. The Path Discovery publishing method does just that: every time you boot Visio it searches a user’s hard drive for content files – an expensive operation. Sharing templates through Path Discovery is good for small scale content deployments as well as deployments to older versions of Visio. Method #2: Sharing using the PublishComponent System The PublishComponent system introduced in Visio 2003 lets developers use Windows Installer technology for template distribution to register their content with Visio in a rich and robust way. The main advantages of this method are quite interesting:      The Windows Installer setup wizard is familiar to users and easy to use. You benefit from Windows Installer repair, install-on-demand and add/remove features. You may choose what language versions of Visio to publish your content to. The approach scales well: Visio only rebuilds its content cache, a moderately expensive operation, when new content is published. The approach is tried and tested since the product publishes its own content this way since the 2003 release. That said, using the Publish Component system is:   A little more complicated than the Path Discovery method. Will only work for Visio 2003 and or later. To use this method you’ll need Visual Studio .NET or later, the Visio 2003 SDK or later. 277 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 277 Try it! 1. Create a simple template and stencil that will be added to the published solution. Save the files. 2. Create a setup project in Visual Studio. 3. Select the "Application folder" and change its default location property to your target install location. Add your template and their supporting stencils to this location by dragging files into the folders. Your project should look something like the figure below at this point. 278 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 278 4. Build the project. This will produce an MSI file - a multi-table installation database that is used by windows to coordinate setup. 5. Install the package as is. Visio will not discover the files the MSI installed. To notify Visio on the whereabouts of these files, the next thing to do is populate the PublishComponent table of the MSI produced above with registration data. Once installed, this extra information will force Visio to rebuild its content cache and incorporate and display the new templates and stencils. 1. Start the Solution Publishing Tool that is included with the Visio SDK (a.k.a the publish component tool). This tool may be found in the Start menu entry for the Visio SDK. 2. On the File menu, select New. It will prompt you for an MSI. Navigate to the one that you've just built. 3. This will present the Visio Files that are in MSI. You must now, for each entry: a. Set the LCID of the language for which you want the templates to be accessible in. Do the same for the supporting stencils. b. Set the position in the Visio startup screen hierarchy you want the template to live in. This is defined by separating different levels of the hierarchy by “\” symbols for example: “MyTemplateCategory\MyTemplateSubCategory\MyTemplateName”. Do the same with the supporting stencils, setting their location in the File > Shapes flyout. Note: For VSL files that contain more than one add-on, select the file in the list and click Add Add-on on the Edit menu to specify information about the additional add-ons implemented in the VSL. To make the changes described above double click on each entry to bring up the “Template Information” dialog seen below, or its counterpart the “Stencil Information” dialog. 279 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 279 4. Press the "!" button in the tools toolbar; this will make modifications to the MSI's Publish Component table. 5. Install the MSI. The MSI can now be distributed; Windows Installer and Visio will do the rest. Although we haven’t discussed it here, the same techniques can be used to publish add-ins and help files. 280 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 280 NET) sample code from the SDK Scenario Build the Flowchart code sample in Visual Studio. All rights reserved.Lab 3. Build and install the SDK Flowchart sample add-on for VB. 281 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.NET) and run.NET Framework 2. create a drawing from the Flowchart(VB .1 or Microsoft . install the COM Add-in.NET 2. Review the basics of how this sample application is put together Estimated time to complete this lab: 60 minutes Before You Begin To complete this lab.0 Visual Studio 2005 or later What You Will Learn After completing this lab.8: Build and run the Visio SDK Flowchart sample During this lab.  Software required for the SDK Flowchart code sample: o o o o o Visio 2010 Excel 2007 Word 2007 (to embed the drawing into a Word document) Microsoft . Volume 3: Programming with the Visio Object Model 281 . you will need:  Participants should have completed the review of this module before completing this lab. you will: 1.  Visio 2010 SDK installed and configured. you will be able to:  Build and run the Flowchart example from the Visio 2010 SDK  Understand the software architecture for this sample Exercise 3: Build and run the Flowchart (VB.NET Framework 1. 2. 4. The following dialog will be displayed: 8. Copy the project files from the SDK folder to the Visual Studio 2005 Projects folder.NET) template. The add-in will build a multi-paged flowchart. 6.sln to open the project in Visual Studio 2005.msi in the \Visual Studio 80\bin\Debug\Setup folder. This copies the active page to a Word document. Double-click FlowchartSampleSetup. Create a new drawing from the Flowchart (VB. 9. 11. Choose Yes.NET) in the Active Application Add-ins list 7. It has two buttons for publishing the drawing to Word and publishing the drawing to the web. 3.msi to install the COM Add-in. This creates FlowchartSampleSetup. Click the button to Save Document as a Web Page. 5. Find FlowchartSample (VB. Choose File > Options > Add-ins b. Volume 3: Programming with the Visio Object Model 282 . In the Visual Studio 2005 Projects folder double-click …\FlowChart\VBNet\Visual Studio 80\FlowchartSample. All rights reserved.Tasks 1. Start Visio and verify the add-in is loaded. 10. Note that a new toolbar has been created: SDK Flowchart Publication. a. but screen updating is turned off so you won’t see anything until the process is complete. Choosing No will do the same thing. To put the other pages into Word you would need to go to each page individually and click the button to publish to Word. From the SDK folder you can copy everything from …\visSDK\Samples\Flowchart. Click the button to publish to Word. File > New > SDK > Samples > Flowchart (VB.NET). 282 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. In the Solution Explorer window right-click on FlowchartSampleSetup and choose Build. In the Solution Explorer window right-click on FlowchartSample and choose Build. 12. It listens for three events: a. which is defined in the Visio type library. Exercise 2: Code review. The code in this class processes marker events created by this Flowchart sample. DocumentCreate – creates a new drawing when a user creates a new document based on the Visio SDK Flowchart Sample template b. based on data contained in a Microsoft Office Excel worksheet.vb This class implements the IDTExtensibility2 interface. The Flowchart Sample calls AddAdvise once in Visio on the Connect module where it registers for Marker events sourced by the Application object. an instance of this class must be passed as the EventSink argument in calls to AddAdvise. DocumentOpen – creates a custom command bar when a document created from the SDK Flowchart Sample template is opened c. 283 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.vb This class creates a Visio document containing flowchart drawings. Scenario This is a high level break down of how the add-in has been architected.vb This class is an event sink for Visio events. DocumentCreator. handleRightMouseClick – handles the case where the user does a right mouse click on a flowchart shape and chooses Number of Connections… 3. Volume 3: Programming with the Visio Object Model 283 . It handles event notification by implementing the IVisEventProc interface. All rights reserved. The drawing process is driven by the CreateDrawing procedure which is initiated from the DocumentCreate event handler. It handles events from Visio which were specified using AddAdvise. In order to be notified of events. for which the Flowchart Sample add-in will listen. allowing it to serve as a COM add-in for Microsoft Office Visio and initializes the Visio Application object's EventList with events. Connect. Right-click a flowchart shape and choose Number Of Connections… This command displays a message box show the number of connections and the name of the connectors glued to the shape. Code components 1. EventSink. 2. All rights reserved. Flowchart (VB.xls – Excel file containing the shape and connection information for the flowchart.vst – Visio template file for creating the drawings. 7.4. 6. Assemblyinfo. Shared.vb Provides the assembly information for the Flowchart Sample Add-in. It also contains methods to handle the click events for the buttons on the custom command bar. CustomCommandbar. 2. Other components 1. Flowchart. Volume 3: Programming with the Visio Object Model 284 .vb Low level shared utilities and constants.NET). Publisher.vb This class provides procedures to export a document to either a Web page or a Microsoft Office Word document. 284 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.vb Creates the custom command bar "SDK Flowchart Publication" and adds it to the Visio CommandBars. 5. com/en-us/library/ms409266. Event Monitor.microsoft. Persistent Events.aspx 285 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. including the ShapeStudio.SDK Introducing the Microsoft Visio 2010 Beta SDK Visio Insights blog about the first beta release of the 2010 SDK. and tools.com/visio/archive/2009/11/19/introducing-the-microsoft-visio-2010-beta-sdk. code librarian code snippets.com/en-us/library/aa167946(office.microsoft.com/downloads/details. Print ShapeSheet. http://blogs.microsoft.microsoft.com/downloads/details. header files.aspx Visio 2007: Software Development Kit The Microsoft Office Visio 2007 Software Development Kit (SDK) contains the latest documentation.Additional Resources . and Solution Publishing tools. libraries and tools that you need to develop custom solutions for Microsoft Office Visio 2007. documentation.aspx?familyid=557120bd-b0bb-46e7-936ab8539898d44d&displaylang=en Visio 2002 Technical Articles Technical articles from the Visio 2002 SDK.aspx Visio 2003 Software Development Kit (SDK) The Visio 2003 SDK contains sample applications.msdn. samples.11). but they aren’t repeated in later versions of the SDK. Volume 3: Programming with the Visio Object Model 285 . http://www. All rights reserved. Many of the technical articles are still relevant. http://msdn2. http://www.aspx?familyid=373d34b8-5ef7-4e6e-a582c8d6b5ee4e33&displaylang=en Microsoft Office Visio 2007 SDK Release Notes http://msdn2. microsoft.NET.aspx How to automate Visio with Visual Basic .com/kb/305199 286 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. http://support.com/en-us/office/aa905478.NET This article demonstrates how to automate Visio using Visual Basic . All rights reserved. It does not use the add-in wizard for Visual Studio.microsoft. Volume 3: Programming with the Visio Object Model 286 .Visio Developer Portal http://msdn2. What are some reasons for using the event monitor? 4.Review: SDK Questions 1. What is the advantage of using Publish Components over using Visio’s File Paths to detect file locations? 287 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. What are persistent events? 5. 2. All rights reserved. Volume 3: Programming with the Visio Object Model 287 . What kind of add-ins and add-ons can be created for Visio with the add-in wizard in the SDK. What versions of Visio do projects created with this wizard work with? 3. All rights reserved. It offers tighter integration with the Visio application. 3. COM add-ins (DLLs) 2. Discover what events fire when certain actions occur in Visio. VSL add-ons (can only be created with C++) b. Executable add-ons (EXEs) c. 5. Depending on the programming language you choose: a. These are actions defined to be kicked off when an event occurs.Answers 1. and better performance on add-on discovery. Volume 3: Programming with the Visio Object Model 288 . They are saved with the drawing and do not need to be reestablished each time the drawing is opened – thus they “persist”. Only Visio 2003 and later. 288 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. 4. as an embeddable component.Visio Drawing Control The Microsoft® Visio® Drawing Control offers the full functionality of the Visio application through the rich Visio object model. the Visio drawing control can provide a diagramming environment for application users within the context of your own application's user interface (UI). You can drive the Visio drawing control programmatically by events or by code in your hosting application. Volume 3: Programming with the Visio Object Model 289 . Module Objectives After completing this module you will be able to:       Describe how that drawing control can be used to provide a graphics rich application without using the Visio user interface Identify the features of the Visio drawing control and example use scenarios. All rights reserved. Describe best practices for creating new applications that use the drawing control. Deploy the Visio drawing control with your application. 289 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Embed the Visio drawing control in a variety of host applications. Alternatively. Use the properties of the Visio drawing control API to manage Visio from your host application. Volume 3: Programming with the Visio Object Model 290 . Office 2003 and later containers (such as Microsoft Word). The new functionality provides more power than just simply embedding a Visio drawing into an OLE container document.Lesson 1: Concepts The Visio Drawing Control is a Microsoft ActiveX control that provides full access to the Visio object model (API) and user interface so that you can integrate the Visio user interface. however.NET 290 2003 and later. You cannot create your own UI. provides functionality to address these scenarios. With the drawing control you can create your own application with its own interface and be in control of how much of the Visio user interface is presented to the user.NET Windows Forms. which rules out technologies such as . The Visio Drawing Control is provided with all version of Visio and is installed when you install Visio. All rights reserved. Using a Visio drawing as an OLE object allows you to view the diagram in the container application. customize its appearance. link the OLE object to the actual Visio document to reflect changes. Like any ActiveX component. like Word. and edit the Visio drawing by activating the Visio application from within the container document. The Visio Drawing Control allows the developer to provide Visio functionality within the context of another application. you are still working within the Visio user interface. The Visio drawing control. Microsoft Internet Explorer Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. This level of integration allows the developer full control over the Visio user interface integration with the host application. and automate Visio in your applications. it can be embedded in custom host applications developed using Visual Studio . and allows you to develop new Visio solutions that go beyond creating add-ons and add-ins for Visio. You are also limited to application hosts that implement an OLE container. In the case of in-place OLE activation. Lesson Objectives After completing this lesson you will be able to:    Describe how that drawing control can be used to provide a graphics rich application without using the Visio user interface Describe the requirements of deploying an application containing the drawing control Describe the types of container applications that can host the drawing control Requirements / Containers The Visio drawing component is essentially an ActiveX® wrapper for the main Visio library. a Microsoft Visual Basic for Applications (VBA) form in Visio. Medium-Low. the control warns the user that it is an unsafe file (unless the end user's browser security level is set to Medium. and other ActiveX component containers. Because it essentially repackages the Visio application engine in a component. the Visio control is installed with the Visio application setup program and requires the Visio client application to initialize. or Low). The sample application can be used to select furniture from an inventory list and plan the space for a conference room or office. install Visio.0. another ActiveX control. Microsoft Visual Studio 7.0.1 and higher. The Visio component provides the full functionality of the Visio application rather than a small subset of features. Demo: Drawing Control The Office Plan Sample Application included with the Visio SDK shows how you can use the Drawing Control to create an application that takes advantage of the drawing features of Visio in a Microsoft Windows Form. Security considerations The Visio Drawing Control is targeted for use in an intranet environment. If the user does not have the Visio client application installed on the machine.5. Before it is run in any version of Internet Explorer. the control will fail to initialize in the host container. However. it is more of an embeddable application component than the typical ActiveX control found on a Web site. All rights reserved. Although the component uses the ActiveX architecture. you cannot embed the Visio Drawing Control in another Visio drawing. Microsoft Visual C++ 6. all users must have licensed copies of a version of Visio that supports the Visio Drawing Control on their computers to use it. Run-time requirements and distribution of your application Microsoft Visio must be installed on any computer where the Visio Drawing Control will be used. Volume 3: Programming with the Visio Object Model 291 . Note: To install the Visio Drawing Control. and other ActiveX control containers. or a Visio solution window. The Visio Drawing Control does not support the IObjectSafety interface. When you distribute your application.5 and greater. Host container applications that support the Visio Drawing Control You can embed the Visio Drawing Control in Microsoft Visual Basic 6. 291 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. The Minimal Install option of Visio will install the Visio Drawing Control. The sample creates a simple office floor plan that permits the end-user of the application, presumably a corporate administrative assistant, to do the following:     Click any of three furniture shapes to add them to the drawing. View dynamically updated information about the furniture that has been added. View dynamically updated information about the total retail and wholesale costs of the current contents of the office plan. Save the results to a Visio drawing file and then re-open the file. The code for this sample application is written in the C# programming language, and is designed to work with Microsoft Visual Studio 2005 or Microsoft Visual Studio 2008. Demo of Office Plan sample from the SDK. The code for this sample is included in the Visio 2010 SDK. Programming features implemented in the Office Plan Sample application This sample application shows how to do the following:          Embed the Drawing Control in a Windows Form. Use the Drawing Control interactively Respond to various Visio events fired by user actions Use mouse events to capture the right-click actions on a drawing shape Use the MarkerEvent event and the EventDblClick ShapeSheet cell to respond to when the user double-clicks shapes in the drawing. Create a custom Windows form to display shape product information in an adjacent DataGrid control Use events to keep track of the shapes within the drawing and to calculate total price information for these shapes Save Visio drawings created by using the Drawing Control Open Visio drawings in the Drawing Control To build the sample code in the Office Plan Sample in Visual Studio 2005 1. Double-click OfficePlanSample.sln in the following folder: C:\Program Files\Microsoft Office\Office14\VisSDK\Samples\Office Plan\CSharp\Visual Studio 80. 292 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 292 The folder path may differ depending on where the SDK was installed. Note: 2. In Visual Studio 2005, click Debug > Start Without debugging. The application is started. The application image is shown below. Add shapes to drawing 3. Click on the furniture buttons on the form. A shape is added for each click. The drop location on the page is adjusted so that the shapes do not lie in exactly the same place. 4. As each shape is added the Total Price figures on the form are updated and the Product data grid is updated. It maintains an accurate total of all of the shapes in the drawing. 293 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 293 Keyboard shortcuts are available Many Visio keyboard shortcuts are supported in the drawing control. 5. Multi-select shapes and enter the keyboard shortcut Ctrl-G. The shapes are grouped together. 6. Zoom in/Zoom out using Ctrl-Shift left mouse/right mouse. 7. Zoom to whole page with Ctrl-W. Delete shapes 8. Delete an individual shape from the drawing. 9. Delete a grouped shape from the drawing. In both cases the Total Price and Products grid are updated. Save the drawing 10. Choose File > Save… and enter a file name in the Save Visio Document dialog. 294 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 294 Start a new drawing 11. Choose File > New. A new blank drawing is created. 12. Choose File > Open and open the file saved earlier. Try this! Application Architecture Review Now let’s take a look at how this application was architected. The following sections describe the structure of the Office Plan code sample. Go through each section and view the code and shapes to see how it works. Embed the Drawing Control in a Windows Form. When the application is started the frmOfficePlanSample form is displayed. 1. In Visual Studio in the Solution Explorer window, right-click frmOfficePlanSample.cs and select View Designer. Right-click frmOfficePlanSample.cs again and choose View Code. Both the code and design view for the form are displayed. 2. Look for the Main procedure in the code view of the form. This is the main entry point for the application. It creates a new instance of the form. 3. Just above the Main procedure is the following code: public OfficePlanSampleForm() { // Initializing the components of the form is required for // Windows Form Designer support InitializeComponent(); } This code is executed when the form is created. The InitializeComponent procedure is code that is generated by the forms designer. It contains all form variable initialization, control initializations, and menu definitions. 4. View the design view of the form. Click on the drawing control and scan its properties in the Properties window. Note its name. 5. Click on the Events button in the Properties window for the drawing control. Scroll through the list and note there are two event procedures defined for the drawing control: MouseUpEvent and VisibleChanged. 295 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 295 The code for the VisibleChanged event is in onDrawingControlVisibleChanged. This event is triggered initially when the form is created. Within the event procedure is a call to setUpVisioDrawing. Within setUpVisioDrawing is the code to establish the connection to the Visio application object. It hides all Visio docked windows and then turns off display of rulers, grid, page tabs, scroll bars. It then gets the viewing size of the window rectangle and does some calculations for positioning shapes when they are created. It then initializes an event sink to watch for Visio events with a call to initializeEventSink. Event management When using the Office Plan application the user is directly interacting with the Office Plan application and indirectly interacting with Visio through the Visio drawing control. Events can be fired and listened to for both the Office Plan application and for Visio. For example, when the user clicks a button control in the Office Plan application, there is a click event that is triggered. This click event instructs Visio to add the appropriate shape to the page. The action of adding the shape to the page causes Visio’s shape added event to fire. The shape added event is used to keep track of the number of shapes in the drawing and keep the product information up to date. Why bother listening for Visio’s shape added event when we know that a shape is going to be added when we click the furniture button? If everything works perfectly you might can assume that a shape will be added and go ahead and process it, but in reality something might go wrong. For example, the stencil that contains the shape’s master may not be accessible by Visio and an error condition may be raised. It is best not to add the product information for a new shape until you are sure that the new shape has finished being added to the drawing. That doesn’t happen until the Visio shape added event is fired. Respond to Visio events fired by user actions The procedure initializeEventSink sets up for listening for events from Visio. This procedure is in frmOfficePlanSample.cs. The following events are established in the event sink:    Shape add: OnAddProductInformation will be called when a shape is added Shape delete: OnRemoveProductInformation will be called when a shape is deleted Marker events: Used to trap double clicks on a shape for those shapes whose doubleclick event runs the QueueMarkerEvent addon. OnShapeDoubleClick will be called. The VisEventProc method also listens for Visio’s NoEventsPending which occurs after Visio has finished flushing its events queue. When a shape is added or deleted they are simply added to a queue of 296 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 296 shapes that need to be processed to update the product information. When the event NoEventsPending is fired, the added and deleted queues are processed. During processing of the shapes added and shapes deleted queues the totals for Retail price and Wholesale price are updated on the form and the data grid is updated to reflect additions and deletions from the drawing. Use events to keep track of the shapes within the drawing and to calculate total price information for these shapes 1. In the design view of the form select one of the furniture button controls. 2. In the property window note its name. 3. Scroll through the properties list and find the value in the Text property. This is the master name that is retrieved from the stencil when this button is clicked. 4. Select the event procedures button in the properties window. Scroll through the list and find the click event procedure. The event procedure is onFurnitureButtonClicked. The onFurnitureButtonClicked method handles the event that is raised when one of the furniture buttons is clicked. The button text field contains the corresponding name of the master shape on the product stencil. The master is retrieved and dropped on the page. 5. When the furniture shape is dropped on the page Visio’s ShapeAdded event is fired. We saw earlier how the event sink was established to listen for this event. Use mouse events to capture the right-click actions on a drawing shape 1. In the design view of the form select the drawing control. 2. In the properties window scroll through the event list and find the MouseUpEvent. Note that it is assigned to the procedure onDrawingControlMouseUp. The onDrawingControlMouseUp checks for different kinds of mouse up actions which can occur when a shape is right-clicked, such as when the user is using keyboard shortcuts to pan and zoom, or when a user is selecting a shape. The main body of the code for onDrawingControlMouseUp is below. // Check if the event was raised because of a right mouse button click, // and the user is not zooming (control+shift+right mouse click) // or selecting shapes (control+right mouse click). if ((eventData.button == (int)VisKeyButtonFlags.visMouseRight) && ((eventData.keyButtonState & (int)VisKeyButtonFlags.visKeyControl) ==0 )) { // Look for a shape on the drawing page at the click location. clickedShape = Utility.GetClickedShape(drawingControl, 297 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. Volume 3: Programming with the Visio Object Model 297 Volume 3: Programming with the Visio Object Model 298 . In the design view of the form select the drawing control. eventData. All rights reserved. Use the MarkerEvent event and the EventDblClick ShapeSheet cell to respond to when the user double-clicks shapes in the drawing The detecting of when the user double clicks on a shape is handled with marker events. The // coordinates need to be converted from the Visio page // units that are in the event data to Windows pixel // coordinates. 1. The Events section for the Office Chair shape is shown below.cancelDefault = true. 2. the shape’s double click event fires which evaluates the EventDblClick cell in the shape’s ShapeSheet. eventData. This causes the MarkerEvent to fire. In addition the MarkerEvent is passed the string “/officeplan /cmd=1” which is used by the marker event listener to verify that the marker event was 298 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Note that the formula calls RUNADDONWARGS and passes the string “QueueMarkerEvent”. We saw earlier how the event sink was set up to listen to marker events.MapVisioToWindows(drawingControl.y)).x. // Show the shortcut menu at the click location. Utility. eventData.x.Show(this. When you double-click on a shape within the control. if (clickedShape != null) { // Cancel the default processing of this event since // it will be handled in this method. shapeShortcutMenu. This uses Visio’s SpatialSearch method of the page to determine the closest shape to our mouse click location. Now let’s look at how a marker event gets fired in the first place. 3.y). } } Finding the shape is done inside Utility.eventData. In the properties window scroll through the event list and note that there is no double click event exposed for the drawing control.GetClickedShape. eventData. // Update the total prices and the data grid // add the information from the new shape.AddProduct updates the datagrid with the data for this productID when a shape is added. productData. The code trail starts with VisEventProc. This is used to associate the product id with the shape. All rights reserved. 4. The variable productId contains the value in the shape data cell ProductID from the shape. The method productData.caused by double clicking a shape that it can recognize. the RUNADDONWARGS functions appends the string “/doc=id /page=id /shape=sheet. In our sample application this is used to get a reference to the specific shape that was double-clicked.RemoveProduct decrements the product information in the data grid with a shape is deleted. Setting TotalRetailPrice updates the retail price on the form.id” to the string passed to the marker event. This calls handleMarker.xml file. The following code comes from the onAddProductInformation procedure which is called when a Visio shape added event is fired. which gets a reference to the shape that was double clicked and then calls onShapeDoubleClick. Setting TotalWholesalePrice updates the wholesale price on the form. 299 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. but contains no shape data except for the ProductID which is used to identify the corresponding ProductListItem in the xml file. TotalWholesalePrice += productData.GetRetailPrice(productId). The method productData. Volume 3: Programming with the Visio Object Model 299 . Create a custom Windows form to display shape product information in an adjacent DataGrid control The information displayed in the datagrid is kept in the ProductData.GetWholesalePrice(productId). The actual product data is maintained in the ProductData object after being loaded from the xml file.AddProduct(productId). onShapeDoubleClick displays the product detail form. Also. TotalRetailPrice += productData. The master shape has shape data fields defined. Open Visio drawings in the Drawing Control Visio drawings can also be opened in the drawing control. This causes the click event for the menu item onMenuFileSaveClicked to execute. All rights reserved. This is done through the File > Open menu and the onMenuFileOpenClicked event procedure.The onShapeDoubleClick procedure and the onMenuProductInformationClicked procedure each display the Product Detail form. This event procedure calls Utility. Save Visio drawings created by using the Drawing Control After constructing a Visio drawing using the drawing control the user can save the drawing using the File > Save command.Src property to the filename of the Visio drawing. This sets the drawingControl.SaveDrawing to save the Visio drawing. 300 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 300 . Get a reference to the Visio Application object in order to work programmatically with the Visio document. Embed the Visio drawing control in a variety of host applications. State best practices for using the Visio drawing control in Visio solutions. you can integrate your Visio solution code directly into the host container application. 301 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. and Microsoft Internet Explorer. A developer using the control in a custom application (such as a C# application) or Internet Explorer should program against the Visio object model directly in the host application. without separating the Visio logic into a COM add-in. Best Practices Because the Visio drawing control is a programmable component. Lesson Objectives After completing this lesson you will be able to:          Identify the features of the Visio drawing control and example use scenarios. Manage the display of the drawing surface. Microsoft Office documents. or executable. a developer writing a solution for the Visio client application needed to package the solution code in a COM add-in. All rights reserved. Use the properties of the Visio drawing control API. Prior to Visio 2003. Load Visio documents into the drawing control window and save changes.Lesson 2: Creating an application The Office Plan sample provides an example of using the drawing control in a Windows forms application. Deploy the Visio drawing control with your application. out-of-process executable. VSL. Visio solution library (VSL). Calling a Visio COM add-in. Integrate the control with your host application user interface. Microsoft Visual Basic® 6. including Microsoft Windows® Forms. In this lesson we will explore more properties and features of the drawing control.0 forms. VSL. or in a Visual Basic for Applications (VBA) project in a document. Volume 3: Programming with the Visio Object Model 301 . The Visio Drawing Control simplifies solution architecture and the development process by allowing programming of the Visio Application object from the hosting application. or executable from the hosting application unnecessarily complicates the debugging of the Visio integration. it makes more sense to store the information in the shape custom properties. In this case. By taking the time to port your code from your existing solution to your host application. it is recommended that you integrate the Visio drawing control programming directly with the host application. You must port all existing VBA code into a COM add-in. For example. create a COM add-in for your host application instead of for Visio. though. or VSL to the container application. Unlike a Visio client application solution. and used heavily for modifying the appearance and layout of shapes. All rights reserved. executable. While it might be initially easier to simply use an existing COM add-in. you will need a way to notify your COM add-in to respond to a user action in your document. Consider how you want the drawing surface to respond to events fired by the host application. create a Word COM add-in and access the Visio control through the Word add-in.However. include these design considerations in your planning. Porting existing code When you are porting your code from an existing Visio client application solution to the Visio control. you'll simplify deployment of your solution. If your current Visio solution stores extensive data in shapes. Make sure your COM add-in is targeted at the host since an Office host application will not load a Visio COM add-in for the drawing control. or VSL with the host application. Volume 3: Programming with the Visio Object Model 302 . and streamline the development. debugging. Visio can store as much data as you need. or more preferably. if you plan to host your Visio control in a Microsoft Office Word 2003 document. Use the 302 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Port an existing Visio solution COM add-in. and how your host application needs to respond to events in the Visio drawing surface. if you would like to host the Visio control in a Microsoft Office System application other than Visio. your host application. you will have to use a COM add-in. If you must use a COM add-in. executable. the Visio drawing surface can respond to both user events and host application events. Re-evaluate data storage in shapes. You do not need to use a COM add-in unless you are working with the control in another Office container. Think about event integration with the host application. but it often makes more sense to keep Visio as a presentation layer component and use your host application as data storage or access to a data source.      Port VBA code. Use marker events for COM add-ins. consider re-architecting data storage out of Visio shapes and into data structures maintained or accessed by the host application. as long as it makes sense working within the control's SDI architecture. If the data is relatively static. and maintenance process over time. You can keep most of your same algorithms and logic. It also means that the user of an application hosting the control will never see the Visio application's security dialog box warning about macros in the document. which is a separate window in the Visio application. However. the ShapeSheet itself still exists for the Visio shapes and pages in the document loaded in the Visio drawing control. with each instance loading a separate Visio document. The control does not provide access to the Visio ShapeSheet user interface. you can use the Cell object's SRC property to add a double-click action for a Visio shape. so any use of the CALLTHIS function will fail silently. the developer can embed multiple instances of the control in the application. VBA is not included with the Visio drawing control. As a result. Unlike the Visio client application. use mouse events or QUEUEMARKEREVENT as was illustrated in the Office Plan sample program earlier. you will not be able to use the CALLTHIS function. which calls a VBA macro in the document. You can still edit ShapeSheet cells for your Visio document in the control using Visio Automation. Use the Visio ShapeSheet® programmatically. Note: When programming the ShapeSheet for documents loaded in the control. The Visio drawing control does not execute VBA code. documents loaded in the Visio drawing control do not execute any VBA code associated with the document. 303 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. For example. The control's single document interface (SDI) architecture results in the following considerations when designing the Visio drawing control integration with your application:    Use multiple instances of the Visio drawing control to display multiple Visio documents in your application. it's important to understand that the Visio control supports a single document in a single window. If the developer wants to display multiple Visio documents. All rights reserved. The Controls SDI (single document interface) When designing an application that uses the Visio drawing control. Instead. The control's lack of a VBA run-time environment prevents the distribution of legitimate code or malicious macros via documents loaded by the Visio control. the Visio drawing control can only display a single document per instance of the control. Volume 3: Programming with the Visio Object Model 303 .QUEUEMARKER function in the ShapeSheet or a persistent event with the document to queue a marker event to which your COM add-in responds. which can display multiple documents and windows at a time. Do not depend on VBA for programming logic. vdx. application = (Microsoft. Volume 3: Programming with the Visio Object Model 304 . Instead assign a blank drawing to the Src property or SelectAll and delete to clear the contents from the current document.Window. You can do the same thing using the following Visual Basic 6.Interop. .Office. For example. but setting the Src property to an empty string after a document has been loaded does not clear the contents of the current document.Window. You can then use the document's SaveAs method to save any changes. Use the Visio drawing control's Src property to load a document into the control. You can load any Visio file type using the Src property (for example.Interop.Visio. For example. the following C# code shows how to get a reference to the Visio Application object using the drawing control's Window property: using Microsoft.Application Loading a document When the Visio drawing control is loaded.Office. the following C# example shows how to load a Visio drawing: drawingControl.Application application = null.vst. All rights reserved.0 code: Dim vsoApplication As Visio. Note: To load a blank drawing into the drawing control when it initializes for the first time. use either the drawing control's Document or Window property. the drawing control exposes an Src property for loading a document into the control.Interop. or .Getting a reference to the Visio Application Object You can access the Visio object model through the Visio drawing control's API.Application.Src = "C:\\Drawing. . private Microsoft.vsd. 304 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. To get a reference to the Visio Application object. The file can be stored locally or on a remote file server.Application) drawingControl. set the Src property to an empty string. If you want to display an existing Visio document.svg).vsd".Visio.Application Set vsoApplication = DrawingControl.Office. it displays a blank Visio drawing. .Visio. The control loads a copy of the file specified by the Src property. 2. All rights reserved. To persist changes in-stream to a Visio document in the control 1. overwriting any modifications. For example.Documents(1). To persist the changes in the control's document.0 code that saves a Visio 2003 drawing into the Visio 2003 file format: Application. you do not modify the original document loaded by the Src property.Document document = drawingControl. Volume 3: Programming with the Visio Object Model 305 . however. The following C# example shows how you can use the drawing control Document property to call the SaveAs method: Visio. document. call the document's SaveAs method. visSaveAsWS + _ visSaveAsListInMRU) Saving a Visio Document in the Control to Stream Developers may want to persist changes to a drawing in the Visio drawing control without saving the drawing to disk. the changes are lost when the user forwards that Word document in an e-mail message. and therefore cannot be saved using the Save method.vsd").SaveAsEx("C:\Documents and Settings" & _ "\myusername\My Documents\Visio2002 file.Saving a document The Visio control's Src property loads a copy of the file specified in the Src value. you can persist changes in-stream. you must save the Visio document using the SaveAs method.vsd". The file loaded through Src is not opened for read/write operations. launch an invisible instance of Visio and call the SaveAsEx method in your Visio application instance. To save changes to the document loaded in the Visio drawing control. as demonstrated in this Visual Basic 6. To save a drawing loaded in the Visio drawing control to Visio 2002 format. In both cases. Alternatively. Load the original document using the Visio control's Src property.SaveAs("C:\\Drawing. You cannot use the SaveAsEx method to save Visio 2003 documents to Visio 2002 format in the Visio ActiveX control. 305 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. the control loads the file specified by the Src property.Document. After the document loads. set the Src property to an empty string. When another user opens the document. if a user modifies a Visio document in an embedded control in a Word document. The best approach for allowing users to modify shapes on a document is to use a custom UI. rulers. However. showing a portion of the drawing page. Integrating the control with the host container You can modify the appearance of the Visio drawing control in your application. All rights reserved.visScrollBarNeither. the following C# code hides the drawing control's scroll bars: drawingControl. you cannot access the ShapeSheet or windows such as icon editor and master and group editing.ShowScrollBars = (short) Visio. if you want to use Visio menus and toolbars. Because the control only supports a single window. your Visio drawing control application will be event-driven and respond to users clicking buttons or menu items contained in the application. By default. The drawing control exposes a PageSizingBehavior property that determines how the page is displayed within the drawing control window. For example. but the technique seems to work reliably. the control displays the last in-stream image rather than the original document specified by the Src property. Most likely.VisScrollbarStates.When the control is activated in its container document after the first initialization. You can choose how the drawing control surface appears by displaying scroll bars. The page and shape right-click menus are enabled by default. The limited Visio UI for controlling shape behavior reflects the intent of the control to be tightly integrated with the container application. You can choose to resize the page in relation to the drawing control's size. Volume 3: Programming with the Visio Object Model 306 . so that you can respond to a user clicking within the control itself. the drawing control does support menu and toolbar merging with the host application. or provide a view similar to Visio. or by changing the window background color. 306 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. The drawing control also exposes Visio events. Managing the Drawing Surface Display You can modify the appearance of the Visio drawing control's surface through the control's Window property. Note: Persisting changes in-stream is an unsupported feature of the drawing control.Window. all Visio toolbars are turned off and the stencil pane is not displayed. which is how Visio Automation specifies colors. You can also change the color of the window background to suit the color scheme of your application. Shapes remain located relative to the coordinate system of the Visio page.Window. and visScrollBarVert (display vertical scroll bar). the ColorTranslator class is used to convert a . within the drawing control window.VisPageSizingBehaviors. including its shapes.Zoom = 2.NET color type into OLE_COLOR type.Window. By removing parts of the Visio UI. Other possible values for the VisScrollbarStates enumeration include visScrollBarBoth (display both scroll bars). In this example.ToOle(Color.0. the following C# code sets the window background color to solid red: drawingControl.Red). 307 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.ToOle(Color. set the Zoom property through the control's Window property. Volume 3: Programming with the Visio Object Model 307 . the page's shapes are not resized with respect to the page.PageSizingBehavior = Visio. drawingControl. as shown in the following C# example: drawingControl.ShowRulers = 0. When PageSizingBehavior is set to visResizePages. The default setting of this property (visNeverResizePages) provides a view similar to that of Visio where a portion of the page is viewable within the window. To rescale the entire page.Red).BackgroundColorGradient = (uint) ColorTranslator.visResizePages. The following C# code example resizes the page to fit the control: drawingControl.BackgroundColor = (uint) ColorTranslator. visScrollBarHoriz (display horizontal scroll bar). The following C# code hides the rulers: drawingControl.Window. For example. you can make the drawing control look more integrated within your application.This example hides both the horizontal and vertical scroll bars. All rights reserved. Sizing the page to fit within the control hides the page boundaries and is useful in situations where the control is sized to the maximum extent of the drawing surface. Page sizing and zoom Use the Visio drawing control's PageSizingBehavior property to resize the page with respect to the control window.Window. which has its origin in the lower left corner of the page. To take effect. Window management You can "turn off" the Visio Shape Search window in the document's stencil pane using the Visio ItemFromID property.ZoomLock = true.ZoomBehavior = Visio. Each of the other View windows such as Size & Position Window and Shape Data Window are each controlled separately.ItemFromID(Visio. which can be accessed through the drawing control's Window or Document property. Volume 3: Programming with the Visio Object Model 308 . set the ZoomLock property as shown in the following C# example: drawingControl. set the VisZoomBehavior property to the VisZoomVisioExact value.visZoomVisioExact. the control will reset to its default size the next time the Word document is opened. such as: Windows(1).Window. not just discrete settings such as 50% or 100%.VisZoomBehavior.This code magnifies the window's contents by 200%. set the same value to True. By default. set the property's Visible property to false.visWinIDShapeSearch). as shown in the following C# example: drawingControl. All rights reserved. the control uses the current zoom setting for the document. 308 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Window. To prevent the user from changing the zoom setting. the zoom settings must be made after loading the document using the Src property. You can set the extent to which Visio controls the zoom through the VisZoomBehavior property.Visible = False To expose the Shape Search window in the stencil pane. If you want to be able to set the zoom to any level. To make the Shape Search window invisible in the stencil pane. Note: You cannot resize the Visio drawing control in a Word document. If you resize the drawing control and save the changes. without making any adjustments for the appearance. set the drawing control's NegotatiateToolbars and NegotiateMenus properties. If you want to display Visio menus and toolbars in your container application.NegotiateMenus = True. There are known issues with menu merging in Internet Explorer (see the Microsoft Knowledge Base article 193098. All rights reserved.Visible = True Important: Important: Do not attempt menu and toolbar merging with multiple active instances of the ActiveX control.Integrating menus and toolbars The best practice when building an application using the Visio drawing control is to implement a custom UI. Volume 3: Programming with the Visio Object Model 309 . 309 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.NegotiateToolbars = True. You may get unexpected results when trying to do menu merging with a single Application object and multiple active instances of the control.CommandBars("Layout & Routing"). Multiple instances of the control share a single underlying Visio Application object. For example. The following C# code enables both menu and toolbar merging: drawingControl. Within the Visual Basic project of the Word document you can programmatically display Visio toolbars. The container application must support OLE menu merging in order to display Visio menus or toolbars. The best practice is to set both of these properties to the same value. vsoApplication. PRB: Unexpected Menu Merging Behavior in Internet Explorer). drawingControl. you can enable toolbar merging in a Word document. The following example displays the Layout & Routing toolbar. Do not merge menus and toolbars with the Internet Explorer user interface. The control will not support independent negotiation of toolbars and menus. Handling events For easier use of Visio events. the Visio drawing control object exposes all Visio Window and Document events. This allows developers to access the events directly from the control rather that going through the Visio Document object. _ ByVal nEventSeqNum As Long. " _ & pSubjectObj. The following code sample demonstrates how to capture a mouse event using an event sink in Visual Basic 6. _ ByVal vMoreInfo As Variant) As Variant Dim strMessage As String ' Determine if mouse up event fired. You can use mouse events on the Visio drawing control to display custom Windows Forms and update data in your host applications. Volume 3: Programming with the Visio Object Model 310 . You can use the Visio mouse and keyboard events like any other Visio event with AddAdvise.0: Implements Visio. Mouse and Keyboard Event Objects Event objects created by the Visio AddAdvise method offer the best performance." If the hosting application "swallows" the mouse and keyboard events. _ ByVal pSubjectObj As Object.X & ". _ ByVal nEventID As Long. you can listen for all keyboard and mouse events and "throw them away. If you would like to "lock down" the Visio control's drawing surface and prevent end users from modifying any content directly in the drawing. the Visio drawing surface won't respond to the user's typing and mouse-click actions.IVisEventProc Private Function IVisEventProc_VisEventProc( _ ByVal nEventCode As Integer. Mouse and keyboard events are commonly used with Visio control programming. All rights reserved.Y & ")") End If 310 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. If nEventCode = visEvtCodeMouseUp Then MsgBox ("MouseUp coordinates (" & pSubjectObj. _ ByVal pSourceObj As Object. VisOcx.Interop. you can also define a C# delegate in a Windows Form to handle mouse-click events within the drawing control window.coordinates for the click event on the window. AxVisOcx. sets Visio constants that 311 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. "".EventList Set vsoMouseUpEvent = vsoWindowEvents. The event handler would then have the following signature: private void drawingControl_MouseUpEvent( object sender.") Delegates for Mouse-Click Events Although using event objects created with AddAdvise provides the best performance. Private mEventSink As clsEventSink Dim vsoMouseUpEvent As Visio.MouseUpEvent += new AxMicrosoft. "Mouse up.drawingControl.Window.EventList Set mEventSink = New clsEventSink Set vsoWindowEvents = DrawingControl1.EVisOcx_MouseUpEventHandler( this.and y..AddAdvise( _ visEvtCodeMouseUp. To locate a particular shape in a page or window on which a user clicks. as shown here: this. Mouse Events for Shapes Visio mouse events are exposed on Page and Window objects. All rights reserved. The following C# code passes in the x.End Function The following code sample demonstrates how to create an event object for the mouse event using the AddAdvise method. mEventSink..Event Dim vsoWindowEvents As Visio.EVisOcx_MouseUpEvent eventData) Note: Examples of using delegates is illustrated in the Office Plan sample from the Visio 2010 SDK.Office.drawingControl_MouseUpEvent). Volume 3: Programming with the Visio Object Model 311 . developers must use the Visio SpatialSearch method. Internet Explorer 5. allowing developers to write script against the Visio object model in Microsoft Visual Basic Scripting Edition (VBScript) or ECMAScript as defined by the specification of the European Computer Manufacturers Association. y. 0. visSpatialFrontToBack) If the tolerance is set to a very small unit relative to the size of the shape. Volume 3: Programming with the Visio Object Model 312 . MySelection = Window. To integrate the Visio drawing control with an Internet Explorer browser control-based application. Add a link in your Internet Explorer browser control that launches a new Internet Explorer process with its own window. Program against the Visio drawing control using your preferred scripting language. the one that the end user clicked on in the window.SpatialSearch(x.001. 3. visSpatialContainedIn. Embed the Visio drawing control in the new Internet Explorer window for the new Internet Explorer process. you can still use the Visio drawing control with applications that depend on the Internet Explorer browser control.dictate how to set up the selection object. such as JScript or JavaScript. Using the Visio Control with the Internet Explorer Browser Control Even though you cannot embed the Visio drawing control directly into another ActiveX control. do the following: 1.coordinates. All rights reserved. and defines a small tolerance in which to search around the xand y. the selection object returned by the SpatialSearch method will only contain one shape. 312 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. 2.0 or later provides an excellent host container for the Visio drawing control. 8: Using the Visio Drawing Control The ScheduleBuilder solution from the previous labs has been ported to a Visual Studio 2005 application that uses the Visio 2010 Drawing Control. All rights reserved. you will be able to:  Set the document Src property  Control windows in the Visio environment using the drawing control  Add menus and call procedures in the container application  Save the document to a Visio file 313 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Lab 3. you will need:  Participants should have completed the lessons within this module before completing this lab. you will make modifications to the application to enrich the functionality presented.  All files from folder Labs\Vol3\Schedule Builder Start o  These files present the starting point for the lab All files from folder Labs\Vol3\Schedule Builder Finished o These files present a completed solution for the lab What You Will Learn After completing this lab. Volume 3: Programming with the Visio Object Model 313 . Estimated time to complete this lab: 60 minutes Before You Begin To complete this lab.  Visual Studio 2005 installed and configured. During this lab.  Visio 2010 installed and configured. Drop Section Shapes. You will fix that in this step. 3. Display Form1.vb (code view) Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. 4. The External Data window is turned off. Display Form1. The program will stop with an error when trying to set the Src property of the document. Exercise 2: Add menus to place and delete Sections Scenario Add menus to access functions to Delete Selection Shapes. Correct the path and continue.vb in design mode. All rights reserved. Tasks 1. you will likely get an error when you first start the application because the path to the Visio drawing being loaded is incorrect.sln 2. Tasks 1. Add 3 menu items under ScheduleBuilder a.Exercise 4: Set the Src property of the document and display the External Data window Scenario Depending on where you placed the Lab files on your machine. Find the code that keeps the window off and make it visible. Add a second top level menu item call ScheduleBuilder 3. Delete Section Shapes b. These were all macros in the VBA version of this solution and have been ported to the Windows Form application containing the drawing control. Drop Section Shapes c. Place Selected Shapes 314 4. 2. Volume 3: Programming with the Visio Object Model 314 . and Place Selected Shapes. Choose Debug > Start Debugging. Open the Visual Studio 2005 project Labs\Schedule Builder Start\ScheduleBuilder. vb 5.a. In the objects drop down list at the top of the form choose DropSectionShapesToolStripMenuItem b. Add the code Document. The procedures to call are in ScheduleDocument. Tasks 1.vb in design mode. 2. Volume 3: Programming with the Visio Object Model 315 . Try out the code. You will find that the Delete Section Shapes does not delete the shapes properly. 315 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Under the File menu insert a new menu before Exit and name it SaveAs 3. Add the Click event procedures for the other two menus. In the events drop down choose the Click event. In the code view of the form add the Click event for this menu 4. This will stub in the event procedure for this menu c. All rights reserved. Exercise 3: Add SaveAs menu Scenario To save the drawing you will need to add a SaveAs menu. Fix this error. Add the code for the SaveAs.vb 6. Display Form1. Look back at the sample code in this module for an example.DropSectionShapes() This calls the DropSectionShapes procedure in the module ScheduleDocument. microsoft.com/en-us/library/aa173510(office.11). Review best practices and how to use the Visio drawing control programmatically. All rights reserved. you can embed the full functionality of the Visio drawing surface into your applications.aspx Drawing Visio Shapes in the Visio ActiveX Control using C# and .com/mailant/archive/2004/09/24/233928. http://www. into applications.msdn.microsoft. also referred to as the Visio drawing control.com/UploadFile/mgold/VisioInDotNet12032006222024PM/VisioInDotNet. (24 printed pages) http://msdn2.com/en-us/library/aa168480(office.aspx About Using the Visio Drawing Control in Your Application [Visio 2003 SDK Documentation] Using this control. http://msdn2.Additional Resources – Drawing Control Programming with the Microsoft Office Visio 2003 ActiveX Control Learn to integrate the Microsoft® Office Visio® 2003 ActiveX® Control.csharpcorner. You can take advantage of the full Visio object model (API) and you can pick the aspects of the Visio user interface you want to expose to better integrate Visio seamlessly into the user interface of your application.11).NET A sample program from Mike Gold to help you get started using the ActiveX Drawing Control.aspx 316 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. http://blogs.aspx Dev Luv: Top Ten Things to Know When Using the Visio 2003 ActiveX Control Mai-lan's Visio Blog This is a good summary blog on common things that can trip you up when using the drawing control. Volume 3: Programming with the Visio Object Model 316 . microsoft. Volume 3: Programming with the Visio Object Model 317 . All rights reserved.NET Custom Clients Microsoft Office Visio 2003 introduces a new drawing component that allows you to embed an interactive drawing surface into your application's user interface.0 Web Service.Integrating Menus and Toolbars in Visio 2003 Drawing Control Applications You can choose from several approaches when integrating Visio menus and toolbars in your applications that host the Visio drawing control.com/en-us/library/aa192480(office.11). http://msdn. http://blogs. This article explains how to embed the Visio drawing component into a C#-based Windows Forms client app that retrieves data from the Fabrikam 2.com/msdnmag/issues/03/12/Visio2003/ 317 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. (13 printed pages) http://msdn2.NET data adapter. The Visio drawing component supports the rich Visio application programming model. including the use of the IOleCommandTarget interface.msdn.com/wmorein/archive/2007/01/26/visio-2007-bug-in-drawing-control.microsoft. You can drive the Visio drawing component from events in your host application or with data from a Web Service and an ADO.aspx Host an Interactive Visio Drawing Surface in . giving you control over how graphics are used and displayed on the drawing surface. Visio crashes.aspx Visio 2007: Bug in Drawing Control Bill Morein's Weblog There is a bug in the Visio 2007 Drawing Control such that if you have the SRC property set and add a new page (either through the UI or through code). This article walks you through a sample application demonstrating these approaches. What property of the drawing control must be set in order to display an existing Visio drawing in the drawing control? 12. What happens to any VBA code that is a part of that document. 8. 9. You can embed the Visio drawing control into an Excel VBA form. The Visio control is installed with the Visio application setup program and requires the Visio client application to initialize. When editing a drawing in an application using the drawing control you are working directly on that document and can update the document with the Save method. Volume 3: Programming with the Visio Object Model 318 . True or False. The Shape Data window cannot be displayed in an application hosting the Visio drawing control. 2. you cannot program against the ShapeSheet in application that use the drawing control. There can only be a single document displayed in an application using the drawing control. 318 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. 13. True or False. A Visio drawing can be displayed in the drawing control by assigning the Src property of the control. 4. What two properties of the drawing control can be used to get a reference to the Visio Application object? 11. True or False. When using a Visio 2010 Drawing Control in a Windows Forms application the developer should: a.Review – Visio Drawing Control Questions 1. Program directly against the Visio object model b. Since the drawing control cannot display the ShapeSheet window. True or False. True or False. What is the key difference in working with Visio embedded as an OLE object versus with the Visio drawing control embedded in a Windows form. Create a COM add-in for the host application and have the COM add-in listen for Visio events and then react to these events c. What are the steps required to upgrade an application currently using the Visio 2003 Drawing Control to use the Visio 2007 Drawing Control? 5. Any of these methods will work 6. how can the Windows application be made to listen to events triggered in Visio? 7. All rights reserved. 3. 10. Host the drawing control in Visio and use VBA to create any necessary forms so that you have access to the Visio user interface d. When using a Visio 2010 Drawing Control in a Windows Forms application. True or False. False. True. As an embedded OLE object you are working with Visio’s own user interface. 9. All rights reserved. False. In working with the drawing control on a form there is no Visio UI. The host application must also support OLE menu merging. 7. but you can embed into VBA forms of other applications. you still have access to the Visio object model and therefore can get and set cells in the ShapeSheet. The interfaces are the same so just rebuild the application. True. 13. Document and Window properties.14. 12. True 4. SpatialSearch. The developer must build the interface that is presented to the user. True or False. 5. The Src property. Answers 1. You cannot embed the drawing control into a Visio VBA form. False. 11. You are always working on a copy of the document when using the drawing control and must use the SaveAs method to save changes to the drawing. 2. False. 14. but the viewing windows can be controlled by the host application. Even though the ShapeSheet window cannot be displayed. The drawing control does not support VBA. 8. Volume 3: Programming with the Visio Object Model 319 . a. 6. 15. The ShapeSheet an icon editing windows cannot be displayed. 15. 3. 319 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Any host application can display Visio menus and toolbars if the NegotiateMenus and NegotiateToolbars properties of the drawing control are set to True. Only a single document can be displayed because of the drawing control’s single document interface. 10. Any VBA code that is in the document cannot execute. What Visio method can be combined with mouse events by the host application to locate a shape on the drawing surface. In the host application create an event sink and define the Visio events that are to be listened for. Now with the release of Microsoft Visio 2010. Visio 2007 and other Office 2007 applications continued to use the older CommandBars interface. migrate their solution to target Visio 2010 and create their UI using the Ribbons or upgrade their solution to target both Visio 2007 and Visio 2010 and manage both a CommandBars based UI and a new Ribbon based UI. This is also the case for CommandBars as future development investments will now be focused on the Ribbon interface. Visio solution developers that are creating new solutions specifically targeted for Visio 2010 should create their UI using the new Ribbon UI. 1) UIObject 2) CommandBars 3) Ribbon. The UIObject is still available however it is recommened that solution developer not use this API as it could be deprecated in future releases. Visio solution developers that currently maintain Visio 2003/2007 based solutions have a choice to make. This adoption does pose some issues for the Visio solution developer as this is yet another user interface technology that is available via the Visio API. the Ribbon interface has been adopted allowing Visio solution developers to build rich Ribbon based interfaces for their Visio based solutions. however this new interface was not adopted in all of the Office 2007 applications. 320 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 320 . giving the Visio solution developer three choices. providing best practices for Ribbon item state management as well as best practices for supporting both CommandBar and Ribbon based UIs in one add-in. Figure 1 – the Add-Ins tab is a catch all for UIObject and CommandBar based UIs This article will walk you thru the process of creating a Ribbon based interface for an existing Visio 2007 add-in.Adding the Office Fluent UI to an existing Addin Microsoft Office 2007 introduced a new user interface called the Fluent UI or Ribbon interface. All rights reserved. Preparing the add-in for Ribbon support In order for your add-in to support the new Ribbon interface when loaded by Visio 2010. Volume 3: Programming with the Visio Object Model 321 .0 from the . Add this reference to your project if it does not already exist.NET tab.0 framework and runtime. From the Add Reference menu select Office. commonly referred to as Shared Add-ins from the managed code world.0. The sample projects for this section are written in C# (Visual Studio 2008) for Visio 2007 using the Visual Studio Tools for Office (VSTO) 3. one for each menu and toolbar created thru these legacy APIs.0 (installed with Visual Studio 2008) Visio 2007 with . Either framework supports Ribbon extensibility by simply implementing the IRibbonExtensibility interface. This interface is defined in the Office PIA. It is up to the host application to call the implemented interface in order to retrieve Ribbon customizations. Updating References For the purpose of this article it is not necessary to reference the Visio 2010 type library. This is the Primary Interop Assembly for Office Core which provides the interfaces for IRibbonExtensibility as well as the APIs and 321 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. All rights reserved. This is good news for both users and solution developers as existing add-ins are still compatible and accessible with the new Ribbon interface. Because both the UIObject and the CommandBars support the idea of Menus and Toolbars you see separate ribbon groups. 12.0. Office add-ins were developed as COM components implementing the IDExtensibility2 interface. any UI modifications made using the UIObject APIs or the CommandBar APIs are aggregated within a new tab on the Visio 2010 ribbon named “Add-Ins”.NET Programmability Support installed (PIA) VSTO is the preferred and supported framework for building add-ins for all Office applications. your add-in must be updated to support the IRibbonExtensibility interface. The following software is required for this scenario:    Visual Studio 2008 VSTO 3.Getting started As shown in Figure 1. Prior to the release of VSTO. Existing Visio 2007 add-ins can continue to reference the Visio 2007 type library in order to support both Visio 2007 and Visio 2010 as well as provide a rich Ribbon based interface when running in Visio 2010. interfaces for CommandBars.Office.Ribbon. Here is a sample definition of this class: using Office = Microsoft. We will generate the XML for the ribbon later in this article. } #endregion The GetCustomUI method is used to return the XML that defines your Ribbon to the host application.dll After adding the reference you will need to implement the IRibbonExtensibility interface in order to provide the host application with an instance of an object that provides your ribbon implementation. This method is called by the VSTO runtime to retrieve an instance of your class that implements 322 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.IRibbonExtensibility {…} A single method needs to be implemented from the IRibbonExtensibility interface: #region IRibbonExtensibility Members public string GetCustomUI(string RibbonID) { return GetResourceText("DataLinkedOrgChart. All rights reserved. This xml is compiled into the add-in as a resource which is retrieved by the GetResourceText method.xml"). For a VSTO based add-in start by creating a separate class that will implement the IRibbonExtensibility interface. [ComVisible(true)] public class Ribbon : Office. I prefer to name this class Ribbon (in a separate file. Volume 3: Programming with the Visio Object Model 322 .Adding a reference to Office. Using this XML the host application generates the Ribbon and displays it to the user.cs). Ribbon. Figure 2 . so if you are using CommandBars you probably already have this reference in your project.Core. Application level Ribbon In order to create a single Application-Level Ribbon you need to override the CreateRibbonExtensibility method. the IRibbonExtensibility interface. To create a Ribbon for a specific document you would create a new instance of the Ribbon class and pass that along with the Visio.Application class that allow you to attach and detach a Ribbon to a specific open document.visRXModeDrawing. Volume 3: Programming with the Visio Object Model 323 . RegisterRibbonX and UnRegisterRibbonX are two new methods on the Visio.VisRibbonXModes. It is important to perform cleanup operations as documents close so you should manage each instance of the Ribbon class that you create and as documents are closed you should call the UnRegisterRibbonX method.ThisAddIn.RegisterRibbonX( ribbon. 323 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.ribbon = new Ribbon(). visioDocument. "My Ribbon"). Visio. passing it to the host application which will then make the call to the GetRibbonUI method. // add our UI for this document Globals.IRibbonExtensibility CreateRibbonExtensibilityObject() { // create a new instance of our Ribbon this.ribbon. Document level Ribbon To implement a Document-Level Ribbon you do not override the CreateRibbonExtensibility method as described above as you will need to create an instance of your Ribbon for each document on an as needed basis. // return the ribbon to the VSTO runtime caller return this.Application. } As you can see this method simply creates a new instance of your Ribbon class and returns it to the caller.Office.Documentinstance that you want to attach it to as parameters to the RegisterRibbonXmethod. protected override Microsoft.Core. All rights reserved. All rights reserved.Globals.Office. Extensibility.ThisAddIn. this. Microsoft.Core.UnregisterRibbonX( this. From the Add New Item dialog select the Ribbon Designer Figure 3 .Adding the Ribbon (Visual Designer) to your project And you will be able to visual design the layout of your ribbon using ribbon controls just as you would with a WinForm. public class Connect : Object.Application.ribbon.IRibbonExtensibility Creating the Ribbon If you have created add-ins for Word or Excel you know that the add-in project template in Visual studio provides a very easy mechanism for creating a Ribbon using the Ribbon Designer. Volume 3: Programming with the Visio Object Model 324 .IDTExtensibility2.visioDocument). 324 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Note for Shared add-ins If you are using the Shared add-in framework you simply implement the IRibbonExtensibility interface directly on the Connect class and provide the implementation for the GetCustomUI method as described above. This is the XML that is passed to the host application from the GetCustomUI method described above. 1. create a new add-in project for Word 2007. To generate the XML from the Visual Designer: 2. choose the Add Existing Items menu and navigate to the temporary Word add-in project folder. Once these files are added to your Visio add-in project you can continue to the next step which would be to actually design the ribbon. Once the new Ribbon Designer is added to this temporary project you can copy the necessary files to your Visio add-in project and discard this temporary Word add-in project. Volume 3: Programming with the Visio Object Model 325 . selecting the following files: a. To copy the ribbon designer files to your Visio add-in project: 1. 3. Right-click on the ribbon and from the context menu choose „Export Ribbon to XML‟ 325 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. RibbonDesign. RibbonDesign. RibbonDesign. Double-click the RibbonDesigner. You can skip the designer and just write the XML from scratch but it is much easier to work with the designer and then have the designer generate the XML when you have your ribbon laid out.Using the Visual Designer for the Ribbon The problem is that the project template that is used to create add-ins for Visio 2007 knows that Visio does not support the Ribbon interface so this option is not available to you. This will open the Visual Designer for the ribbon as shown in Figure 4 Once you are happy with the design and layout of your ribbon it is time to generate the XML that will be embedded as a resource in your project.cs b. Then from the Add New Item dialog choose the Ribbon Designer.cs c.Figure 4 . All rights reserved.designer.cs item in the Project Explorer window. From your Visio add-in project.resx This will copy the ribbon designer files to your Visio add-in project. Open the Visual Designer as shown in Figure 4 above. 2. Close and save changes to the temporary Word add-in project/solution. To do this. 326 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. If you open this XML file in the editor you will see that it is a very simple schema.Figure 5 .xml‟. All rights reserved. Volume 3: Programming with the Visio Object Model 326 .Export Ribbon to XML This will add a new file to your Visio add-in project named „Ribbon. <button idMso="DataRefreshAllDialog" /> 327 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Volume 3: Programming with the Visio Object Model 327 . verify that the Build Action for this file is set to Embedded Resource or the call to GetCustomUI will fail to return the XML.Build Action set to Embedded Resource Tip: If you want to duplicate built in buttons on your Ribbon.Figure 6 View of XML generated by the Visual Designer After the Ribbon. All rights reserved. such as the Refresh All button. you can use the idMso attribute in your XML.xml file is generated and added to the project. Figure 7 . Sample XML showing callback attributes The onAction callback should be defined as follows: public void OnAction( Office. Make sure to set it for all three designer files: Tip: These files can be removed from your project once you are finished with the design of your Ribbon or they can be left for future design changes. Volume 3: Programming with the Visio Object Model 328 . These callbacks are assigned to ribbon controls using attributes in the ribbon xml.IRibbonControl control) { switch (control. All rights reserved. It you compile these files into your project they could conflict with the Ribbon class.Make sure to set the Build Actions for the Ribbon Designer files to None. Callbacks At this point you could actually compile and run your add-in and you should see your ribbon however the ribbon controls will not do anything (unless linked to build in commands). } // define a case for each button that needs a handler 328 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation.Id) { case "buttonCreate": { // do any work necessary for the selected control break. In order for the ribbon controls to perform custom actions you need to implement callback methods on the Ribbon class that can be called by the host application or the ribbon controls. Figure 8 . } } Manage Ribbon control state In addition to creating a Ribbon with controls that perform actions within your add-in. 329 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. if (Globals. } } Not only do we get the instance of the Ribbon that was created by the host application but in this callback we will connect to a few Visio events so that we can determine when Ribbon control states need to be updated. We can get a handle to this Ribbon when the host application creates it if we provide a callback to the onLoad attribute of the Ribbon XML.Sample XML showing definition for onLoad callback Callback defined in the Ribbon class public void Ribbon_Load(Office. All rights reserved. Callback defined in XML Figure 9 . Volume 3: Programming with the Visio Object Model 329 . you will also want to manage the state of the controls on your Ribbon so that users have access to each control when appropriate.ribbon = ribbonUI.ThisAddIn. When the host application receives the XML from the GetCustomUI method it generates a new Ribbon tab.IRibbonUI ribbonUI) { // hold on to the instance of our ribbon this.Application != null) { VisioEvents_Connect(). Visio. Globals.Visio. } } Within each Visio event handler we can call the Invalidate method on our Ribbon to notify the Ribbon that it needs to get the state for each control.Office.Interop.WindowActivated += new Microsoft.Office.Visio.Application.ribbon.AppObjActivated += new Microsoft. 330 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Globals.ThisAddIn.Office.Visio.Application. Globals.ThisAddIn. Globals.Window Window) { this.Interop.Application.Interop.EApplication_BeforeWindowClosedEventHandler(Applicatio n_BeforeWindowClosed).Office.EApplication_AfterModalEventHandler(Application_AfterM odal).ThisAddIn. All rights reserved.ThisAddIn.AfterModal += new Microsoft.WindowChanged += new Microsoft.Interop.BeforeWindowClosed += new Microsoft.Visio.Visio.Interop.Interop.ThisAddIn.Application. for each control to update its new state each control must have a callback defined that returns true for Enabled or false for Disabled.Visio. Globals.private void VisioEvents_Connect() { if (Globals.EApplication_WindowActivatedEventHandler(Application_W indowActivated).Invalidate().ThisAddIn.Application.ThisAddIn.Office.Application != null) { Globals.Office. Volume 3: Programming with the Visio Object Model 330 .EApplication_WindowOpenedEventHandler(Application_Wind owOpened).WindowOpened += new Microsoft.Interop.Application.EApplication_AppObjActivatedEventHandler(Application_A ppObjActivated). } However.EApplication_WindowChangedEventHandler(Application_Win dowChanged). void Application_WindowChanged(Microsoft.Office. } After Invalidate is called.Callback defined in XML Figure 10 . 331 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. break.IRibbonControl control) { bool retVal = false. Volume 3: Programming with the Visio Object Model 331 .Sample XML showing getEnabled callback getEnabled defined in Ribbon class public bool GetEnabled( Microsoft.Office.ThisAddIn.Id) { case "buttonCreate": { // create is always available retVal = true. each Ribbon control that has its getEnabled attribute set will execute its callback and set its state based on the return value of the callback. break. At this point you can test the ActiveDocument or the Selection to see if the control should be enabled or disabled.Core. } // additional cases for all controls that have state } return retVal.Application.IsOurDocument(Globals. // default to false until we prove this enabled switch (control. All rights reserved.ActiveDocument). } case "buttonGenerate": { // only enabled if the active document is our document retVal = this. Id) { case "buttonApplyDataGraphics": { return Properties. Volume 3: Programming with the Visio Object Model 332 .OperationsManagerProductIcon_32.TypelibMinorVersion <= 12) { // code to provide CommandBars } else { // do nothing. As you can see in the sample below you can easily add your image to your add-in project as a resource and then return it to the caller based on the control. To do this add this simple check when initializing your add-in: if (this. } CommandBars and Ribbon After implementing the Ribbon as described above there is only one more step you should take.Additional callbacks getImage If you do not find an image from Office (ex. VSTO will call into the defined 332 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. public System. imageMso="Refresh") to use on your control you can provide your own.Application.Resources.Bitmap GetImage( Microsoft. } } // we should not get here for these buttons return null.Core. The getImage attribute can be set on each control so that it will retrieve its own image from the specified callback in your add-in. All rights reserved.Office. add a conditional statement around your existing UI code so that you do not build your legacy UI using CommandBars if the user is running Visio 2010.Id property.IRibbonControl control) { switch (control.Drawing. Volume 3: Programming with the Visio Object Model 333 . Using Visual Studio 2008 open the project in <install>\Samples\Office Fluent UI\ Enhanced Ribbon a. Review the example 4. Review the example 2.// IRibbonExtensibility interface } With this check in place your add-in will now run in both Visio 2007 and Visio 2010. providing the user with the best UI experience available to each. Using Visual Studio 2008 open the project in <install>\Samples\Office Fluent UI\ Doc Level Ribbon a. Review the example 3. Review the example 333 Microsoft Visio 2010 Developer Training © 2010 Microsoft Corporation. Using Visual Studio 2008 open the project in <install>\Samples\Office Fluent UI\ Command Bars Only a. Sample Code There are four Visual Studio projects included with this training which demonstrate the above concepts. Try it! Creating Office Fluent UI for Visio Addins 1. Using Visual Studio 2008 open the project in <install>\Samples\Office Fluent UI\ Basic Ribbon a. All rights reserved.
Copyright © 2024 DOKUMEN.SITE Inc.