Try/Catch and Try/Finally macros for VB.NET

I recently started playing around with macros in Visual Studio .NET 2003 and wrote up two I find very helpful: Wrap Try/Catch and Wrap Try/Finally. Basically, they take the selected text and wrap it in a try/catch block or a try/finally block.

This version supports empty selections (to create a new block) and both full-line and partial selections. It places the insertion point inside the try block for an empty selection and inside the catch block for a text selection.


Imports EnvDTE
Imports System.Diagnostics

Public Module CodeModifiers

  Sub WrapTryCatch()
    WrapTrySomething("Catch ex As Exception")
  End Sub

  Sub WrapTryFinally()
  End Sub

  Private Sub WrapTrySomething(ByVal middleText As String)

    If DTE.ActiveDocument Is Nothing Then
    End If

    Dim selection As TextSelection
    Dim startPoint As EditPoint
    Dim endPoint As EditPoint
    Dim insertPoint As EditPoint
    Dim empty As Boolean

    selection = DTE.ActiveDocument.Selection()
    startPoint = selection.TopPoint.CreateEditPoint()
    endPoint = selection.BottomPoint.CreateEditPoint()

    empty = startPoint.EqualTo(endPoint)

    DTE.UndoContext.Open("Wrap Try")

      Dim insertEndingCrLf As Boolean
      If endPoint.AtEndOfLine Then
        insertEndingCrLf = endPoint.AtStartOfLine
        insertEndingCrLf = True
      End If

      If Not endPoint.AtStartOfLine OrElse _
        endPoint.EqualTo(startPoint) Then
      End If

      endPoint.Insert(middleText + ControlChars.CrLf)

      If Not empty Then
        insertPoint = endPoint.CreateEditPoint()
      End If

      endPoint.Insert(ControlChars.CrLf + "End Try")

      If insertEndingCrLf Then
      End If

      ' insert try
      If Not AtStartOfLineIgnoringWhitepsace(startPoint) Then
      End If
      startPoint.Insert("Try" + _

      If empty Then
        insertPoint = startPoint.CreateEditPoint()
      End If


    End Try
  End Sub

  Private Function AtStartOfLineIgnoringWhitepsace( _
                    ByVal point As EditPoint) As Boolean

    If point.AtStartOfLine Then
      Return True
    End If

    Dim p As EditPoint = point.CreateEditPoint()

      If Not Char.IsWhiteSpace(p.GetText(1), 0) Then
        Return False
      End If

      If p.AtStartOfLine Then
        Return True
      End If

  End Function

End Module

This macro will only work for VB.NET. It can be translated to work with C# code or you can use the wonderful resharper plugin which unfortunately isn’t available for VB.NET.

This entry was posted in Uncategorized by Sam. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>