Category Archives: wix

Generating GUIDs in the Visual Studio IDE

If you’re programming on Windows you’ll often come across a situation where you have to generate a new GUID. In fact I find myself generating new GUIDs more than ever! I used to use them only for COM/ActiveX and Windows shell integration stuff. Nowadays however I spit out several GUIDs a day, especially for projects involving WiX and SharePoint. In fact, I tend to use them everytime I need a unique identifier. Here’s one I’ve generated especially for this blog post:

{1B87C5E2-0818-4c21-ADFC-741E8D8C1B3D} 😉

The classic tool of choice for generating GUIDs is ofcourse GuidGen.exe, which ships with all the major Microsoft SDK’s and can also be started from the Tools menu of Visual Studio. GuidGen is a small tool which gets the job done, but somehow I have never gotten used to it. I don’t like the fact that I have to leave the Visual Studio IDE to use it and that I cannot control the output format of the GUIDs GuidGen generates. For instance when using WiX you need to use GUIDs without the accolades, which means that a GUID generated by GuidGen needs some editing before it can be used. Yawn…

In the past I was a pretty avid Borland Delphi programmer. One of the nice things of the Delphi IDE, and one that I used very often, was that you could press the keyboard shortcut <ctrl> + <alt> + G and it would place a fresh new GUID at the cursor’s position in the source code editor. I really missed this functionality in Visual Studio.

Fortunately Visual Studio can be easily customized using macro’s and it was easy hacking together a little macro that does the job. I’ve used it for several years now and shared it with many colleagues and friends. Here it is:

Sub Create_GUID()
    Dim sel As TextSelection
    sel = DTE.ActiveDocument.Selection
    sel.Text = System.Guid.NewGuid.ToString("D").ToUpper()
End Sub

Just add this macro to Visual Studio and assign it to the keyboard shortcut of your choice. I use <alt> + G, since the original Delphi shortcut I mentioned above is already in use by Visual Studio by default (it point to the Debug.Registers function).

Ofcourse you can easily modify this macro to suit your personal needs. If you like the way GuidGen bakes ’em, here it is:

Sub Create_GUID
    Dim sel As TextSelection
    sel = DTE.ActiveDocument.Selection
    sel.Text = "{" + System.Guid.NewGuid.ToString("D").ToUpper() + "}"
End Sub

Or maybe you prefer underscores instead of hyphens:

Sub Create_GUID
    Dim sel As TextSelection
    sel = DTE.ActiveDocument.Selection
    sel.Text = Replace(System.Guid.NewGuid.ToString("D").ToUpper(), "-", "_")
End Sub

Or you might be a lower-case fanatic:

Sub Create_GUID
    Dim sel As TextSelection
    sel = DTE.ActiveDocument.Selection
    sel.Text = System.Guid.NewGuid.ToString("D").ToLower()
End Sub

Anyway, I think you get the point…