Thursday, July 21, 2011

graph using xml with GraphViz tool

Currently I am working on project that generate graph for xml file. I have found few tools that does the same but I have expended to another level.

I am using GraphViz to generate the graph. GrahpViz is very awesome tool. You need to understand GraphViz dot statement. Please have a look that site.

I have written one WinForm tool that translates dot statment to graph and another which is a console application that convert xml file into graph image.

I share the code as well.

I have written a small utility that generates graph, the idea is how to execute the dot statement. You can create Windows form application, where user can write dot statment and it will show the image based on that.

Here is the code that does for you:
public void CreateImage(string graphVizDotExePath, string dotStatement, string imagePath)
var startInfo
= new ProcessStartInfo(graphVizDotExePath)
FileName = graphVizDotExePath,
Arguments = "-Tpng -o" + imagePath,
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
CreateNoWindow = true

graphVizProcess = Process.Start(startInfo);

string output = graphVizProcess.StandardOutput.ReadToEnd();

here is the main method:
static void Main(string[] args)
GrapVizWrapper dotCmd = new GrapVizWrapper();
Console.WriteLine("Write your dot statement here, when you finish press q:");
StringBuilder dotStatement = new StringBuilder();
string line = string.Empty;
line = Console.ReadLine();
if (!line.Equals("q"))
} while (!line.Equals("q"));

Console.WriteLine("Creating image please wait...");
dotCmd.CreateImage(@"C:\Program Files (x86)\Graphviz 2.28\bin\dot.exe", dotStatement.ToString(), @"C:\Projects\masood.png");
Console.WriteLine("image created.");

and I am calling above method from Main method of program class with:
path to dot.exe file (when you install GraphViz, you will see in Program File folder)
dot statement like below:
digraph {
"class a" -> "class b"

and path and file where you want this exe to create the image. You can have a look the generated image below:

I have tried another statment, that is:
digraph {
"compile" -> "clean"
"build" -> "compile"
"build" -> "clean"

and following is the output:

There is whole lot of different types of statements to generate the graph or diagram.
Visit to the different types of dot statements. To view the statement, you have to click on the picture and supply the same dot statement to your program to see the output.

Using this technique I have created a tool that generates graph of all dependencies and calls for NAnt build file.

No comments:

Post a Comment