Unmanaged Visio

15 May 2010

Persisting Visio shapes

kitten

After this post in microsoft.public.visio.developers newsgroup I was asked a few times, how to save Visio shapes in external source exactly, so here is the code to store master/shape in a stream and then drop it back to the document:

Download sample project (C++)

Download sample project (C#)

To save Visio shapes in some external system (persist them) you can:

- Query master or shape you want to persist for IDataObject interface.
- Using this interface, obtain data blob in "Visio 11 Shapes" clipboard format (or maybe actually anything that contains “Shapes” word to be compatible with further Visio versions, please refer to the code).

Now this blob can be stored any way you want (database/memory/file/whatever). The sample code just saves it to a string variable in base64 encoding. To drop shapes back to the drawing, you can use "Drop" functions of Visio document/page. It turned out that these functions are happy enough with plain IDataObject interface passed in. So, to drop the stored master or shape back to the drawing:

- Create you own object that implements IDataObject interface.
- Load this object with your data
- Pass this object in one of those "Drop" functions (e.g. Page.Drop)

For managed code, all this stuff can be done using “DataObject” framework class that is capable of handling all nasty details for you behind the screen. Here is the basic idea:
string _clipFormat;
string _shapeData;

void SaveShape(IVShape shape)
{
   DataObject dataObj = new DataObject(shape);
   foreach (string clipFormat in dataObj.GetFormats(false))
   {
       if (clipFormat.Contains("Shapes"))
       {
           MemoryStream stream = (MemoryStream)dataObj.GetData(clipFormat);
           _clipFormat = clipFormat;
           _shapeData = Convert.ToBase64String(stream.ToArray());
       }
   }
}

void DropSavedShape(IVPage page)
{
   MemoryStream stream = new MemoryStream(Convert.FromBase64String(_shapeData));
   DataObject obj = new DataObject(_clipFormat, stream);
   page.Drop(obj, 0, 0);
}

Hope this is helpful.

Labels: , , , ,

1 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home