Welcome to MSDN Blogs Sign in | Join | Help

Chris Hopkins' Visilog

Visio Shape and Solution Development
Visio 2010 - Check the Edition at Runtime

With the release of Visio 2007 you could no longer rely on just a check to see if Visio was installed, you also needed to know the Edition or SKU that was installed if you were to use the Data Linking or Data Graphic capabilities via the API.  Now with the release of Visio 2010 Premium there is another reason to check the edition at runtime.

Visio 2010 Premium includes new functionality for rules based validation which is available via the API, however, this functionality and APIs are only available to user of the Premium edition, meaning that if your solution uses these APIs you will need to make sure that they are available before calling them.

CurrentEdition is a new property that has been added to the Application class which is set to one of the following values at runtime:

visEditionStandard
visEditionProfessional
visEditionPremium

Using this new property you can determine if the running instance of Visio that is hosting your solution supports rules validation.

Here are two simple properties that you can add to your ThisAddin class (if you are using VSTO) that you can use to:

Check for Data features support:

internal bool DoesVisioSupportDataFeatures
{
    get
    {
        bool retVal = false;

        if (this.Application != null &&
            this.Application.TypelibMinorVersion >= 12)
        {
            retVal = this.Application.DataFeaturesEnabled;
        }

        return retVal;
    }
}

Check for Process features support:

internal bool DoesVisioSupportProcessFeatures
{
    get
    {
        bool retVal = false;

        if (this.Application != null &&
            this.Application.TypelibMinorVersion >= 14)
        {
            if (this.Application.CurrentEdition ==
                Visio.VisEdition.visEditionPremium)
            {
                retVal = true;
            }
        }

        return retVal;
    }
}

Customize the Server shape with Visio Guy

The Visio Guy site released a new tool that will help you customize the icon on the Server shape that ships with Visio so that you can easily create a server shape that represents your individual needs.

visio-server-icon-tool-big

Take a look at the article and download the tool today.

Visio 2010 Product Team blog

I just wanted to publicize the Visio Product team’s blog which is being updated with important articles about the new features and APIs that will be available with the release of Visio 2010.

Visio 2007 Add-in for Operations Manager 2007 R2 Released

Recently we released a new add-in for Visio 2007 that allows you to connect your diagrams to data from an Operations Manager server.

Visio Add-in Samples 2

To download this new add-in or to read more details please visit the System Center Operations Manager blog.

Adding your .NET DataSet as an External DataRecordset in your Visio diagrams

Visio 2007 provides the capability to add data to your diagrams from several supported data sources such as Access, Excel, SharePoint, and SQL, etc.  You can also use this capability within your Visio add-ins as the Visio object model provides many objects, methods, and properties for adding, removing, and manipulating DataRecordsets within your add-in.

Here is some sample code that demonstrates taking a .NET DataTable and adding it to a Visio drawing…

// create a new instance of our DataTable
TeamDataSet.TeamMembersDataTable data = new TeamDataSet.TeamMembersDataTable();

// read the sample data from a file to populate our data table
data.ReadXml(dataPath + "sample data.xml");

// convert the .NET DataTable to ADO Recordset XML using this class provided by the Visio 2007 SDK
string newXmlData = ADONET2ADO.ConvertToAdoRecordsetXml(data);

// create a new datarecordset in our Visio drawing using the converted XML
Visio.DataRecordset newRecordSet = this.VisioDocument.DataRecordsets.AddFromXML(newXmlData, 0, "Team Members");

Once this DataRecordset has been added to the document you can open the External Data window to view the data within your diagram and link the records in this DataRecordset to the shapes in your diagrams.

One issue I do want to point out is a small change that I made to the ADONET2ADO class that shipped with the Visio 2007 SDK.  Attached to this article is an updated version of the ADONET2ADO class that contains one small fix to the TranslateType function for the System.String case.  When the SDK was released this case converted System.String to ADODB.DataTypeEnum.adVarChar but this type does not handle Unicode which is very common with System.String since strings .NET are Unicode based.

Click here to download the updated ADONET2ADO class.

New shapes for System Center Operations Manager

image

The System Center forum hosts a download that contains three new stencils dedicated to System Center Operations Manager.  These stencils contain approximately 64 shapes

You can easily add these stencils to your My Shapes menu by unzipping the content of the download into your My Shapes folder under My Documents (XP) or Documents (Vista)…

image

image

Each shape is a high quality raster based image with no shape data or data graphics attached so you have a fresh canvas to build your Operations Manager diagrams.

Click here to download the System Center Operations Manager shapes.

Rotate text on Timeline shapes

I recently received a request from a user who wanted the ability to:

1. rotate the text for the Bracket Interval shape to an angle such as 45deg.
2. display the interval name above the date instead of below.

image

I took the built-in shape and customized it to support these two requirements, allowing you to have a Bracket Interval shape that looks like this…

image

This new shape has an additional right-click menu item that toggles the text from ‘Horizontal Text’ to ‘Angled Text’.  When set to ‘Angled Text’ a new control handle appears that allows you to set the angle of the text.

Feel free to download my Visio diagram that contains this new shape and use this shape in your timeline diagrams.

Visio Slide Show

(updated 6/11/09 – added support for a dialog to allow you to set the interval between slides)

Recently I was asked if it was possible to set a timer to automatically switch to the next page when in full screen mode, producing a slide show style presentation mode.

I decided to do this using VBA as this code can easily be added to any Visio document that needs this functionality.

FYI, when the slide show macro is running and the last page in the document is reached, the slide show will continue with the first page via a continuous loop.

To add this functionality to your document:

  1. Open your document
  2. Open the Visual Basic editor, ALT + F11 or from the Tools > Macro > Visual Basic Editor menu item
  3. Paste the code below into the ThisDocument module via the Visual Basic editor

    1. By default the editor opens the ThisDocument module.

      image

Start the slide show

From the Tools > Macros > ThisDocument menu select StartSlideShow

image

Stop the slide show

Simply press the ESC key.  This will exit full screen mode and also trigger the timer in the macro to stop, returning you to the Visio application window.

Set the Interval

From the Tools >Macros > ThisDocument menu select SetInterval

image 

Download the Visio diagram that contains this code here.

Here is the VBA code:

Option Explicit

Private WithEvents g_vsoApplication As Visio.Application

Private g_interval As Integer
Private Const DEFAULT_INTERVAL As Integer = 5

Private g_fullScreen As Boolean

Public Sub SetInterval()

    Dim entryVal As String
    Dim entryError As Boolean
   
reEnterValue:
   
    ' init our error flag
    entryError = False
   
    ' determine if we show the default value or the last entered value
    Dim initVal As Integer
   
    If Not (g_interval = DEFAULT_INTERVAL) And Not (g_interval = 0) Then
        initVal = g_interval
    Else
        initVal = DEFAULT_INTERVAL
    End If
   
    ' get a new value from the user
    entryVal = InputBox("Enter the interval (in seconds 1 - 60)", "Set Slide Show interval", initVal)
   
    If Len(entryVal) = 0 Then
        ' the user pressed cancel
        Exit Sub
    End If
   
    Dim tmpInterval As Integer
   
    If IsNumeric(entryVal) Then

        tmpInterval = Conversion.CInt(entryVal)
       
        If tmpInterval < 1 Or tmpInterval > 60 Then
            entryError = True
        End If

    Else
   
        entryError = True
   
    End If
   
    If entryError Then
   
        MsgBox "Please enter a value between 1 - 60"
        GoTo reEnterValue
       
    End If

    g_interval = tmpInterval

End Sub

Public Sub StartSlideShow()

    Set g_vsoApplication = Application

    Dim iNextPage As Integer
    iNextPage = 1
   
    ' set the first page
    ActiveWindow.Page = ThisDocument.Pages(iNextPage)

    ' enter full screen mode
    Application.DoCmd visCmdFullScreenMode

    g_fullScreen = True

    Do While g_fullScreen

        ' start timer
        Dim pTime, pStart, pEnd, tTime, lTime
       
        'five second loop
        pTime = g_interval
        pStart = Timer
       
        Do While (Timer < pStart + pTime) And g_fullScreen = True
            DoEvents
            lTime = (pStart + pTime) - Timer
        Loop
       
        ' get the next page index that we need to switch to
        If iNextPage = ThisDocument.Pages.Count Then
            iNextPage = 0
        End If
       
        iNextPage = iNextPage + 1
       
        ' get the next page and switch to it
        Dim vsoNextPage As Visio.Page
        Set vsoNextPage = ThisDocument.Pages(iNextPage)
        ActiveWindow.Page = vsoNextPage
       
        ' reset timer
        pEnd = Timer
        tTime = pEnd - pStart
   
    Loop
   
End Sub

Private Sub g_vsoApplication_KeyPress(ByVal KeyAscii As Long, CancelDefault As Boolean)

    ' kill the code on any keypress
    g_fullScreen = False

End Sub

State management for CommandBars v2.0

After I posted my source for managing CommandBarButton and CommandBarPopup objects I received a few requests to include management of CommandBarButtons that control the state of AnchorBar windows.

As you know you can add your own windows within the Visio drawing window, similar to the Shape Data window.  These type of windows are typically controlled via a menu item that toggles its state or caption depending on the visible state of the window.  For example, the caption of the menu item changes or the visual state or the menu item switches between a pushed or unpushed state.

Good news.  I updated my CommandBar management code to support this functionality.

Included in this update is my new VisioCommandBarButtonForAnchorWindow class.  This new class contains the functionality for toggling either the Caption property or the State property of the CommandBarButton based on the Visible state of your AnchorBar window.

Getting Started

After you download this source you should be able to compile it and run it.  You will need VS 2008, VSTO 3.0, and Visio 2007.  Visio 2007 will also need to have .NET Programmability Support installed (PIA).

Feel free to add the UIMgr.cs and the VisioCommandBars.cs source files to your own project.  In most cases all you will need to do is change the AddUI method to add your specific CommandBarButtons or PopUps.

Click here to download the sample VSTO based add-in that demonstrates how these wrapper classes are used, along with the full source to the wrapper classes.

Check before you customize CommandBars…

Recently I have noticed a few add-ins that lock customization on the MenuBar object after the add-in has made its changes, i.e. adding a custom menu.  There are valid reasons for using this functionality but you also have to consider the impact to other add-ins that may be installed.

Example:
menuBar.Protection = MsoBarProtection.msoBarNoCustomize

If you are setting the Protection property on the MenuBar object you are preventing the user from being able to make modifications to the entire MenuBar object.  This will protect your custom menu but it will also prevent any other add-ins from making changes to the MenuBar object.

If another add-in attempts to customize the CommandBars after this property is set the add-in will receive the following exception, which is not easily interpreted as a protection issue…

clip_image002

Error HRESULT E_FAIL has been returned from a call to a COM component.

Best Practices

1. Do not set the Protection property of the MenuBar object unless it is absolutely necessary.  Rather than setting this property add the additional logic to manage your CommandBar objects.  For example, check to see if your UI changes exist and if not simply add them back.  I typically do this when my add-in is first loaded.

2. I started adding the following code to all of my add-ins.  Before I attempt to make modifications to the CommandBar objects I check the Protection property and reset it to msoBarNoCustomize before attempting to make my changes.  This ensures that my add-in is able to make changes to the CommandBar objects.

...
CommandBars commandBars = Globals.ThisAddIn.Application.CommandBars as CommandBars;
CommandBar menuBar = commandBars["Menu Bar"] as CommandBar;

if ((menuBar.Protection & MsoBarProtection.msoBarNoCustomize) == MsoBarProtection.msoBarNoCustomize)
{
    // make sure we can always add out UI
    menuBar.Protection = MsoBarProtection.msoBarNoProtection;
}
...
Reset the Menu and Toolbars

