Property Macro

Frequently, I find myself needing to add a property to an existing entity. Manually typing the property definition is tedious. So, I created a macro to aid this process. Once we move to Visual Studio 2010, this won’t be needed, but until then, it should be pretty handy. (VS2010 will add a new shortcut for creating a simple property with just one line of code.)

To implement the macro in your IDE, follow these steps.

First, open the Macro explorer by selecting View/Other Windows/Macro Explorer, or pressing Alt-F8.

Right click the MyMacros node, and select New module…

Enter a name such as “MyMacroModule”.

Next, right click your newly created module and select New Macro.
Enter a name, such as “NewProperty” and click Add.

The macro IDE will open and take you to the module editing window. Delete the existing template code and paste the macro code below:

[EDIT July 8, 2008: Since I originally published this macro, I have completely refactored it, incorporated a change suggested in a comment, fixed a couple of minor issues (problems inserting a macro near the end of a document, and the editor window not being active after the macro runs). So below is the latest and greatest version of the macro code.]

Option Strict On
Option Explicit On
Imports EnvDTE
Imports Microsoft.VisualBasic

Public Module DavidMacros

    Sub NewProperty()
        Dim strName As String
        strName = InputBox("Property Name:", "Add Property")
        If (strName = "") Then
            Exit Sub
        End If

        Dim strType As String
        strType = InputBox("Data Type:", "Add Property")
        If (strType = "") Then
            Exit Sub
        End If

        strName = strName.Substring(0, 1).ToUpper & strName.Substring(1, strName.Length - 1)
        Dim strLocal As String = "_" & strName.Substring(0, 1).ToLower & strName.Substring(1, strName.Length - 1)
        strType = StrConv(strType, VbStrConv.ProperCase)

        Dim textSel As TextSelection = DirectCast(DTE.ActiveDocument.Selection, TextSelection)
        textSel.StartOfLine()
        ' Insert the property
        textSel.Insert(String.Format("{4}Private {0} As {1}{2}{4}Public Property {3}() As {1}{2}{4}{4}Get{2}{4}{4}{4}Return {0}{2}{4}{4}End Get{2}{4}{4}Set(ByVal value As {1}){2}{4}{4}{4}{0} = value{2}{4}{4}End Set{2}{4}End Property{2}{2}" _
                              , strLocal, strType, ControlChars.NewLine, strName, ControlChars.Tab))
        ' Get the cursor to show up again
        DTE.ActiveDocument.Activate()

    End Sub
End Module

After you paste the code, change the Module name to match your module name. Then, on the file menu, select Close and Return. You will return to your VS2008 IDE and on the Macro Explorer, you should see your new macro.

To test it out, go to an entity class and try adding a property. Get into the editor and make a blank line or two. From macro explorer, right click your NewProperty macro and select Run. Enter a property name and hit Enter. Then enter a data type and hit Enter. Your private variable, and get/set statements will magically appear in your document.

In the olden times, in VB6 and earlier, we all developed a habit of putting our private variables at the top of our class, all clustered together and then having our get/set statements in another location. This is entirely uneccessary and more than a little bit of a pain when you wind up needing to edit them — all that jumping around. So, the macro puts everything all together, in one convenient location.

To make the macro more convenient, you may assign a keyboard shortcut to it. I selected Control-P for myself, but you may select some other key combination.

Select Tools/Customize…

Then click the Keyboard… button at the bottom. On the options dialog, in the box labeled “Show commands containing:”, type macro. Then scroll the list to find your NewProperty macro. Go to the “Press shortcut keys:” text box (set focus to this) and then type your shortcut key combination. You can set the “Use new shortcut in:” dropdown to Text Editor. Then click the Assign button and OK.

If all went as it should, you now have a quick way to create properties.

Share
Line Break

Author: David (81 Articles)

David is an IT professional with over 29 years of experience (he started his career as a teenager). He has programmed in more languages and on more types of computers (and similar devices) than he can remember, including TRS-80 Model I Level 2, Commodore Vic-20, C-64 and C-128, Industrial Process Controllers, CP/M machines, and Intel 80x86+ architectures. He currently uses Microsoft .NET Framework tools and SQL Server. When he's not geeking out, he studies the Martial Art, Aikido; engages in community volunteer work; writes fiction (as well as non-fiction blogs); and does home rennovation work and is an avid and aspiring photographer. He lives in Charlotte NC, USA.

3 thoughts on “Property Macro

  1. Good stuff. I used to have a macro to do this but I lost it when I reformatted, didn’t want to recreate the wheel and found this. Thanks for sharing (will be useful until VS2010 comes out). The only change I made was having it upper case the first letter of the property name (e.g. so the private variable _firstName would have a property called FirstName). I used the following function though I believe there’s a way to use StrConv in VB to convert to property case… anyway:

    Public Function UCaseFirstLetter(ByVal str As String) As String
    Return String.Format(“{0}{1}”, UCase(Left(str, 1)), Mid(str, 2))
    End Function

    I then just modified the propety line in your macro changing strName to UCaseFirstLetter(strName)

    Also, it’s funny, I use VS2008 everyday and I’ve never assigned hotkeys to macro’s and for the life of me, I don’t know why. Thanks for giving the steps to do this. Huge time saver.

  2. On July 8th, I completely refactored the code. The original code was a modified version of a macro I recorded, and was not very robust. The new version is much better and resolves some issues with the original.

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>