Posterous theme by Cory Watilo

Server Block Formatting in Visual Studio

This is one of those more-for-me-than-you posts. If you're working with ASP.NET MVC (or god help you ASP Classic) you'll likely be annoyed by the way server blocks are formatted in Visual Studio. In particular closing curly braces seem to throw the formatting engine a real curve-ball. For example, you type something like this:
But after slapping return, you ultimately get this lovely thing:
Thanks Visual Studio! So how do we fix this. Well, you'd like it if hitting Ctrl+K+D took care of this for you, but apparently that ignores server blocks. Next you'll hunt and peck your way through the mounds of Visual Studio options in Tools > Options...but that search will ultimately prove fruitless. Finally, you'll turn to the humble macro...I know macro can be a dirty word but in this case it's really your only option. Here's how this goes: 1. Mouse over to Tools > Macros > Macro IDE 2. Notice that Visual Studio macros are in Visual Basic...really? I know...but go with it. 3. Right-click 'My Macros' 4. Choose 'Add New Item' 5. Choose 'Module' in the dialog 6. Enter the following method in the newly created Module:
Public Module FormatCurrentFile

    Sub FixServerBlocks()
        Dim selection As TextSelection = DTE.ActiveDocument.Selection
        Dim fixed As String = ""
        Dim regex As String = "\"
        While selection.FindPattern(regex, vsFindOptions.vsFindOptionsRegularExpression)
            selection.ReplacePattern(regex, fixed, vsFindOptions.vsFindOptionsRegularExpression)
        End While
    End Sub

End Module
Now you can go through Tools > Options > Keyboard and map a key command to this macro...I chose Ctrl+K+C for example since it's close to the other magic formatting keys that you'll want to run right before the macro. There you have it. Thanks to some help from StackOverflow.com for this solution: http://stackoverflow.com/questions/720042