Skip to content

Instantly share code, notes, and snippets.

@abdullin
Created October 6, 2011 18:27
Show Gist options
  • Save abdullin/1268198 to your computer and use it in GitHub Desktop.
Save abdullin/1268198 to your computer and use it in GitHub Desktop.
Wiring Lokad-CodeDSL in a MightyMoose style.
// This is a hacky sample (that works for me) of alternative way to use Lokad-codeDSL
// or any similar way of generating message contracts on-the-fly. Original approach was
// with using T4 template, that would rebuild cs files from DSL representation, whenever
// we hit Ctrl-S.
// This approach works almost exactly like this (Ctrl-S to rebuild), but does not require VS
// to run or does not require unloading VS to change the underlying generator code.
// in fact it is extremely boring. Lolcats from MightyMoose could be used to improve the situation, though.
// any takers? :)
// Original article with T4 approach is here:
// http://abdullin.com/journal/2010/10/12/teach-visual-studio-your-own-language-easy.html
// Essentially we just start our program in background and let it monitor files, rebuilding them
// on a save.
class Program
{
static ConcurrentDictionary<string, string> _states = new ConcurrentDictionary<string, string>();
static void Main(string[] args)
{
var info = new DirectoryInfo("..\\..\\..\\..\\Source\\Hub.Contracts");
var files = info.GetFiles("*.tt");
foreach (var fileInfo in files)
{
var text = File.ReadAllText(fileInfo.FullName);
Changed(fileInfo.FullName, text);
Rebuild(text, fileInfo.FullName);
}
var notifier = new FileSystemWatcher(info.FullName, "*.tt");
notifier.Changed += NotifierOnChanged;
notifier.EnableRaisingEvents = true;
Console.ReadLine();
}
static void NotifierOnChanged(object sender, FileSystemEventArgs args)
{
if (!File.Exists(args.FullPath)) return;
try
{
var text = File.ReadAllText(args.FullPath);
if (!Changed(args.FullPath, text))
return;
Console.WriteLine("{1}-{0}", args.Name, args.ChangeType);
Rebuild(text, args.FullPath);
SystemSounds.Beep.Play();
}
catch (IOException) {}
catch (Exception ex)
{
Console.WriteLine(ex);
SystemSounds.Exclamation.Play();
}
}
static bool Changed(string path, string value)
{
var changed = false;
_states.AddOrUpdate(path, key =>
{
changed = true;
return value;
}, (s, s1) =>
{
changed = s1 != value;
return value;
});
return changed;
}
static void Rebuild(string text, string fullPath)
{
var generator = new TemplatedGenerator();
var contents = GeneratorUtil.Build(text, generator);
File.WriteAllText(Path.ChangeExtension(fullPath, "cs"), contents);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment