Thursday, November 05, 2009

Long Live the Guid!

Guid generation came up earlier today and it struck me, as someone who loves automation, Guid generation is still a very manual process for me.

It seems like forever that I have used the Visual Studio Tools | Create GUID tool to generate new Guid’s, using the Registry Format option, and then removing the squiggy braces from the end product.

Today I learned from Mr. Anderson that my Guid string can keep the squiggy braces:

var g = new Guid("{10246A29-8E88-46DC-925A-6F4BCB31EB56}");

This code for Guid generation is just as valid as:

var g = new Guid("10246A29-8E88-46DC-925A-6F4BCB31EB56");

I would have sworn there was a time not so long ago that the squiggy braces would have caused an issue.

I also learned that ReSharper has a built-in live template for generating GUID’s called ‘nguid’, much like a snippet. However, it doesn’t generate the Guid with quotes around it – which is my 99.999% usage scenario when creating Guid’s. Outside of COM IDL work, I haven’t had to generate a Guid that wasn’t a string in as long as I can remember. Fortunately, ReSharper gives me a nice little UI editor for modifying their templates (snippets) and now ‘ngen’ works the way I wanted it to by inserting the text:

"10246A29-8E88-46DC-925A-6F4BCB31EB56".

Of course, this got me to thinking surely Visual Studio can do this? Of course it can. Here is the macro I created to do the same thing, which I then promptly mapped to the keyboard shortcut CTRL-N,CTRL-G.

Public Module CodeGeneration

Sub CreateGuid()
Dim ts As TextSelection = DTE.ActiveDocument.Selection
ts.Insert("""" + Guid.NewGuid().ToString() + """")

End Sub

End Module

So now I can burn through Guids with wild abandon and so can you!