Creating Visio 2007 Add-Ins by Using Visual Studio 2005 Tools for Office

Summary:   Learn how to use the Microsoft Office Visio 2007 object model to work with shapes and data. In this article, you create a toolbar button to call the functionality of a Visio add-in and link data to shapes in a diagram. (16 printed pages)

Robert Green, MCW Technologies, LLC

January 2008

Applies to:   Microsoft Visual Studio 2005 Tools for the Microsoft Office System, Microsoft Office Visio 2007

Contents

  • Overview of Visio 2007 Add-Ins

  • The Visio 2007 Object Model

  • Creating a Visio Add-In

  • Linking External Data to Shapes

  • Customizing the Appearance of the Page and Data Graphics

  • Saving the Diagram as a Web Page

  • Conclusion

  • Additional Resources

  • About the Author

Overview of Visio 2007 Add-Ins

Microsoft Office Visio 2007 enables you to display complex information by creating diagrams. A diagram is a collection of shapes, with each shape representing an entity. An entity can be as simple as a product or person or as complex as a calendar. Visio 2007 includes a large number of diagram templates, such as basic diagrams, flowcharts, maps, and organization charts. Each diagram template includes related shapes that you can add to your diagram.

In Visio 2007, it is easier to integrate external data into your diagrams. You can connect a diagram to data contained in a Microsoft Office Excel 2007 workbook, a Microsoft Office Access 2007 database, a Windows SharePoint Services list, a Microsoft SQL Server database, and any data source that is accessible via OLEDB or ODBC. You can create many types of reports, both visually and programmatically.

In this article, you learn how to create a Visio 2007 add-in by using Microsoft Visual Studio 2005 Tools for the Microsoft Office system. This add-in creates a sales report from data stored in a Microsoft SQL Server database.

The Visio 2007 Object Model

The top level object in the Visio 2007 object model is the Application object. This represents a running instance of Visio. The Application object contains a collection of Document objects. A Document object represents a drawing, and is associated with an open file, such as Drawing1.vsd. Drawings can have multiple pages, represented by the Page object. Each page contains shapes, represented by the Shape object.

To visually create a diagram, you drag shapes from the Stencil onto the drawing. The Stencil serves the same purpose as the Toolbox in Visual Studio 2005. The Basic Shapes Stencil is shown in Figure 1.

Figure 1. The Basic Shapes Stencil

The Basic Shapes Stencil

To programmatically add a shape to a diagram, use the Drop method of the Page object. You pass a Master object to the Drop method. The Master object represents a shape in the Stencil. The following code adds a triangle shape to a diagram.

Dim vsoShape as Visio.Shape
vsoShape = currentPage.Drop(Application.Documents.Item( _
    "BASIC_U.VSS").Masters.ItemU("Triangle"), 2, 5)

The Drop method of the Page object creates a shape. This method takes three arguments. The first argument is the shape to create. The second and third arguments represent the x and y coordinates on the page.

The ItemU property of the Master object returns an object from a collection. The code above instructs Visio to retrieve a Triangle object from the Basic Shapes Stencil, which is contained in the BASIC_U.VSS file.

In the rest of this article, you learn how to build a Visio Add-in.

Creating a Visio Add-In

In the following procedures, you create an add-in for Visio 2007 in Visual Basic.Net. This add-in retrieves sales information from a Microsoft SQL Server database, and then adds shapes to a diagram. Each shape represents a sales category. Based on the volume of sales, each shape appears differently.

To create the Visio add-in

  1. Start Microsoft Visual Studio 2005

  2. On the File menu, click New Project.

  3. In the New Project dialog box, expand the Visual Basic node, expand the Office node, and then click 2007 Add-ins.

  4. In the Templates pane, select Visio Add-in. Type VSTOVisioAddIn in the Name box, and then click OK.

  5. On the Project menu, click Show All Files.

  6. In Solution Explorer, expand the References node.

    NoteNote

    Visual Studio adds several Office-related references to the project, including Microsoft.Office.Core, a reference to the Microsoft Office 12.0 Object Library, and Visio, a reference to theMicrosoft Visio 12.0 Type Library.

You are creating an application-level add-in that is available whenever you have Visio 2007 open, regardless of the diagram you are working with. This add-in performs a specific task: generating a sales report. You probably do not want to generate a sales report every time you start Visio 2007. Instead, you want the user to select a menu item or click a toolbar button to create the report. In the following procedures you create a toolbar button.

NoteNote

Visio 2007 does not include the Office Fluent Ribbon, so to expose the functionality of your add-in, you must add a menu item or a toolbar button.

To create a toolbar button in Visio

  1. In Solution Explorer, right-click the ThisAddIn.vb node, and then click View Code to open the code window.

  2. Add the following declarations to the code just after the statement Public Class ThisAddIn.

    Private commandBars As Office.CommandBars
    Private commandBar As Office.CommandBar
    Private salesReportButton As Office.CommandBarButton
    
  3. Add the following method to create the toolbar.

    Private Sub AddCommandBar()
        commandBars = CType(Application.CommandBars, _
            Microsoft.Office.Core.CommandBars)
        commandBar = commandBars.Add("VSTOAddinToolbar", _
            Office.MsoBarPosition.msoBarTop, , True)
       ' Set the context when the toolbar is visible.
        commandBar.Context = Visio.VisUIObjSets.visUIObjSetDrawing & "*"
    
        ' Add a button with an icon that looks like a report.
        salesReportButton = CType(commandBar.Controls.Add( _
            Office.MsoControlType.msoControlButton), _
            Microsoft.Office.Core.CommandBarButton)
        salesReportButton.Tag = "Sales by category"
        salesReportButton.FaceId = 2522 
        salesReportButton.TooltipText = "Sales by category"
    
        AddHandler salesReportButton.Click, AddressOf _
            SalesReportButton_Click
    End Sub
    
  4. Add the following method to create the sales report when the user clicks the toolbar button.

    Private Sub SalesReportButton_Click( _
        ByVal ctrl As Office.CommandBarButton, _
        ByRef CancelDefault As Boolean)
    
    End Sub
    
  5. Add the following code to the Startup method. This code adds the toolbar to Visio when the add-in loads.

    AddCommandBar()
    
  6. Press F5 to run the application.

    You see a toolbar with one button below the other toolbars. Move the pointer over the button, and the tooltip displays Sales report, as shown in Figure 2.

    Figure 2. The toolbar and Sales report button

    The toolbar and Sales report button

Linking External Data to Shapes

In the following procedures, you write the code to programmatically link external data to shapes in a diagram. However, first you manually link external data to shapes in a diagram in Visio 2007.

NoteNote

These procedures use Microsoft SQL Server 2005 Express Edition and the Northwind sample database. You can also use Microsoft SQL Server 2005. You can download this sample database from the Northwind and pubs Sample Databases for SQL Server 2000. See also Downloading Northwind and pubs Sample Databases.

  1. In Visio 2007, on the File menu, point to New, point to General, and then click Basic Diagram.

  2. On the Data menu, click Link Data to Shapes to display the Data Selector dialog box.

  3. Select Microsoft SQL Server database and click Next to display the Data Connection Wizard dialog box.

  4. On the Connect to Database Server page, type the name of your SQL Server Express instance. This typically is the name of your computer followed by \SQLEXPRESS. You can logon using Microsoft Windows authentication or a user id and password. Click Next.

  5. On the Select Database and Table page shown in Figure 3, select Northwind from the drop-down list. Select the view Category Sales for 1997, and then click Next.

    Figure 3. Selecting a database and a table

    Selecting a database and a table

  6. On the Save Data Connection File and Finish page, change the friendly name to Northwind Category Sales for 1997.

    You can also supply a description. The data connection is saved in a file with an .odc extension.

  7. Click Finish to return to the Data Selector dialog box. Accept the remaining defaults and click Finish.

    The category sales data is displayed in the Visio External Data window, as shown in Figure 4.

    Figure 4. Category Sales data in the External Data window

    Category Sales data in the External Data window

  8. Drag a Square from the Basic Shapes stencil to the diagram. Select a row of sales data, and then drag it onto the square. The shape is now linked to that row of data.

    Figure 5. Linking the square shape to external sales data

    Linking the square shape to external sales data

Next, add code to the add-in to automate this process.

  1. Add the following declarations to the ThisAddIn class.

    Private currentPage As Visio.Page
    Private salesReportDoc As Visio.Document
    Private salesDataRecordset As Visio.DataRecordset
    Private salesRowIds() As Integer
    Private salesData() As Object
    Private xPos As Double
    Private yPos As Double
    Private shapeType As String
    Private shapeFillColor As String
    Private vsoShape As Visio.Shape
    
  2. Add the following code to the SalesReportButton_Click method to retrieve sales data from the database. Make sure to replace VSTO with the name of your server.

    ' Store the current active page. 
    currentPage = Me.Application.ActivePage
    
    ' Reset the starting x and y coordinates.
    xPos = 2.0
    yPos = 9.25
    
    salesReportDoc = Application.ActiveDocument
    ' Retrieve the data from the SQL Server database.
    salesDataRecordset = salesReportDoc.DataRecordsets.Add( _
      "Provider=SQLOLEDB.1;Integrated Security=SSPI;" & _
      "Persist Security Info=True;Initial Catalog=Northwind;" & _
      "Data Source=VSTO\SQLEXPRESS;Use Procedure for Prepare=1;" & _
      "Auto Translate=True;Packet Size=4096;Workstation ID=VSTO;" & _
      "Use Encryption for Data=False;" & _
      "Tag with column collation when possible=False", _
      "select * from ""Northwind"".""dbo"".""Category Sales for 1997""", _
      0, "Northwind Category Sales for 1997")
    

    Note

    If you use SQL Server 2005 rather than SQL Server 2005 Express Edition, remove the \SQLEXPRESS from the Data Source.

    This code retrieves the sales data and places it into a data recordset. The DataRecordSet object is based on the ADO RecordSet object and can contain data from the following sources: Microsoft Office Excel workbooks, Microsoft Office Access databases, SQL Server databases, SharePoint lists, Oracle databases, or XML.

    Next, add code to loop through the rows of the DataRecordSet object, and then create a shape for each category. First, you need to know how many rows are returned.

  3. Add the following code to retrieve an array of the IDs of each row in the data recordset.

    ' Populate the array with the data row IDs. 
    ' The length of the array tells how many rows there are.
    salesRowIds = CType(salesDataRecordset.GetDataRowIDs(""), _
        Integer())
    

    The ADO RecordSet object has a RecordCount property; however, the DataRecordSet does not. The code uses the GetDataRowIDs method to create an array with an element for each row. The length of the array tells you how many rows are in the data recordset.

  4. Add the following code to loop through each row of data and pass the category’s sales to a method that draws a shape.

    ' Create a shape for each row of data.
    For i As Integer = 1 To salesRowIds.Length
        ' Create an array to hold the next row of sales data.
        salesData = CType(salesDataRecordset.GetRowData(i), _
            [Object]())
        ' Create a shape.
        DrawShape(i, Convert.ToDecimal(salesData(1)))
    Next
    
  5. Add the following code to display the contents of the data recordset.

    ' Display the actual data
    Application.ActiveWindow.Windows.ItemFromID( _
        Visio.VisWinTypes.visWinIDExternalData).Visible = True
    
  6. Add the following code to define the DrawShape method. This method takes two arguments. The first argument is a counter identifying which row of data is current. This is used to link the new shape to the appropriate row in the data recordset. The second argument is the sales amount for the current category.

    Private Sub DrawShape(ByVal item As Integer, ByVal sales As Decimal)
    
    End Sub
    
  7. Add the following code to the DrawShape method to determine what shape to draw.

    A green square is drawn if sales are $100,000 or above. A yellow triangle is drawn if sales are greater than $75,000, but less than $100,000. A red hexagon is drawn if sales are less than $75,000.

    If sales > CDec(100000) Then
        shapeType = "Square"
        shapeFillColor = "THEMEGUARD(RGB(146,208,80))"
    ElseIf sales > CDec(75000) Then
        shapeType = "Triangle"
        shapeFillColor = "THEMEGUARD(RGB(255,255,0))"
    Else
        shapeType = "Hexagon"
        shapeFillColor = "THEMEGUARD(RGB(255,0,0))"
    End If
    
  8. Add the following code to draw the shape and link it to the data.

    The DropLinked method creates a shape and links it to data in a data recordset. The first argument in this method is the type of shape to create. The second and third arguments are the x and y coordinates. The fourth argument identifies the data recordset. In this example, there is one data recordset, but you could have more than one on a page. The fifth argument identifies the row in the recordset to link to. The final argument identifies whether to apply a data graphic to the shape. Data graphics are discussed later in this article.

    ' Draw the shape, linked to the data.
    If shapeType = "Triangle" Then
        ' Position the triangle a bit above the other shapes. 
        vsoShape = currentPage.DropLinked( _
            Application.Documents.Item("BASIC_U.VSS").Masters.ItemU( _
            shapeType), xPos, yPos - 0.25, 1, item, True)
    Else
        vsoShape = currentPage.DropLinked( _
            Application.Documents.Item("BASIC_U.VSS").Masters.ItemU( _
            shapeType), xPos, yPos, 1, item, True)
    End If
    
  9. Add the following code to fill the shape with the appropriate color.

    You can control the appearance and behavior of a shape by working with the formulas in the shape's cells. To reference the shape’s cells, use the CellsSRC property. This property takes three arguments: the section, row, and column index of the cell you want to address. The code specifies the FillForegnd cell index. It then changes the shape’s fill color by setting the FormulaU property of the Cell object to the appropriate color.

    ' Fill each shape with the appropriate color.
    vsoShape.CellsSRC( _
        CShort(Visio.tagVisSectionIndices.visSectionObject), _
        CShort(Visio.tagVisRowIndices.visRowFill), _
        CShort(Visio.tagVisCellIndices.visFillForegnd)).FormulaU = _
        shapeFillColor
    
  10. Next, add the following code to determine where to position the next shape.

    There are eight categories in the database. The code draws two columns of four shapes.

    ' Determine the x and y position for the next shape.
    yPos -= 2.5
    ' If we are the bottom of the page, go to the next column.
    If yPos < 1.0 Then
        xPos = 6.25
        yPos = 9.25
    End If
    
  11. On the Build menu, click Build Solution and verify that the project compiles correctly with no errors.

  12. Press F5 to run the application.

  13. Open a new basic diagram and click the Sales report toolbar button.

    You see eight shapes added to the diagram, one for each category.

    Figure 6. Each shape linked to a row of data

    Each shape linked to a row of data

