Skip to content

Instantly share code, notes, and snippets.

@heltonbiker
Last active April 3, 2018 19:09
Show Gist options
  • Save heltonbiker/6b38e4ed3c80d1b57e730a119c81aea8 to your computer and use it in GitHub Desktop.
Save heltonbiker/6b38e4ed3c80d1b57e730a119c81aea8 to your computer and use it in GitHub Desktop.
Simple Digraph class (for use with GraphViz etc.)
using System.Collections.Generic;
using System.IO;
using System.Text;
using Colorspace;
public class Digraph
{
public List<Dependency> Dependencies = new List<Dependency>();
ColorGenerator _colorgen => new ColorGenerator();
public void Save(string filename)
{
var sb = new StringBuilder();
sb.AppendLine("digraph g {");
sb.AppendLine("rankdir = \"LR\"");
foreach (var d in Dependencies)
{
sb.AppendLine($"{d.Source} -> {d.Target} [color=\"{d.Color?? _colorgen.GetRandomHexColor()}\"]".Replace('.', '_'));
}
sb.AppendLine("}");
File.WriteAllText(filename, sb.ToString());
}
}
public class Dependency
{
public string Source { get; internal set; }
public string Target { get; internal set; }
public string Color { get; internal set; }
}
internal class ColorGenerator
{
Random _random => new Random();
internal string GetRandomHexColor()
{
double lightness = 0.4;
double saturation = 0.75;
var color = new ColorRGB(new ColorHSL(_random.NextDouble(), saturation, lightness));
var rgb = new double[] { color.R, color.G, color.B };
string hexcolor = "#" + String.Join("", rgb.Select(c => Convert.ToByte(c * 255).ToString("X2")));
Thread.Sleep(20);
return hexcolor;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment