I have this code that creates a new Visio document and adds a rectangle. It works, but I don't like having to open another document to get the Masters collection from it. The issue is the new document has an empty Masters shape collection. I couldn't find a method in the Document class to add shapes to the Masters collection and all the examples I could find for adding shapes assumed you had an existing document. Is there a better way to do what I want?
// create the new application
Visio.Application va = new Microsoft.Office.Interop.Visio.Application();
// add a document
va.Documents.Add(@"");
// Visio.Documents vdocs = va.Documents;
// we need this document to get its Masters shapes collection
// since our new document has none
Visio.Document vu = vdocs.OpenEx(@"C:\Program Files (x86)\Microsoft Office\Office12\1033\Basic_U.vss", (short)Microsoft.Office.Interop.Visio.VisOpenSaveArgs.visOpenDocked);
// set the working document to our new document
Visio.Document vd = va.ActiveDocument;
// set the working page to the active page
Microsoft.Office.Interop.Visio.Page vp = va.ActivePage;
// if we try this from the Masters collection from our new document
// we get a run time since our masters collection is empty
Visio.Master vm = vu.Masters.get_ItemU(@"Rectangle");
Visio.Shape visioRectShape = vp.Drop(vm, 4.25, 5.5);
visioRectShape.Text = @"Rectangle text.";
You're right - the Masters collection is ReadOnly. Documents normally start off with an empty masters collection. The collection gets populated by dropping masters from a stencil document.
If you want to create a new document with a pre-populated Masters collection then you could create your own template (.vst) and then base your new document on that. For example:
Normally you would package your stencils and templates together and then always create shapes by dropping a master from the respective stencil document (.vss).
Masters also have a MatchByName property. Dropping a master when this property is set to true, Visio first checks that a master of the same exists in the drawing document masters collection. If it does an instance of that master will be dropped. If not a new master will be added based on the original stencil. Have a look at these two links for more information:
If you really want to create your own masters in code, you can draw / drop your own shapes on the page and then use the Document.Drop method to add it to the masters collection.
Also if you want to use a master by name then you'll need to loop through the masters collection to check that it exists before you use it.
I think you will find this on-line book extremely useful : http://msdn.microsoft.com/en-us/library/aa245244(v=office.10).aspx