Customizing the Appearance of the Page and Data Graphics

The shapes in the diagram have data graphics next to them. The data graphics display the category name and the sales amount. By default, the data graphics appear to the right of the shape. Next, write code to change the location of the data graphics so they appear below each shape.

The DataGraphic property of the Shape object returns a reference to the data graphic master associated with the shape. To edit a master, you must first make a copy of it by calling its Open method. After making changes to the copy, you can call the Close method to merge the changes from the copy back to the original.

To customize the data graphics

  1. Add the following declaration to the ThisAddIn class.

    Private targetDataGraphicCopy As Visio.Master
    
  2. Add the following code to the DrawShape method to create a copy of the data graphic master. Add this code after the code to fill in the shape and before the code to determine where the next shape goes.

    targetDataGraphicCopy = vsoShape.DataGraphic.Open
    
  3. Add the following code to change the horizontal and vertical position of the data graphic belonging to the current shape.

    targetDataGraphicCopy.DataGraphicHorizontalPosition = _
        Visio.VisGraphicPositionHorizontal.visGraphicLeft
    targetDataGraphicCopy.DataGraphicVerticalPosition = _
        Visio.VisGraphicPositionVertical.visGraphicBelow
    
  4. Add the following code to merge the changes back to the original data graphic master.

    targetDataGraphicCopy.Close()
    
  5. On the Build menu, click Build Solution and verify that the project compiles correctly with no errors.

  6. Press F5 to run the application.

  7. Open a new basic diagram and click the SalesReport toolbar button.

    Each of the data graphics appears under the associated shape.

    Figure 7. Data graphic under the linked shape

    Data graphic under the linked shape

