Volume 3: Programming with the Visio Object Model disclaimer


Managing External Data Sets



Download 0.78 Mb.
Page26/36
Date29.01.2017
Size0.78 Mb.
#11974
1   ...   22   23   24   25   26   27   28   29   ...   36

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. The linking process updates a shape to import data into existing Shape Data fields, and adds new fields as needed.

Each of the actions that can be performed through the user interface can also be performed programmatically. Using programming techniques to add datarecordsets, create and link shapes, add data graphics, refresh data, and detect and respond to changes after refresh are the topics of this module.


Module Objectives

After completing this module you will be able to:

  • Add data to Visio programmatically from different data sources

  • Describe the objects, properties, 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

Lesson 1: Data Link Concepts


The first part of managing linked data is getting connected to the data. There are three variations of the Add method for creating a new datarecordset: Add, AddFromConnectionFile, and AddFromXML.

The key to using these methods is setting up the connection string and the command string. The connection string identifies the data’s location of the data and any security information needed for accessing the data. The command string is used to specify what part of the data is desired.

At the end of this lesson we will review an example that is more extensive than the simple code snippets in the Help files. This example adds datarecordsets, adds shapes, links the shapes to the data, adds and modifies a data graphic, and lays out the drawing. The final solution is an organizational chart created from data in an Excel file, but uses simple rectangle shapes and data graphics to display the organizational information on the shapes.

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, methods, 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

22.Overview of Objects / Methods / Properties


Big changes occurred to Visio 2007 in the area of data support. 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). There are also new tools for displaying data associated with shapes (data graphics). 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.

Data Linking


The DataRecordSets object is part of the Document. 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. There may be multiple DataRecordSet objects within a document, each pointing to a different data source.

The data in a DataRecordSet contains columns of data, each column representing a field. The DataColumns is the collection of all of the columns. The DataColumn object allows custom mapping of the column to a ShapeSheet cell.

The DataConnection object holds the information for making the connection to the data source.

When data recordset rows are added, changed, or deleted, and when data recordset columns are added or deleted, in each case as a result of a data recordset being refreshed, properties of the DataRecordsetChangedEvent object return arrays of the affected rows or columns.



The relationship of the data linking objects to other portions of the Visio object model is shown in the graphic below.


Methods


DataRecordSets

Description

AddFromConnectionFile

Adds a DataRecordset object to the DataRecordsets collection, associates it with a new or existing DataConnection object, 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.

AddFromXML

Adds a DataRecordset object to the DataRecordsets collection and fills it with data from an XML file, without requiring a DataConnection object.

GetLastDataError

Gets the ActiveX Data Objects (ADO) error code, ADO description, and data recordset ID associated with an error that results from adding a new data recordset or refreshing the data in an existing recordset.




DataRecordSet

Description

GetAllRefreshConflicts

Returns an array of all the shapes in the data recordset that have refresh conflicts.

GetDataRowIDs

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.

GetMatchingRowsForRefreshConflict

Returns an array of IDs of data rows that may have a broken link to a specified shape after a refresh operation.

GetPrimaryKey

Returns the name of the primary key column of the data recordset.

GetRowData

Returns an array of values for each column in the specified data row. Returns an array of column names when data row 0 is specified.

Refresh

Refreshes the data in the data recordset.

RefreshUsingXML

Refreshes the data in a data recordset that has no data connection.

RemoveRefreshConflict

Removes all conflict information from the drawing file.

SetPrimaryKey

Sets the column name of the primary key column used during a refresh operation.




DataColumns

Description

SetColumnProperties

Sets the properties of the specified columns to the values specified.




DataColumn

Description

GetProperty

Returns the value of the data column property passed in as VisDataColumnProperties.

SetProperty

Sets the specified property (as VisDataColumnProperties) to the specified value.




Page

Description

DropLinked

Creates a shape linked to data on the page.

DropManyLinkedU

Creates many shapes linked to data on the same page.

GetShapesLinkedToData

Returns an array of shapes on the page linked to a specific data recordset.

GetShapesLinkedToDataRow

Returns an array of shapes on the page linked to a particular data row in a data recordset.

LinkShapesToDataRows

Links an array of shapes to an array of data rows from a particular data recordset on a one-to-one basis, by matching positions in the arrays. Optionally, applies a data graphic to linked shapes.



Selection

Description

AutomaticLink

Automatically matches shapes to data rows by comparing shape-attribute values with recordset-data-row values and finding the best match. You can specify the column (field) in each row of data and the shape attribute upon which to base the comparison.

