Sunday, August 26, 2012

The Mess That Is Programming Visio

So I am writing a program that among other things will draw the diagram of a network.  Unfortunately the .COM interface to Visio is a disaster, at least from the OO model perspective.  First, here's how you create the Visio document.  This is C#, and I am skipping all the using statements you might need as well some variable declarations.

// create the application instance

 Visio.Application va = new Visio.Application();
            va.Documents.Add(@"");

//grab the document in the application
// since you can't just write a file in the .vsd format



Visio.Documents vdocs = va.Documents;

// now open it - of course casting arcane arguments as short
// makes perfect sense
// and no, I don't know what that does
      Visio.Document vc = vdocs.OpenEx(@"Basic_U.vss", (short)Visio.VisOpenSaveArgs.visOpenDocked);

// it gets a little better here, this is pretty straightforward
            
Visio.Document vd = va.ActiveDocument;
Visio.Page vp = vd.Pages.Add();

// but now we need to get the master shapes collection
Visio.Masters vMasters = vc.Masters;  

// and select the shapes we are using from the collection
// I had to open the collection in the debugger to figure out
// which ones I needed - there wasn't a way to just get a list
// oh and another annoyance - the C# convention is to have 
// members start with upper case.  For Visio, some do and some don't
           Visio.Master RectangleMaster = vc.Masters.get_ItemU(@"Rounded rectangle");
Visio.Master ConnectionMaster = vc.Masters.get_ItemU(@"Dynamic connector");

 Visio.Shape MyselfAsShape = null;
// now let's drop a shape on the page and set some parameters
// here's where the fun starts

 MyselfAsShape = vp.Drop(RectangleMaster, xaxis, yaxis);

// set the width - you can't just access a width property 
// on the shape                       MyselfAsShape.get_CellsSRC((short)Visio.VisSectionIndices.visSectionObject, 
                           (short)Visio.VisRowIndices.visRowXFormOut, 
                           (short)Visio.VisCellIndices.visXFormWidth).FormulaU = "1.0 in";

// same for height                      MyselfAsShape.get_CellsSRC((short)Visio.VisSectionIndices.visSectionObject, 
                           (short)Visio.VisRowIndices.visRowXFormOut, 
                           (short)Visio.VisCellIndices.visXFormHeight).FormulaU = "1.5 in";



Other operations on shapes and connectors are similarly arcane.  I won't show the code but to connect 2 shapes you first get the shapes, then you figure out where the connection points are, then you use code similar to the above to connect them. You can't just do something like:

shape1.Connect(shape2)