Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / Visual Basic
Article

Automating the code writing process using macros

Rate me:
Please Sign up or sign in to vote.
4.63/5 (33 votes)
5 Jul 2007CPOL11 min read 177.5K   2.5K   162   35
This article describes the documentator macros for making code writing with Visual Studio 2003 a lot faster and easier.

Changes

See history for a full changelog. The documentation found in the zip contains an updated documentation in addition to the changelog of the macros.

Introduction

When writing code and documentation for source files, there is much manual work to complete the task. Often you follow a specific code standard and some code you write quite often with small changes. I have developed a set of macros for easing my daily work and thus making me more efficient as a developer. These macros employ our company's code standard, that hopefully are not so far from yours, and they can be fine-tuned to match your standards.

The macros focus on inline XML documentation, region blocks, automation and refactoring. They work with Visual Studio 2003 and primarily with C#, but some macros also support VB.NET.

Installation

Download the supplied files and follow the instructions given below:

For VS 2005

  1. Open the Macro explorer (Alt+F8 or View -> Other windows -> Macro Explorer)
  2. Rightclick "Macros" in the macro explorer and select "Load Macro Project"
  3. Select the "Meridium.vsmacros" and click "Add"
  4. Run the Macro Meridium.Documentator.FixKeyMapping to install the shortcuts
  5. [Optional] If you have installed the Resharper add-in, run the Meridium.Documentator.FixKeyMappingsAfterResharperInstallation macro
  6. Ready to go

For VS 2003

  1. Create a new keyboard mapping scheme if you are using the Default settings (Tools -> Options -> Environment-> Keyboard-> Save as)
  2. Load the macro project "Meridium.vsmacros" in Visual Studio (Tools -> Macros -> Load Macro project...)
  3. Open the Macro explorer (Alt+F8 or Tools -> Macros -> Macro Explorer)
  4. Run the Macro Meridium.Documentator.FixKeyMapping to install the shortcuts
  5. Ready to go

Using the macros

The full explanation of the macros exists in the manual, but I will give some descriptions for the main features.

For instance, if you have written a method that looks like this:

C#
public int MyMethod(string name, int maxNo, Font font) 
{
    //my code
}

and then invoke the Document and regionize macro (Ctrl+d), you'll end up as follows:

C#
#region public int MyMethod(string name, int maxNo, Font font)
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="maxNo"></param>
/// <param name="font"></param>
/// <returns></returns>
public int MyMethod(string name, int maxNo, Font font) 
{
    //my code
}
#endregion

The cursor is then placed at the first XML doc tag (<summary>) and you are ready to start documenting. If you have also activated the EnableTabMapping, you can use Tab and Shift+Tab to move between the different tags in the XML doc section.

It also supports updates, so if you add a parameter or change the order of the parameters and then activate the macro again, the documentation and region will be updated.

Another major macro is the PasteTemplate macro that supports automation and refactoring by templates. For now, the templates are hard coded into the macros, but you can easily modify them to suit your own needs.

For example, if you want to create a try catch clause, enter the following text:

C#
tryc

and activate the PasteTemplate macro (Ctrl+J), you'll end up as follows:

C#
try 
{
} 
catch(Exception ex) 
{
}

More automation functions exists. Try fori, trycm, trycf, tryf, gp, sp and gsp.

A more complex automation is supported when creating events. If you define the following event:

C#
public event EventHandler MyEvent;

and activate the PasteTemplate macro, you'll end up with the following code:

C#
#region public event EventHandler MyEvent
/// <summary>
/// This event is fired when
/// </summary>
public event EventHandler MyEvent;
#endregion
#region protected virtual void OnMyEvent(EventArgs e)
/// <summary>
/// Notifies the listeners of the MyEvent event
/// </summary>
/// <param name="e">The argument to send to the
    listeners</param>
protected virtual void OnMyEvent(EventArgs e) 
{
    if(MyEvent != null) 
    {
        MyEvent(this,e);
    }
}
#endregion

This saves a lot of time.

The same macro also adds refactoring capabilities. For instance, if you want to convert a field to a property,

C#
public string Name;

place the cursor at the end of the line and activate the PasteTemplate macro, you'll end up as follows:

C#
public string Name;
    get { return _name; }
    set { _name = value; }
}
private string _name;

Then add the Document and regionize macro to that, and in a few seconds, you have refactored and documented your field.

The field refactoring method contains a few variants depending on the field initialization; look in the manual for a full description. I have added some more refactoring types, but you'll have to look in the manual for the complete specification.

Given below are some macros described in short, a full description exists in (yes, you are right) the manual.

MacroShortcutSummary

Document and regionize this

Ctrl + dAdds updates to the XML documentation on the current code element and puts #region #endregion directives around the section.

Paste template

Ctrl + Shift+ jChecks for keywords and pastes an appropriate template. Compare to Borland's template functions and VS 2005 Code Snippets.

Toggle parent region

Ctrl + m, Ctrl + mToggles the parent #region block.

Expand all regions

Ctrl + Shift + +Expands all #region blocks.

Collapse all regions

Ctrl + Shift + -Collapses all #region blocks.

Create documentation heading

Ctrl + Shift + Alt + hCreates a Documentation heading.

Format current document

Ctrl + Shift + dFormats the current document, compare to Edit.FormatSection.

Sort lines ascending

Ctrl + Alt + sSorts the selected lines in an ascending order.
Sort lines descendingCtrl + Alt + Shift + sSorts the selected lines in a descending order.

Install documentation toolbar items

Installs user configured toolbar(s) and items in the toolbox.

Act on tab

Ctrl + <Advances to the next XML doc tag if cursor is in an XML doc block.

Act on shift tab

Ctrl + >Goes to the previous XML doc tag if cursor is in an XML doc block.

Fix key mappings

