Click here to Skip to main content
Click here to Skip to main content
Go to top

Automating the code writing process using macros

, 5 Jul 2007
Rate this:
Please Sign up or sign in to vote.
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:

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:

#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:

tryc

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

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:

public event EventHandler MyEvent;

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

#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,

public string Name;

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

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.

Macro Shortcut Summary

Document and regionize this

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

Paste template

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

Toggle parent region

Ctrl + m, Ctrl + m Toggles 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 + h Creates a Documentation heading.

Format current document

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

Sort lines ascending

Ctrl + Alt + s Sorts the selected lines in an ascending order.
Sort lines descending Ctrl + Alt + Shift + s Sorts 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 mappings Removes all keymappings for the Macros. (Doesn't restore any overridden macros though)
Fix key mappings after resharper installation Fixes some keymapping collisions between resharper, DocumentatorMacros and VisualStudio.
MakeCData Wraps the selected text in a <![CDATA[ ... ]]> structure.
FixHTMLValidationErrors Fixes common validation errors in HTML documents.
KillLine Ctrl + Shift + k Kills the rest of the line
EnterCodeComment Ctrl + Shift + c Creates a comment on the format <date>: <domain>\<user>
EnterCodeRemark Ctrl + Shift + Alt + c 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

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:
Value Meaning
Less than zero x less than y.
Zero x 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:
Value Meaning
Less than zero This instance is less than 0.
Zero This instance is equal to 0.
Greater than zero This 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)

Share

About the Author

Dan Handevik
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 PinmemberPrasenjit Purohit14-Apr-09 20:24 
AnswerRe: Do you have any for vb.net PinmemberDan Handevik19-Apr-09 20:29 
QuestionIs it applicable/will it work in VS2008? PinmemberBill Seddon28-Feb-08 21:53 
AnswerRe: Is it applicable/will it work in VS2008? PinmemberDan Handevik28-Feb-08 23:31 
QuestionHow to disable a macro? Pinmemberanisa_allahdadi7-Sep-07 22:08 
AnswerRe: How to disable a macro? PinmemberDan Handevik9-Sep-07 8:21 
Questionctrl + d is nice, but how about doing that for a awhole project or solution? PinmemberRelampago28-Jun-07 20:11 
AnswerRe: ctrl + d is nice, but how about doing that for a awhole project or solution? PinmemberDan Handevik28-Jun-07 20:39 
QuestionCreate a Form and open the Designer PinmemberPaolo Pagano6-Feb-07 21:18 
GeneralA working ExpandAllRegions Pinmembermjwills6-Sep-06 16:01 
GeneralRe: A working ExpandAllRegions PinmemberDan Hvik7-Jan-07 21:15 
QuestionNew node in header ...how Pinmemberlpastor23-Aug-06 2:54 
AnswerRe: New node in header ...how PinmemberDan Händevik24-Aug-06 0:28 
GeneralRe: New node in header ...how Pinmemberlpastor25-Aug-06 2:46 
GeneralRe: New node in header ...how PinmemberDan Händevik25-Aug-06 11:43 
GeneralSome changes for CollapseAllRegions PinmemberDragonWang_SFIS16-May-06 20:53 
AnswerRe: Some changes for CollapseAllRegions PinmemberDan Händevik17-May-06 23:40 
QuestionMacros in C# PinmemberSavaliya Bharat15-May-06 20:29 
AnswerRe: Macros in C# PinmemberDan Händevik15-May-06 21:34 
GeneralKeyboard Pinmemberu neek9-Mar-06 11:02 
AnswerRe: Keyboard PinmemberDan Händevik10-Mar-06 1:52 
GeneralRe: Keyboard Pinmemberu neek10-Mar-06 6:19 
AnswerRe: Keyboard PinmemberDan Händevik11-Mar-06 19:19 
GeneralSweet! Pinmembermashiharu27-Feb-06 22:55 
GeneralSmall note on your .chm file Pinmembercbono20001-Nov-05 11:12 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140926.1 | Last Updated 5 Jul 2007
Article Copyright 2005 by Dan Handevik
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid