Building Dynamic Visio Diagrams with .NET
page 1 of 1
Published: 04 Apr 2006
Unedited - Community Contributed
Abstract
This article will show how to dynamically create and display Visio diagrams on a WebForm. The diagram's symbols change color to represent different status states each time the diagram displays.
by Michael Libby
Feedback
Average Rating: 
Views (Total / Last 10 Days): 26323/ 38

Introduction

Microsoft Office Visio 2003 provides a feature that allows you to save diagrams to web pages.  This article builds upon this ability by introducing a way to dynamically manipulate a diagram when a web page is requested. The following step by step instructions show how this can be done by dynamically changing symbol colors within a Visio diagram.

Create and Save a Visio XML Diagram

1.      Open Visio and create a basic flow diagram. 

Right click on each shape, select format and then fill.  In the Fill Dialog, select a fill color and press OK.  The fill color must be defined in order for our example to work.  The reason for this will be explained later.

2.      Select File, SaveAs, SaveAs Type: XML Drawing (*.vdx), enter the name of your file and press Save.

Create a .NET Runtime Callable Wrapper (RCW) for Visio's COM DLL

1.      Open a Visual Studio .NET 2003 Command Prompt.

2.      Enter and run the following syntax:

Listing 1

tlbimp "VISLIB.dll"/out:"VisioDotNet.dll" /namespace:VisioDotNet/asmversion:VisioVersion

·         VISLIB.dll - The path to Visio's existing COM file.

·         VisioDotNet.dll - The path and file name for the resulting RCW file.

·         VisioDotNet - The RCW namespace.

·         VisioVersion - Visio's version number that can be obtained in Visio's About Dialog.

For example, my command line syntax looks like the following:

Listing 2

tlbimp "C:\Program Files\MicrosoftOffice\Visio11\VISLIB.dll" /out:"C:\visio\VisioDotNet.dll" 
/namespace:VisioDotNet /asmversion:11.3216.5606

Create a Dynamic Visio Web Application

1.      Open Visual Studio .NET 2003 and create a C# web application called DynamicVisio.

2.      Add a .NET reference to the VisioDotNet.dll that was created above.

3.      Create a WebForm called Dynamic.aspx. Add a WebForm Button called Upload (id=btnUpload). Add a DropDownList (id=ddlColor) with its Autopostback property set to true.  Enter the following text value pairs in the ddlColor item collection:  White, 1; Red, 2; Green, 3; Yellow, 5. Add the following HTML control: File Field (id=uploadFile) set to run at the server (runat="server"). Type the following just before the </form> tag: <iframe id="VisioOutput" src="VisioDiagram.htm" width="100%" height="600"></iframe>.

4.      Switch to the form's code view and add the following namespaces:

Listing 3

using System.IO;
using System.Xml;
using System.Text;

5.      Add the following properties to the Dynamic class which will store the Visio XML document and Visio File Name in Session where they will be accessible for future requests:

Listing 4