Connects all shortcuts to the macros, except the Act on tab and Act on shift tab macros.
Remove key mappingsRemoves all keymappings for the Macros. (Doesn't restore any overridden macros though)
Fix key mappings after resharper installationFixes some keymapping collisions between resharper, DocumentatorMacros and VisualStudio.
MakeCDataWraps the selected text in a <![CDATA[ ... ]]> structure.
FixHTMLValidationErrorsFixes common validation errors in HTML documents.
KillLineCtrl + Shift + kKills the rest of the line
EnterCodeCommentCtrl + Shift + cCreates a comment on the format <date>: <domain>\<user>
EnterCodeRemarkCtrl + Shift + Alt + cAppends a remark comment to the current class documentation
RemoveWordPasteHtmlTagsRemoves Word specific HTML tags and attributes if you paste some formatted text from Word.
HTMLEncodeHTML encodes the marked text

Auto documentation

For properties, indexers and some methods, a default documentation is provided when the Document(AndRegionize) macro is invoked.

The following elements are auto documentated:

Method/Element Example
Constructors

<summary>
Initializes a new instance of the <b>MyType</b> class.
</summary>

Destructors
(Finalize)

<summary>
Releases unmanaged resources and performs other cleanup operations before
the <b>MyType</b> is reclaimed by garbage collection.
</summary>

void Dispose(...)

<summary>
Releases the resources used by the <b>MyType</b>
</summary>

string ToString(...)<summary>
Returns a <see cref="String"/>that represents the current <see cref="MyType"/>.
</summary>
<returns>A <see cref="String"/> that represents the current <see cref="MyType"/>.</returns>
bool Equals(MyType o)<summary>
Determines whether the specified <see cref="MyType"/> is equal to the current
<b>MyType</b>.
</summary>
<param name="o">The <see cref="MyType"/> to compare with the current <see cref="MyType"/>.</param>
<returns>true if the specified <see cref="MyType"/> is equal to the current <b>MyType</b>.;
otherwise, false.</returns>
bool Equals(MyType a, MyType b)<summary>
Determines whether the specified <see cref="MyType"/> instances are considered equal.
</summary>
<param name="a">The first <see cref="MyType"/> to compare</param>
<param name="b">The second <see cref="MyType"/> to compare</param>
<returns> true if <i>a</i> is the same instance as <i>a</i>
or if both are null references or if <c>a.Equals(b)</c> returns true; otherwise, false. </returns>
int GetHashCode(...)<summary>
Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
</summary>
<returns>A hash code for the current <see cref="MyType"/>.</returns>
Properties

<summary>
[Get/Set]s the [PropertyName] of the [ClassType]
</summary>

Indexers

<summary>
[Get/Set]s <see cref="[IndexerType]"/> item identified by the given arguments of the [ClassType]
</summary>

void ControlName_EventName(object param1, [Any]Args param2)

<summary>
This method is called when the [ControlName]'s [eventName] event has been fired.
</summary>
<param name="param1">The <see cref="object"/> that fired the event</param><param name="param2">The <see cref="AnyArgs"/> of the event</param>

Clone(Object obj)

<summary>
Creates a new object that is a copy of the current instance.
</summary>
<param name="source"></param>
<returns>A new object that is a copy of this instance.</returns>
bool Contains(Object obj)<summary>
Returns a value indicating whether the specified <see cref="Object"/>is contained in the <see cref="Class1"/>.
</summary>
<param name="a">The <see cref="Object"/> to locate in the
<see cref="Class1"/></param>
<returns><b>true</b> if the <i>Object</i> parameter is a member
of the <see cref="Class1"/>; otherwise, <b>false</b>.</returns>
bool IsWord(..)<returns>True if it is word, otherwise false.</returns>
bool IsWord1Word2WordN(...)<returns>True if word1 word2 is wordn, otherwise false.</returns>
[Any]Format(string format, param object[] args)<param name="format">A string containing zero or more format specifications.</param>
<param name="args">An array of objects to format.</param>
int Compare(MyType x, MyType y)<summary>Compares two objects and returns a value indicating whether one is less than,
equal to, or greater than the other.<summary>
<param name="x">The first object to compare.</param><param name="y">The second object to compare.</param>
<returns>A 32-bit signed integer that indicates the relative order
of the objects being compared. The return value has these meanings:
ValueMeaning
Less than zerox less than y.
Zerox is equal to y.
Greater than zero x is greater than y.
</returns>
int CompareTo(MyType o)<summary>Compares the current instance with another object of the same type.</summary>
<param name="o">The <see cref="MyType"> to compare with this instance.</param>
<returns>A 32-bit signed integer that indicates the relative order
of the objects being compared. The return value has these meanings:
ValueMeaning
Less than zeroThis instance is less than 0.
ZeroThis instance is equal to 0.
Greater than zeroThis instance is greater than 0.
</returns>

Points of Interest

I have to thank Roland Weigelt for his inspiring GhostDoc and some other macros (region expand). The Key mapping binder is also found on the net, I can't remember where though.

The upcoming Visual Studio 2005 will be a good update for the automation and refactoring with the introduction of code snippets.

History

2007-06-28 - 2.5.1.0

Contains support for

  • New macros

    • FixKeyMappingsAfterReSharper25Installation - renamed from FixKeyMappingsAfterReSharperInstallation. Used to setup keymappings after Resharper 2.5 has been installed
    • FixKeyMappingsAfterResharper3Installation - Used to setup keymappings after Resharper 3 has been installed
    • KillHtmlStyleAndClassFormatting - removes style and class formatting from selected HTML code

  • Enhancements /Bugfixes

    • PasteTemplate - added the disp keyword
    • EnterCodeRemark - Better output of code remarks
    • RemoveWordPasteHtmlTags - removes all mso-* styles, lang attributes from span tags.
    • DocumentThis - Auto documents public void Dispose(bool disposing)

007-01-25 - 1.4.0.0

Version 1.4.0.0 is a branch from v 1.3.0.0 that supports Visual Studio 2003. The 2003 branch misses all additional functionality after version 1.3.0.0 and has to be developed separately. I have no intention (personal need) to bring the 2003 branch up to the same functionality as the 2005 branch but if you feel like implementing in the 2003 branch, please send me your modifications and I can update this project.

  • New macros

    • FixKeyMappingsAfterResharper203Installation - updates the keyboard shortcuts

2007-01-15 - 2.5.0.0

  • Supports Visual Studio 2005 and

  • New macros

    • KillLine - Kills the rest of the line
    • EnterCodeComment - Enters a code comment on the format <date>: <domain>\<user>
    • EnterCodeRemark - Appends a remark comment to the current class documentation
    • RemoveWordPasteHtmlTags - Removes Word specific HTML tags and attributes if you paste some formatted text from Word.
    • HTMLEncode - HTML encodes the marked text

  • Enhancements/Bugfixes

    • FixKeyMappingsAfterResharperInstallation - Supports Resharper 2.5
    • CollapseAllRegions - now supports nested regions (thanks to DragonWang_SFIS) and commented ones.
    • PasteTemplate
      • Indentions now work better.
      • PropertyChanged events now fully documented
      • Field to property now recognizes private _variables and converts them to public Properties
      • for to foreach matches better
    • MakeCData - now does not HTML encode the selected text before creating the CData section.
    • FixHTMLValidationErrors
      • Combines multiple style attributes
      • Removes language and ms_positioning attributes from div tags
      • Removes topmargin attributes from body tags
      • Adds alt attributes to images if missing (defaults to the same as src)
    • DocumentThis
      • Better support for generics
      • Now supports explicit generic interfaces
      • Autodocuments [Any]Format(string format, param object[] args) methods
      • Autodocuments Compare methods
      • Regionizes better on long declarations
  • Updated installation instructions

2006-02-27 - 2.0.0.0

  • Supports Visual Studio 2005. For VS2003 support please use version 1.3.0.0.

  • New macros

    • MakeCData
    • Fix HtmlValidationErrors

  • Enhancements/Bugfixes

    • FixKeyMappingsAfterResharperInstallation - Supports
    • DocumentAndRegionizeThis - now works with VB.NET
  • CommentSection - Macro removed (VS 2005 internal CommentSection now works with XML/HTML/Javascript code
  • Plus an additional lot of enhancements and bugfixes

2005-10-27 - 1.3.0.0

  • Even more functions and enhancements

  • New macros

    • LoadColorableSettings
    • SaveColorableSettings
    • FixKeyMappingsAfterReSharperInstallation

  • Enhancements/Bugfixes

    • PasteSeeParameterXmlDocTag
      • Now works with delegates, Structs, Interfaces, Namespaces
    • DocumentAndRegionize
      • Added autodocumentation features on
        • get/set properties
        • indexers (interface)
        • "Is" methods

2005-06-08 - 1.2.0.0

  • Some more functions and enhancements.
  • Now more compatible with ReSharper

  • New Macros

    • PasteSeeParameterXmlDocTag
    • DocumentThis
    • RemoveKeyMappings

  • Enhancements/Bugfixes

    • DocumentAndRegionize
      • Added autodocumentation features on
        • Properties
        • Indexers
        • Event methods
        • Clone methods
        • Contains methods
    • PasteTemplate
      • Changed shortcut to Ctrl + Shift + j (to work with ReSharper)
      • fori template changed
      • Added templates forj, fork, test
    • ActOnTab
      • Changed shortcut to Ctrl + < (didn't want to lock up the tab key any longer)
    • ActOnShiftTab
      • Changed shortcut to Ctrl + > (didn't want to lock up the tab key any longer)
  • EnableTabMappings - Removed
  • DisableTabMappings - Removed

2005-04-07 - 1.1.0.0

  • This release contains a few more functions and bugfixes

  • Enhancements/Bugfixes

    • PasteTemplate
      • Added Singleton Template in PasteTemplate
      • Convert to property now recognizes static properties
    • DocumentAndRegionize
      • Document and Regionize now actually fills in documentation for a few methods
      • Empty documentation tags are now removed
      • Now Documents classes (not regionizes them)
      • Regionizes variables in structs
      • Better general quality of output XML documentation
      • Don't add <return> tags on properties anymore
      • Adds <value> tags on properties
      • Basic XML documentation now functions correctly when using this macro several times
      • No longer divides single tags into start/end tags when not appropriate

2005-03-15 - 1.0.0.1

  • Removed the reference to Se.MeridiumKalmar (thanks enigmacs).

2005-03-13 - 1.0.0.0

  • First public release

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Sweden Sweden
Dan Händevik is a software architect/developer, employed at Meridium ( http://www.meridium.se ) as Director of Development.
Dan has been programming since late 1980:s and is skilled in several programming languages such as C#, Java, Perl, VB.Net, JavaScript, VBScript and much more.
On his spare time, he enjoys spending time with his family and children.
Visit his blog for more information http://dhvik.blogspot.com

Comments and Discussions

 
QuestionDo you have any for vb.net Pin
Prasenjit Purohit14-Apr-09 20:24
Prasenjit Purohit14-Apr-09 20:24 
AnswerRe: Do you have any for vb.net Pin
Dan Handevik19-Apr-09 20:29
Dan Handevik19-Apr-09 20:29 
QuestionIs it applicable/will it work in VS2008? Pin
Bill Seddon28-Feb-08 21:53
Bill Seddon28-Feb-08 21:53 
AnswerRe: Is it applicable/will it work in VS2008? Pin
Dan Handevik28-Feb-08 23:31
Dan Handevik28-Feb-08 23:31 
QuestionHow to disable a macro? Pin
anisa_allahdadi7-Sep-07 22:08
anisa_allahdadi7-Sep-07 22:08 
AnswerRe: How to disable a macro? Pin
Dan Handevik9-Sep-07 8:21
Dan Handevik9-Sep-07 8:21 
Questionctrl + d is nice, but how about doing that for a awhole project or solution? Pin
Relampago28-Jun-07 20:11
Relampago28-Jun-07 20:11 
AnswerRe: ctrl + d is nice, but how about doing that for a awhole project or solution? Pin
Dan Handevik28-Jun-07 20:39
Dan Handevik28-Jun-07 20:39 
QuestionCreate a Form and open the Designer Pin
Paolo Pagano6-Feb-07 21:18
Paolo Pagano6-Feb-07 21:18 
GeneralA working ExpandAllRegions Pin
mjwills6-Sep-06 16:01
mjwills6-Sep-06 16:01 
If you are having problems with ExpandAllRegions in VS 2005, try the following:

Sub ExpandAllRegions()

Dim objSelection As TextSelection

objSelection = DTE.ActiveDocument.Selection

objSelection.StartOfDocument()
On Error Resume Next
DTE.ExecuteCommand("Edit.StopOutlining")
On Error GoTo 0

Here:

If objSelection.FindText("#region", vsFindOptions.vsFindOptionsMatchInHiddenText) Then
DTE.ActiveDocument.Selection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn)
objSelection = DTE.ActiveDocument.Selection
objSelection.LineDown(True)
GoTo Here
End If

objSelection.StartOfDocument()

End Sub
GeneralRe: A working ExpandAllRegions Pin
Dan Handevik7-Jan-07 21:15
Dan Handevik7-Jan-07 21:15 
QuestionNew node in header ...how Pin
lpastor23-Aug-06 2:54
lpastor23-Aug-06 2:54 
AnswerRe: New node in header ...how Pin
Dan Handevik24-Aug-06 0:28
Dan Handevik24-Aug-06 0:28 
GeneralRe: New node in header ...how Pin
lpastor25-Aug-06 2:46
lpastor25-Aug-06 2:46 
GeneralRe: New node in header ...how Pin
Dan Handevik25-Aug-06 11:43
Dan Handevik25-Aug-06 11:43 
GeneralSome changes for CollapseAllRegions Pin
Darrell Wang16-May-06 20:53
Darrell Wang16-May-06 20:53 
AnswerRe: Some changes for CollapseAllRegions Pin
Dan Handevik17-May-06 23:40
Dan Handevik17-May-06 23:40 
QuestionMacros in C# Pin
CodeIsGod15-May-06 20:29
CodeIsGod15-May-06 20:29 
AnswerRe: Macros in C# Pin
Dan Handevik15-May-06 21:34
Dan Handevik15-May-06 21:34 
GeneralKeyboard Pin
u neek9-Mar-06 11:02
u neek9-Mar-06 11:02 
AnswerRe: Keyboard Pin
Dan Handevik10-Mar-06 1:52
Dan Handevik10-Mar-06 1:52 
GeneralRe: Keyboard Pin
u neek10-Mar-06 6:19
u neek10-Mar-06 6:19 
AnswerRe: Keyboard Pin
Dan Handevik11-Mar-06 19:19
Dan Handevik11-Mar-06 19:19 
GeneralSweet! Pin
mashiharu27-Feb-06 22:55
mashiharu27-Feb-06 22:55 
GeneralSmall note on your .chm file Pin
cbono20001-Nov-05 11:12
cbono20001-Nov-05 11:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.