Most add-ins that are developed for Visio make modifications to the Visio menu and toolbars.  The add-in developer is responsible for making the appropriate changes to the Visio UI in a manner that does not affect the operation of Visio or other add-ins that maybe installed.  They are also responsible for cleaning up their changes.

Uninstall is a typical scenario that is often overlooked when making changes to the Visio menus and toolbars.  In this scenario the user has installed an add-in for Visio but at some point decided to uninstall the add-in.  After the user uninstalls the add-in they notice there are still menus or toolbars from the add-in that should have been removed.  At this point the user is left to manually clean up these items using the Customize dialog by clicking on the View > Toolbars > Customize menu.

image

For example, by clicking on the Menu Bar item as shown above and then clicking on the Reset button, the main menu in Visio will be reset back to the default, removing any customizations that have been made by the user or by any add-ins.

I have seen instances where the Reset button is not enabled.  This could be because an add-in explicitly set protection on a menu or toolbar to try and keep someone from modifying it or removing it.  In this situation you are left with the option of finding the file that saves all UI changes and deleting it from your system.  This file is called ‘ custom12.vsu ’ and is located in your profile folder, typically ‘ C:\Users\[user name]\AppData\Roaming\Microsoft\Visio ’.  If you deleted this file (while Visio is not running) all menu and toolbar changes will be removed.

My ResetUI Tool

I have a small macro that resets all changes made to the menus and toolbars in the attached Visio document.

Click here to download this document.

When you open this document VBA macros are disabled by default so you have to enable the macros in the document by clicking the button on the Security Warning bar…

image

After you enable the macros in this document you will be asked if you want to reset the UI.  Answering Yes to this will run the ResetUI macro which calls reset on all built-in menus and toolbars, disables any protection that has been set on any of the menus or toolbars, and removes any custom menus or toolbars that were added by third parties.

Using WPF Windows in Visio add-ins

With the release of .NET Framework 3.0, Windows Presentation Foundation was introduced.  WPF is the new UI development environment for forms based development.

If you are not familiar with WPF you can take a look at this introduction article on MSDN.

 

Setup your Visio add-in to support WPF

All you need to do to your add-in project to support WPF is to add references to the following assemblies…

WindowsBase.dll
PresentationCore.dll
PresentationFramework.dll

image

Create a WPF Window

The Add New Item dialog for a VSTO 3.0 project filters out all WPF templates except the User Control (WPF) template.  WPF User controls can be hosted within a WinForm instance, however we want the entire window to be WPF based.  To do this we can create a new temporary WPF project in Visual Studio and then use the Add Existing Item function in our VSTO project to copy the new WPF window files.

To create a new WPF project in Visual Studio start Visual Studio and choose the WPF Application template from the New Project dialog.  Now you can use this project to create the shell for all the WPF windows you need in your Visio add-in project.

Add a new window to this project by selecting the Window (WPF) template.

image

To add this new Window to your Visio add-in, use the Add Existing Item function.

image

Browse to the location of the WPF Application project and choose the files for the WPF window that you want to add.  You will have to set the filter to “All Files” in order to see both the .xaml and the xaml.cs files.

image

image

This function will make a copy of  selected files to your Visio add-in project folder.  At this point you can open the designer and finish the layout and development of your window.  But before you use this window you will need to fix the namespace for these files that were added.

Changing the NameSpace

Because we created the WPF window in another project, the namespace is not the same as the namespace of our Visio add-in project.  You can leave it as-is but you will need to add a using statement for that namespace or explicitly define that namespace with each instance of the window you create.  To change the namespace you will need to manually change the Class attribute in the XAML and the namespace in the xaml.cs file.

image

Set properties of the WPF Window

ShowInTaskBar = false
WindowStartupLocation = CenterOwner

I generally set these properties so that my dialogs behave like the dialogs that are built-in to Visio.  For example, if you open the Options dialog for Visio from the Tools > Options menu you wil notice that a separate item does not appear on the TaskBar.  Setting the WindowStartupLocation to CenterOwner is also dependant on the Owner property of the WPF window.  See the sample code in the section below.