BreakLinkToData

Breaks the link between one or more shapes and the data row or rows to which the shape or shapes are linked.

GetIDs

Returns an array of the IDs of shapes in a selection so that you can link them to data.

LinkToData

Links a single data-recordset row to a shape or to all shapes in a selection. Optionally, applies a data graphic to linked shapes.



Shape

Description

BreakLinkToData

Breaks the link between one or more shapes and the data row or rows to which the shape or shapes are linked.

GetCustomPropertiesLinkedToData

Returns an array of indices of shape data linked to a particular data recordset.

GetCustomPropertiesLinkedColumn

Returns the name of the column in the specified data recordset that is linked to the specified shape-data field.

GetLinkedDataRecordsetIDs

Returns an array of the IDs of data recordsets linked to a shape.

GetLinkedDataRow

Returns the ID of the row to which a shape is linked in the specified data recordset.

IsCustomPropertyLinked

Determines whether a specified shape data item is linked to a particular data recordset.

LinkToData

Links a single data-recordset row to a shape or to all shapes in a selection. Optionally, applies a data graphic to linked shapes.


Properties


DataRecordset

Description

CommandString

Gets or sets the command string used to query the data source.

DataAsXML

Permits exporting data in XML format from Visio. Gets the XML string describing the data recordset following the ADO XML schema. Contains all the rows in the data recordset with Visio row IDs pre-pended to them. Read-only.

DataColumns

Returns the DataColumns object associated with the DataRecordset object.

DataConnection

Returns the DataConnection object associated with the DataRecordset object. Returns Nothing for a connectionless DataRecordset object. Read-only.

LinkReplaceBehavior

Gets or sets how existing links between shapes and data rows are handled during application of the Selection.AutomaticLink method.

RefreshInterval

Gets or sets the refresh interval for the data recordset in minutes. Default value is 0, which means that refreshing by interval never occurs. Minimum value is one minute.

RefreshSettings

Gets or sets refresh settings for the data recordset, as a combination of VisRefreshSettings values.

TimeRefreshed

Returns the date and time of the last refresh operation. Read-only.




DataConnection

Description

ConnectionString

Gets or sets the connection string used to access an existing DataConnection object or to create a new DataConnection object.

Timeout

Gets or sets how long (in seconds) to attempt to establish a data connection before terminating the attempt and generating an error. Default is 15 seconds.




DataColumn

Description

DataRecordset

Returns the DataRecordset object associated with the parent object.

DisplayName

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.




DataRecordsetChangedEvent

Description

DataColumnsAdded

Returns an array of the IDs of columns added to the data recordset as part of a refresh operation. Read-only.

DataColumnsChanged

Returns an array of the IDs of columns in the data recordset whose type changed as part of a refresh operation. Read-only.

DataColumnsDeleted

Returns an array of the IDs of columns deleted from the data recordset as part of a refresh operation. Read-only.

DataRecordset

Returns the DataRecordset object associated with the parent object.

DataRowsAdded

Returns an array of the IDs of rows added to the data recordset as part of a refresh operation. Read-only.

DataRowsDeleted

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. Read-only.




Application

Description

DataFeaturesEnabled

True if data features are enabled for the current instance of Visio. Read-only.




Document

Description







DataRecordsets

Returns the collection of DataRecordset objects associated with the Document object.




Window

Description







SelectedDataRecordset

Gets or sets the DataRecordset object that is selected on the active tab of the External Data window.

SelectedDataRowID

Gets or sets the row ID of the selected row displayed on the active tab of the External Data window.



23.Data Sources


The Data Selector wizard enables the Visio user to connect to external data sources and bring that data into the Visio environment. Data sources you can connect to include Microsoft Office Excel worksheets, Microsoft Office Access databases, Microsoft SQL Server databases, Microsoft SharePoint lists, and other OLEDB or ODBC data sources, such as an Oracle database.

To connect your Visio drawing to a data source programmatically, use the new additions to the Visio API for data connectivity which include the following objects and their associated properties, methods, and events:



  • DataRecordsets collection object

  • DataRecordset object

  • DataConnection object

  • DataRecordsetChangedEvent object

  • DataColumns collection object

  • DataColumn object




Figure . Data objects as they appear in the user interface.

