How to: Display modeling diagrams outside Visual Studio

 

 

In one of Cameron’s blog post we show how to load and save a diagram from within Visual Studio. In this post we’ll show how to use the modeling API to load an Uml diagram outside Visual Studio from a small Windows Form Application and display the diagrams in it.

The modeling API uses the interface IModelingProjectReader to access data in the modeling project.

In order to use this API you need to add the following references to your project:

Microsoft.VisualStudio.ArchitectureTools.Extensibility

Microsoft.VisualStudio.Uml.Interfaces

 

To load a modeling project use the following code:

using Microsoft.VisualStudio.ArchitectureTools.Extensibility;

using Microsoft.VisualStudio.ArchitectureTools.Extensibility.Presentation;

 

this.modelingProject = ModelingProject.LoadReadOnly(openFileDialog.FileName);

 

Once the project is loaded, we need to get the list of diagrams in that project:

foreach(var diagramFile in this.modelingProject.DiagramFileNames)

{

  ShowDiagram(this.modelingProject.LoadDiagram(diagramFile));

}

 

Now we are almost ready to get the diagram, but first we need to add the following reference to our project:

Microsoft.VisualStudio.Modeling.Sdk.10.0

Microsoft.VisualStudio.Modeling.Sdk.Diagrams.10.0

 

LoadDiagram from IModelingProjectReader will return an IDiagram instance, from this instance you need to get the shape element for the DSL diagram. To do this use GetObject:

using Microsoft.VisualStudio.ArchitectureTools.Extensibility.Presentation;

using DslDiagrams = Microsoft.VisualStudio.Modeling.Diagrams;

 

void ShowDiagram (IDiagram diagram)

{

  var dslDiagram = diagram.GetObject<DslDiagrams::Diagram>();

 

Once we have the dslDiagram we can use the CreateMetafile from the DSL API to get the image out of the diagram:

var selectedShapes = new []

  { diagram.GetObject<DslDiagrams::PresentationElement>() }.ToList();

var image = dslDiagram.CreateMetafile(selectedShapes);

 

 

That’s it. I zip the sample at WinFormsViewer.zip, the sample code has a modeling project, and this is how the viewer looks like:

 

 

Hope you find this useful.