Show the WPF Window

To show the WPF window we need to create an instance of the window and call its ShowDialog method.  Just like the ShowDialog method of a WinForms instance, we can specify the parent window.  As you know with WinForms, to specify the parent window as the Visio application window you had to use the IWin32Window interface which wraps the HWND or Handle property.  In WPF we use the WindowInteropHelper class as shown in the code below.

private void ShowWPFOptions()
{
    OptionsWindow window = new OptionsWindow();

    // use WindowInteropHelper to set the Owner of our WPF window to the Visio application window
    System.Windows.Interop.WindowInteropHelper hwndHelper = new System.Windows.Interop.WindowInteropHelper(window);
    hwndHelper.Owner = new IntPtr(Globals.ThisAddIn.Application.WindowHandle32);

    // show our window
    window.ShowDialog();

    // if OK was selected then do work
    if (window.DialogResult.HasValue && window.DialogResult.Value)
    {
        // do any work based on the success of the DialogResult property
    }
}
 

Sample Code

Click here to download the sample code demonstrating both the WinForms method and the WPF window method in a VSTO 3.0 based add-in project for Visio 2007…

The WBS menu is not available after installing WBS Modeler add-in for Visio

After installing the WBS Modeler add-in for Visio and creating a new diagram based on the WBS Modeler template the WBS Modeler menu should be available on the Visio menu as shown in Figure 1 below.

clip_image002

Figure 1

Issue

In some cases the WBS Modeler menu does not appear when opening or creating WBS Modeler based diagrams.

The most common cause for this behavior is the Visio installation is missing the required .NET Programmability Support component. .NET Programmability Support is required for the WBS Modeler add-in to operate.

Resolution

To install the required components you have two options:

Option 1 – Install the Office PIA redistributable

You will need to download and install the appropriate package based on the version of Microsoft Office and Microsoft Office Visio that you have installed:

Download and install the Office 2007 PIA package

Download and install the Office 2003 PIA package

After you have installed the appropriate package you will need to enable the WBS Modeler add-in. See the ‘Enable the WBS Modeler add-in’ section below.

Option 2 – Update your Visio installation

You can change the installed features for Visio by running setup and adding the .NET Programmability Support feature.

To install .NET Programmability Support you will need to go to Add/Remove Programs and go thru the ‘Change’ process for Visio 2007.

1. From the Start menu select Control Panel

2. In Control Panel choose Add/Remove Programs (Windows XP) or Programs and Features (Windows Vista).

3. Select Microsoft Office Visio in the programs list and click on the Change button.

4. After the setup starts select the Add or Remove Features option and click the Continue button.

5. In the Installation Options list, expand Microsoft Office Visio to find the .NET Programmability Support feature. Choose the ‘Run from my computer’ option for this feature.
clip_image004

6. Click the Continue button to complete the setup changes.

After you have installed this feature you will need to enable the WBS Modeler add-in. See the ‘Enable the WBS Modeler add-in’ section below.

Enable the WBS Modeler add-in

1. Start Visio.

2. Click on the Tools menu and select Trust Center.

3. In the Trust Center dialog click on the Add-Ins tab in the column on the left side.

4. On the Add-Ins tab click on the Go button at the bottom to manage the list of COM Add-ins.

clip_image006

5. In the list of installed COM Add-ins check ‘WBSModeller.Connect’ and click on the OK button.

clip_image008

If you get an error after you click the OK button you may need to reinstall the WBS Modeler add-in. Based on the installation options you may need administrator rights on the machine.

6. Close Visio and restart Visio.

You should now see the WBS Modeler menu when you create or open a WBS Modeler based diagram.

State management for CommandBars

I thought I would share some wrapper classes that I use in just about all of my Visio add-ins for managing the state of my custom menu and toolbar items.  These wrapper classes were a collaborative effort between me and the developers at Visimation, Inc.