Next, you add a title to the diagram.

To add a title to the diagram

  1. Add the following declaration to the ThisAddIn class after the code to draw the shape.

    Private vsoCharacters As Visio.Characters
    
  2. Add the following code to the SalesReportButton_Click method to draw a rectangle.

    ' Draw a rectangle.
    vsoShape = currentPage.DrawRectangle(0.25, 10.375, 8.25, 10.875)
    
  3. Add the following code to add a text box to the rectangle.

    ' Add a text box to the rectangle.
    vsoShape.TextStyle = "Basic"
    vsoShape.LineStyle = "Text Only"
    vsoShape.FillStyle = "Text Only"
    
  4. Add the following code to add text to the title.

    ' Add the title text.
    vsoCharacters = currentPage.Shapes.ItemFromID(41).Characters
    vsoCharacters.Begin = 0
    vsoCharacters.End = 0
    vsoCharacters.Text = "Sales by Category"
    
  5. Add the following code to change the font size of the title to 18 point.

    ' Set the title font.
    vsoCharacters.Begin = 0
    vsoCharacters.End = 18
    vsoCharacters.CharProps( _
        CShort(Visio.tagVisCellIndices.visCharacterSize)) = CShort(18.0#)
    
  6. On the Build menu, click Build Solution and verify that the project compiles correctly with no errors.

  7. Press F5 to run the application.

  8. Open a new basic diagram and click the Sales report toolbar button.

    The sales report diagram now has a title.

Saving the Diagram as a Web Page

The Save as Web Page feature of Visio enables you to publish a Visio diagram on the Web. Click the File menu, and then click Save as Web Page to display the Save As dialog box, so you can specify the name. location, and title of the Web page. Click Publish to display the Save As Web Page dialog box, so you can specify additional options, such as Pan and Zoom, which provides a way to navigate around the diagram in the browser.

Figure 8. Options for saving diagrams as Web pages

Options for saving diagrams as Web pages

In the following procedures, you use the Save as Web Page API in your code to programmatically save the sales by category diagram as a Web page.

To save the diagram as a Web page

  1. Add a project reference to the Microsoft Visio 12.0 Save As Web Type Library. In Solution Explorer, right-click the References node, and then click Add Reference.

  2. In the Add Reference dialog box, click the COM tab. Scroll to and select the Microsoft Visio 12.0 Save As Web Type Library, and then click OK.

  3. Add the following declarations to the ThisAddIn class.

    Private webPageButton As Office.CommandBarButton
    Private vsoSaveAsWeb As Visio.SaveAsWeb.VisSaveAsWeb
    Private vsoWebSettings As Visio.SaveAsWeb.VisWebPageSettings
    
  4. Add the following code to the AddCommandBar method. This code adds a second button to the toolbar.

    ' Add a button with an icon that represents the Web.
    webPageButton = _
        CType(commandBar.Controls.Add( _
        Office.MsoControlType.msoControlButton), _
        Microsoft.Office.Core.CommandBarButton)
    webPageButton.Tag = "Save as Web page"
    webPageButton.FaceId = 3044 
    webPageButton.TooltipText = "Save as Web page"
    
    AddHandler webPageButton.Click, AddressOf WebPageButton_Click
    
  5. Add the following method to save the diagram as a Web page when the user clicks the toolbar button.

    Private Sub WebPageButton_Click( _
        ByVal ctrl As Office.CommandBarButton, _
        ByRef CancelDefault As Boolean)
    
    End Sub
    
  6. Add the following code to the WebPageButton_Click method to initiate Web page creation.

    ' Get the SaveAsWeb object from the application.
    vsoSaveAsWeb = CType(Application.SaveAsWebObject, _
        Visio.SaveAsWeb.VisSaveAsWeb)
    ' Get the SaveAsWeb settings object from the SaveAsWeb interface
    vsoWebSettings = CType(vsoSaveAsWeb.WebPageSettings, _
        Visio.SaveAsWeb.VisWebPageSettings)
    

    The VisSaveAsWeb object is located in the Save as Web Page API. This object contains methods and property settings used when you save a diagram as a Web page. To use this object, first get the SaveAsWebObject property of the Application object, and then cast that appropriately.

    The VisWebPageSettings object is also located in the Save as Web Page API. This object contains the settings for the Web page. The WebPageSettings property of the VisSaveAsWeb object represents the settings for the current Save as Web Page operation.

  7. Add the following code to the WebPageButton_Click procedure to indicate which document to save as a Web page.

    vsoSaveAsWeb.AttachToVisioDoc(Application.ActiveDocument)
    
  8. Add the following code to set the title and file name of the Web page.

    vsoWebSettings.PageTitle = "Sales by Category"
    vsoWebSettings.TargetPath = "c:\SalesByCategory.htm"
    
  9. Add the following code to display custom properties in the left pane of the browser. You set the custom properties in the next step.

    ' Add a left pane in the browser window.
    vsoWebSettings.PropControl = 1
    ' Add a Search tool in the browser window.
    vsoWebSettings.Search = 1
    ' Add a Pan and Zoom tool in the browser window.
    vsoWebSettings.PanAndZoom = 1
    ' Add a Go To Page tool in the browser window.
    vsoWebSettings.NavBar = 1
    
  10. Add the following code to specify that the browser should be opened after the Web page is created and that Visio dialog boxes should be suppressed during the creation of the Web page.

    vsoWebSettings.OpenBrowser = 1
    vsoWebSettings.QuietMode = 1
    
  11. Finally, add the following code to create the Web page.

    vsoSaveAsWeb.CreatePages()
    
  12. On the Build menu, click Build Solution and verify that the project compiles correctly with no errors.

  13. Press F5 to run the application.

  14. Open a new basic diagram and click the Sales report toolbar button.

  15. Click the Save as Web Page toolbar button.

    The browser should open and display the Sales by Category Web page.

    NoteNote

    As a security precaution, your browser may block the custom properties from displaying. If so, allow the blocked content when the dialog box is displayed. At that point, the navigation frame should appear with sections for Pan and Zoom, Details, and Search Pages.

    Figure 9. Using the navigation frame to view the shapes on the Web page

    Using the navigation frame to view the shapes

Conclusion

After you become familiar with the Visio object model and how to work with shapes and data, you have an excellent tool for visually representing information. In this article, you learned to work with basic shapes, but you can also explore using additional shapes, such as pie charts, bar graphs, flowcharts, and organization charts. You can link these shapes to a variety of external data sources and provide users with both an automated and interactive experience for visualizing information.

Additional Resources

You can find more information about the topics discussed in this article at the following locations:

About the Author

Robert Green is a developer, writer and trainer, and is a senior consultant with MCW Technologies. Robert is a co-author of AppDev's Visual Basic, C#, and Windows Workflow Foundation courseware. Prior to joining MCW, Robert worked at Microsoft, and was the Visual Studio Tools for Office Product Manager.