private XmlDocument VisioXMLDoc
{
  get
  {
    if((XmlDocument)Session["VisioXMLDoc"] == null)
       Session["VisioXMLDoc"= newXmlDocument();
    return(XmlDocument)Session["VisioXMLDoc"];
  }
  set
  {
    Session["VisioXMLDoc"= value;
  }
}
 
private string VisioFileNm
{
  get
  {
    returnSession["VisioFileNm"].ToString();
  }
  set
  {
    Session["VisioFileNm"= value;
  }
}

6.      Double-click the upload button and enter the following code in the Click event handler:

Listing 5

private void btnUpload_Click(object sender,System.EventArgs e)
{
  VisioFileNm = Path.GetTempPath() +uploadFile.Value.Substring
    (uploadFile.Value.LastIndexOf(@
   "\")+1);uploadFile.PostedFile.SaveAs(VisioFileNm);
  XmlTextReader xtr = newXmlTextReader(VisioFileNm); xtr.WhitespaceHandling =
    WhitespaceHandling.All;VisioXMLDoc.Load(xtr); xtr.Close();
  ddlColor.Enabled = true;RenderVisioDiagram(nullnull);
}

The above code uploads and saves a Visio diagram file in your server's temporary file directory where write permissions are not required.  Next, the Visio file's XML is read and stored in Application Cache for later use.  The ddlColor control is then enabled and the diagram displayed.

7.      Add the following code to display the Visio Diagram:

Listing 6

private void RenderVisioDiagram(object sender,System.EventArgs e)
{
  Application.Lock();
  XmlNodeList xShapes =VisioXMLDoc.GetElementsByTagName("Shape");
  foreach (XmlNode xnod in xShapes)
    ChangeShapeAttributes(xnod);
  Application.UnLock();
 
  XmlTextWriter xtw = newXmlTextWriter(VisioFileNm,
    System.Text.UTF8Encoding.UTF8);
  VisioXMLDoc.WriteTo(xtw);
  xtw.Close();
 
  VisioDotNet.Application app = newVisioDotNet.ApplicationClass();
  app.Documents.Open(VisioFileNm);
 app.Addons.get_ItemU("SaveAsWeb").Run(
    "/quiet=True /openbrowser=False /target="+ Request.PhysicalApplicationPath
    + "VisioDiagram");
  app.Quit();
}

The above code locks application cache so that only one web request can modify the Visio XML document. Each shape is then extracted from the XML document and its attributes are changed.

Once shape attributes are changed, the document is saved to a file where it can be opened by Visio and then resaved to an HTML Web page. An IFrame on the WebForm will load and display this page.

·         Note: For complete documentation on calling Visio's Run method using the "SaveAsWeb" add-on see Running Visio Save As From the CommandLine.

8.      Add the following code to change each shape's fill color:

Listing 7

public void ChangeShapeAttributes(XmlNode xnod)
{
  XmlNamedNodeMap attrs = xnod.Attributes;
  string id =attrs.GetNamedItem("ID").Value.ToString();
 
  XmlNodeList xchilds = xnod.ChildNodes;
  foreach (XmlNode node in xnod.ChildNodes)
  {
    if (node.Name == "Fill")
    {
      foreach (XmlNode fillnode innode.ChildNodes)
      {
        if (fillnode.Name =="FillForegnd")
        {
          fillnode.InnerText =ddlColor.SelectedValue.ToString();
          break;
        }
      }
    }
  }
}

The above code shows an example of how to get each shape's id and iterate through a shape's child nodes to change attributes.

·         Note: If the shape's fill was not defined by the user when the diagram was designed, then the fill node will not be found in the XML and will need to be created.  This same behavior is true of other Visio attributes. For complete documentation on Visio's XML see XML for Visio Schema.

9.      Open the web.config file and add the following line after <system.web>, allowing the web application to run Visio:

Listing 8

<identity impersonate="true" />

10.   Run the Web application. Press the Browse button and find a Visio .vdx file.  Press the Upload button to upload the file to the web server. Once the diagram is loaded, you can select colors from the dropdown and see shapes in the diagram change colors.  Open other browser windows to see identical diagrams display. If you had any difficulties with the above steps, please download and try the sample code.

Figure 1

References

·         Running Visio Save As From the CommandLine

·         XML for Visio Schema

·         History of Visio

·         Host an Interactive Visio Drawing Surface in .NET Custom Clients

Downloads

[Download Sample]

Summary

Visio allows you to create visual representations of complex business problems and model processes.  Saving Visio diagrams as web pages provides access to multitudes of users. However, if these diagrams are static they can only be used as a reference.  Add the capability of dynamically changing a diagrams symbol's status and a Visio diagram becomes a point of reference that can also provide status and isolate problems.

Extrapolate from this article and you will begin to envision dynamic workflow status, the ability to design diagrams on a WebForm with drag and drop functionality and other innovative solutions limited only by one's imagination.



User Comments

Title: Editing Property Values   
Name: Sampath Kumar
Date: 2008-07-31 7:31:50 AM
Comment:
It is a nice. But I need a thing that i want to edit the property value from the application.(Not Color) I want to edit the Cost,Resources that things from the application please help me i try to do the thing but i cant able to do for single shape that i have selected.
Title: Different chart for different user   
Name: Arshdeep
Date: 2008-03-14 7:09:15 AM
Comment:
The method u have discussed makes use of single visio file to be uploaded but wat if we want to display such chart "by default" on webpage and that too depending upon user i.e.depending upon user hitting the website the different organisaton chart should be displayed according to his/her position in organistaion??
Title: The left frame does not show up in FireFox   
Name: Choreson
Date: 2007-07-03 3:02:57 PM
Comment:
This is cool, but it does not work well in FireFox. The left frame simply does not show up.

Is there a workaround for FireFox?
Title: Error!   
Name: Raphael Firmino
Date: 2006-11-30 12:20:58 PM
Comment:
Hi! Very good explanation!
I'm with a little trouble... When the variable VisioDotNet.Application app is created, i'm getting an error relationed to the factory of COM classes with the CLSID component...
I'm thinking that the error is cause i don't have Visio installed in my machine... But i've got the VisioDotNet.dll from the sample... It's that the problem?
Sorry by the bad english!
Thanks!
Title: Permissions problem?   
Name: Steve
Date: 2006-11-28 4:44:39 AM
Comment:
We've got the code to work on our Windows 2003 server but only when we log on at the server console and impersonate the same user in .net

The .net user account has been granted full admin permissions to the server but we can't get the code to work as that user. Either Visio opens on the server (visible in task manager) and just hangs there or we get an application is busy error.

Any ideas why we have a permissions problem when the .net account has more permissions than the user account we impersonate!? We read various things on application pools and com+ application permissions but not got much further.

Thanks.
Title: Modify the graph visio.   
Name: Javier
Date: 2006-10-04 3:00:33 AM
Comment:
Hi. It is possible to modify the graph visio from the application ASP .NET and save changes ?

Thanks.
Title: Works Great   
Name: Jon Nickles
Date: 2006-04-08 9:05:23 PM
Comment:
I've been looking for a solution like this for a while to show work flow status. Thank you, exactly what I needed and your article worked flawlessly.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2019 ASPAlliance.com  |  Page Processed at 2019-07-17 4:41:43 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search