Each Visio Document object has a DataRecordsets collection, which is empty until you make a connection to a data source. To connect a Visio document to a data source, you add a DataRecordset object to the DataRecordsets collection of the document. A DataRecordset object has a DataColumns collection of DataColumn objects, each of which is mapped to a corresponding column (field) in the data source. When you add a DataRecordset object by connecting to an data source, Visio abstracts the connection in a DataConnection object, and the DataRecordset object is said to be connected.

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. The resulting DataRecordset object is said to be connection-less. An example of using this technique to create a DataRecordset is presented later in this material.

The connection between a data source and a DataRecordset object goes only one way—from the data source to the Visio drawing. If data in the source changes, you can refresh the data in the drawing to reflect those changes. You cannot, however, make changes in the data in the drawing and then push those changes back to the data source. Visio can only read the data source. It cannot update the data in the source.


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. Accessing different data sources only requires a modification to the connection string used that describes the location of the data.
Try it!

  1. Open from the Samples directory Working With DataRecordsets.vsd.

  2. Use the Data Selector wizard (Data > Link Data to Shapes...) to import the data in Orgdata.xls data from the Samples folder. When the import is finished, the data is displayed in the External Data window.

  3. Run the macro to display the DataConnection object (View > Macro > InterestingMacros.GetDataConnectionObject). The connection string is displayed in the Immediate window. The code and the connection string are listed below.

Public Sub GetDataConnectionObject()

'Displays the connection string from the DataConnection object

'for the most recently opened datarecordset

Dim vsoDataConnection As Visio.DataConnection

Dim vsoDataRecordset As Visio.DataRecordset

Dim iCount As Integer

iCount = ActiveDocument.DataRecordsets.Count

Set vsoDataRecordset = ActiveDocument.DataRecordsets(iCount)

Set vsoDataConnection = vsoDataRecordset.DataConnection

Debug.Print vsoDataConnection.ConnectionString

End Sub

Sample connection string for Excel data source:



Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=C:\Program Files\Microsoft Office\OFFICE12\Samples\1033\ORGDATA.XLS;Mode=Read;Extended Properties="HDR=YES;IMEX=1;MaxScanRows=0;Excel 12.0;";Jet OLEDB:System database="";Jet OLEDB:Registry Path="";Jet OLEDB:Engine Type=35;Jet OLEDB:Database Locking Mode=0;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password="";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False;Jet OLEDB:Support Complex Data=False

Sample connection string for SharePoint list:

PROVIDER=WSS;DATABASE=http://name.officeisp.net/ShapingFuturez;LIST={05F6AF30-326C-4932-83C1-35BF2015F718};

Sample connection string for SQL Server:

Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=localhost\sqlexpress;Initial Catalog=WhitePaperSamples

Add a DataRecordset

DataRecordsets.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.
Try it!

  1. From the file Working with DataRecordsets.vsd run the macro View > Macro > InterestingMacros.AddDataRecordsetFromConnectionObject. The macro will create two DataRecordsets from the sample data in ORGDATA.xls.

  2. View the code for this macro. The first time the Add method is used, the connection information is passed as a string. Upon completion of this first Add the DataRecordset object is created and its DataConnection object is established.

Set vsoDataRecordset = ActiveDocument.DataRecordsets.Add( _

strConnection, strCommand, 0, "Org Data")



  1. The second time the Add method is used the DataConnection object previously created is passed as the parameter to the Add method. This creates another DataRecordset from the same data in ORGDATA.xls.

Set vsoDataRecordsetTwo = ActiveDocument.DataRecordsets.Add( _

vsoDataRecordset.DataConnection.ID, _

strCommand, 0, "Org Data")


Tip:

Anytime a DataRecordset exists, there will be a DataConnection object containing the connection information for the data used to create the DataRecordset (except for connectionless DataRecordsets). This DataConnection can be used to create more instances of the same data.


DataRecordsets.AddFromConnectionFile

Creating a DataRecordset from an Office Database Connection file (.odc) is done with the AddFromConnectionFile method of the DataRecordsets object. If an .odc file exists pass the path of the .odc file in the first parameter of the method similar to the code presented below.

Public Sub AddFromConnectionFile_Example()

'Create a DataRecordset from an .odc file using the

'AddFromConnectionFile method

Dim strFile As String

Dim strName As String

Dim vsoDataRecordset As Visio.DataRecordset

strFile = "C:\Documents and Settings\System Admin\My Documents\" & _

"My Data Sources\Northwind Employees.odc"

strName = "Data from ODC"

Set vsoDataRecordset = _

ThisDocument.DataRecordsets.AddFromConnectionFile( _

strFile, 0, strName)

End Sub



Note:

An .odc file can be created in different ways including using tools in SharePoint and tools in Access and Excel. The .odc file used for this example was created with the Data Connection Wizard in Excel.



Try it! (optional)

  1. Use Excel to create an .odc file. This can point to any Excel file or easily accessible database such as Northwind.mdb. Note the path where the .odc file is saved.

  2. Modify the macro AddFromConnectionFile_Example in the file Working with DataRecordsets.vsd to create a DataRecordset based on the new .odc file just created.



DataRecordsets.AddFromXML

Adds a DataRecordset object to the DataRecordsets collection, and fills the resulting data recordset with data supplied in the form of an XML string.

In contrast with data recordsets created by using the Add or AddFromConnectionFile methods, data recordsets created by using the AddFromXML method are not associated with a DataConnection object.




Note:

Because DataRecordsets created using AddFromXML have no DataConnection object, they are referred to as a connection-less data source.

What's more, Visio never refreshes a data recordset you created by using the AddFromXML method automatically, regardless of the setting of the DataRecordset.RefreshInterval property. To refresh the data in such a data recordset, you must call the DataRecordset.RefreshUsingXML method.


Try it!

  1. From the file Working with DataRecordsets run the macro View > Macro > InterestingMacros.AddFromXML_Example. The macro will create a DataRecordset from the XML data defined within the macro.

  2. View the code. Following is the XML data used to create the DataRecordset. Compare this to the VBA code to see how the XML data is put into a string.

xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882'

xmlns:rs='urn:schemas-microsoft-com:rowset'

xmlns:z='#RowsetSchema'>







rs:number='2' rs:nullable='true' rs:maydefer='true' rs:write='true'>























  1. Run the macro GetDataConnectionObject. This will trip the error handler when checking for the DataConnection object and display a message in VBA’s Immediate window.

Accessing data in the DataRecordset


When you import data, Visio assigns integer row IDs, starting with the number 1, to each data row in the resulting datarecordset, based on the order of the rows in the original data source. Visio uses data row IDs to track the rows when they are linked to shapes and when data is refreshed. If you want to access data rows programmatically, you must use these data row IDs.

Two important methods for retrieving information from DataRecordsets include GetDataRowIDs and GetRowData. Use GetRowData to retrieve all columns of data within a given row. Use GetDataRowIDs to retrieve a subset of IDs within the DataRecordset that satisfy a given criteria string.

A sample of how to use these methods is included in the following demonstration code.

Try it!

  1. Make sure a datarecordset exists and then run the macro GetDataRecords. This macro is a simple example of using GetRowData and GetDataRowIDs and writing the information to the VBA’s Immediate Window.

  2. Run the macro View > Macro > BuildOrgMacros.DoItAll. This macro builds an organizational chart. It creates a DataRecordset, 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, modifies the data graphic that displays the organizational data, and then lays out and resizes the page.

  3. Look at the code in the macro AddDataRecordSet. This macro is used by the DoItAll macro. Note that it uses the DataRecordSets.Add method to create the datarecordset. It also sets the primary key field of the datarecordset.

  4. Look at the code in the macro DropManyLinkedShape. 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. Note that the data graphic is added at the same time the shapes are created.

  5. Look at the code in the macro AddAndGlueConnectors. This macro utilizes GetRowData and GetDataRowIDs to extract the needed information.

The key segment of code follows. 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.

GetRowData is used to extract the fields from a row in the form of an array of variant data.

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.

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.

This is enough information to give us the “from shape” and “to shape” so that we can add and glue the connectors.

'Get the shape id of the "Reports_To" shape

varRowData = vsoDataRecordset.GetRowData(ShapeRowID)

strReportsTo = varRowData(2)

'Find the datarecordset row that has this "Reports_To" data

'in the "Name" field

strCriteria = "Name = '" & strReportsTo & "'"

lngNameRowIDs = vsoDataRecordset.GetDataRowIDs(strCriteria)

'Find the shape linked to this data row

ActivePage.GetShapesLinkedToDataRow vsoDataRecordset.ID, _

lngNameRowIDs(0), lngShapeIDs



  1. The macro ModifyDataGraphicMaster modifies the default data graphic applied to the shapes to add another text callout that displays the employee’s “Title” information.

  2. The final step is in LayoutAndResize. 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.

We will explore the other macros in this file later in this module.


Download 0.78 Mb.

Share with your friends:
1   ...   22   23   24   25   26   27   28   29   ...   36




The database is protected by copyright ©ininet.org 2024
send message

    Main page