Before Visio began using CommandBars as the supported method for customizing the Visio menus and toolbars, state management was much easier.  The UIObject allowed you to scope your custom UI to the Application object or the Document object.  Applying your custom UI to a specific document object prevented your UI from being accessible from other open documents.  Visio handled this for you as you switched between documents.

CommandBars is now the preferred method for customizing the UI in Visio and has been for some time.  CommandBars provide additional functionality but CommandBar customizations cannot be scoped to a specific Document object, they are only available from the Application object.  Because of this, your custom UI changes are available no matter what document is active.

This is fairly easy to workaround and a typical method is to have each function that is executed based on the clicked CommandBarControl to first perform a check to see if that function should execute based on the active document or the current selection.  What you really want is to have your menu and toolbar items automatically enable and disable based on the active document or the content of the current selection, and these wrapper classes provide that for you.

The architecture is simple, wrap each CommandBarButton object that you create and tell the wrapper how it should treat the wrapped CommandBarButton, i.e. AlwaysActive, DocumentActive, or SelectionActive.  The wrapper handles updating the Enabled property of each wrapped CommandBarButton instance based on this setting.  In addition to this setting you can also define a callback method that each wrapper can call to allow you to set the Enabled property with your own custom rules, i.e. the active document must contain a User cell that has the value of “MyCustomDocument”.

UIMgr class

In the attachment you will see the UIMgr class that is used to manage all the objects for the UI customizations.  The Startup and Shutdown methods from the ThisAddIn class make calls to the UIMgr class to add or remove our customizations.

image

I like to remove my UI customizations in the event that a user chooses to unload my add-ins from the list of managed add-in via the Trust Center dialog.  This is typically overlooked and I see a lot of orphaned UI customizations because someone has unloaded an add-in or they have uninstalled an add-in.

VisioCommandBarItem wrapper classes

To use these wrappers all you have to do is create your CommandBarButton or CommandBarPopUp object as you normally would.  Then you create an instance of the corresponding wrapper class, VisioCommandBarButton or VisioCommandBarPopUp and set the ButtonEnabled argument to specify how you want the Enabled state to be managed.

image

Each wrapper instance manages the Enabled state for the wrapped object using some events from the Visio.Application object.  These events trigger an update to the Enabled state if needed.

The AddUI method in the UIMgr class demonstrates how to create a button for each of the ButtonEnabled states.

Getting Started

After you download this source you should be able to compile it and run it.  You will need VS 2008, VSTO 3.0, and Visio 2007.  Visio 2007 will also need to have .NET Programmability Support installed (PIA).

Feel free to add the UIMgr.cs and the VisioCommandBars.cs source files to your own project.  In most cases all you will need to do is change the AddUI method to add your specific CommandBarButtons or PopUps.

Click here to download the sample VSTO based add-in that demonstrates how these wrapper classes are used, along with the full source to the wrapper classes.

Source for Visio Toolbox add-ins released

I am happy to announce that we just released the source for the following Visio add-ins via CodePlex:

Visio add-in for Disk Space Monitoring

Visio add-In for Rack Server Virtualization

Visio add-in for System Center

 

If you are not familiar with these add-ins take a look at each of them as posted on the Visio Toolbox site:

Visio add-in for Disk Space Monitoring

Visio add-In for Rack Server Virtualization

Visio add-in for System Center

 

Each source project not only contains the code for the add-in but it also contains the setup project, making each of these great samples showing the complete picture for developing and deploying custom add-ins for Visio.

Getting Started

Each project site describes the requirements needed for you to open and build these complete solutions so feel free to download them as a means for learning how you can develop and deploy your own custom add-ins for Visio.

Data Linking and Data Graphics

Each of these solutions demonstrate the use of Visio’s new Data Linking and Data Graphics features and how these features can be controlled easily from managed code.

WMI and System Center

Not only do these solutions demonstrate many of the development tasks associated with Visio add-in development, they also demonstrate the use of the WMI and System Center APIs which are used in these solutions to extract data for use in the Visio diagrams.

More Posts Next page »
Page view tracker