VB.NET Property code generation macro in VS.NET.
A time ago, I read Duncan's post about macros in Visual Studio.NET. I altered a bit his macro to suit my needs. The macro lets you rapidly generate code for the properties of a class. For example when you type the following code for a class (Remark: The generated code has xml comments, but the formatting on this page does not show them.):
Public Class Customer
Private _name As String
Private _telephone As String
End Class
Then you select the internal declarations:
_name and _telephone, and run the macro.
The result is:
Public Class Customer
Private _name As String
Private _telephone As String
'
'This is the Name property.
'
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal Value As String)
_name = Value
End Set
End Property
'
'This is the Telephone property.
'
Public Property Telephone() As String
Get
Return _telephone
End Get
Set(ByVal Value As String)
_telephone = Value
End Set
End Property
End Class
The complete code for the macro is:
Imports EnvDTE
Imports System.Diagnostics
Public Module ClassMacros
Sub ConvertProperties()
DTE.UndoContext.Open("ConvertProperties")
Try
Dim txt As TextSelection
txt = DTE.ActiveDocument.Selection
Dim line, originalCode As String
originalCode = txt.Text
Dim lines() As String
lines = Split(originalCode, vbLf)
Dim variableName, publicName, dataType, propertyProcedure As String
Dim r As System.Text.RegularExpressions.Regex
r = New System.Text.RegularExpressions.Regex( _
"(Dim|Private)\s*(?\S*)\s*As\s*(? \S*)", _
System.Text.RegularExpressions.RegexOptions.IgnoreCase _
Or System.Text.RegularExpressions.RegexOptions.IgnoreCase.ExplicitCapture)
For Each line In lines
line = line.Trim
If Not line = "" Then
Dim mtch As System.Text.RegularExpressions.Match
mtch = r.Match(line)
If mtch.Success Then
variableName = mtch.Groups("varname").Value.Trim
dataType = mtch.Groups("typename").Value.Trim
publicName = variableName.Substring(1, 1).ToUpper & variableName.Substring(2)
propertyProcedure = _
String.Format( _
"{0}'{0}" _ {0}" _
& "'This is the {1} property.{0}" _
& "'
& "Public Property {1} As {2}{0}" _
& " Get{0}" _
& " Return {3}{0}" _
& " End Get{0}" _
& " Set(ByVal Value As {2}){0}" _
& " {3} = Value{0}" _
& " End Set{0}" _
& "End Property", vbCrLf, publicName, _
dataType, variableName)
txt.Insert(vbCrLf & propertyProcedure, _
vsInsertFlags.vsInsertFlagsInsertAtEnd)
End If
End If
Next
txt.SmartFormat()
Catch ex As System.Exception
MsgBox("There was an error while constructing Property code: " & _
ex.ToString & ".", MsgBoxStyle.Critical, "ConvertProperties")
End Try
DTE.UndoContext.Close()
End Sub
End Module
Thanks again to Duncan for the original code!