Formatting code with Regions

When it comes to keeping my code clean I’m a bit of stickler for using regions to help group my methods and properties. I will admit that I don’t always put these in when I’m in a hurry but when I do go back to my code to add these in I find it can take a considerable amount of time. One thing I’m surprised by is that Visual Studios doesn’t have a nice built in way for adding regions by simply highlighting the code you want to enclose in a region. I ended up doing some research and found some ways to deal with this.

Using Visual Studio macros

After a quick search online I found macros that do the job. I decided to use the macro found here: http://weblogs.asp.net/fbouma/archive/2003/06/23/9140.aspx but made some alterations. Besides enclosing groups of methods with regions I like to ensure that the region tags have a newline between them and the code they are enclosing. I’ve also removed some of the extra macros they had as I didn’t need them. To add this macro to your Visual Studios go into View–>Other Windows->Macro Explorer, right click on MyMacro’s and add a new macro called “Regions”. An editor for the macro should open, if not right click on the macro and select “Edit”. Copy the following code into the macro editor and save it:

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics

Public Module Regions
    ”’ Makes a generic C# region of the selected lines and asks for the name of the region.
    Sub MakeRegion()
        Dim regionName As String = InputBox("Region name: ")
        MakeRegion(regionName)
    End Sub

    Sub MakeRegion(ByVal regionName As String)
        Dim selection As TextSelection = DTE.ActiveDocument.Selection()
        Dim start As EditPoint = selection.TopPoint.CreateEditPoint()
        Dim endpt As EditPoint = selection.BottomPoint.CreateEditPoint()

        DTE.UndoContext.Open("Make Region")
        Try
            ‘ insert the start of the region
            start.Insert("#region " & regionName)
            start.SmartFormat(start)
            start.Insert(Environment.NewLine)
            start.SmartFormat(start)
            Dim cursorPoint As EditPoint = start.CreateEditPoint()
            start.Insert(Environment.NewLine)

            If selection.IsEmpty Then
                start.Insert(Environment.NewLine)
                start.SmartFormat(start)
                start.Insert("#endregion")
                start.SmartFormat(start)
                start.Insert(Environment.NewLine & Environment.NewLine)
                Dim ts As TextSelection = DTE.ActiveWindow.Selection
                ts.MoveToPoint(cursorPoint)
            Else
                ‘ insert the end of the region
                If Not (endpt.AtStartOfLine) Then
                    endpt.Insert(Environment.NewLine)
                End If
                endpt.Insert(Environment.NewLine)
                endpt.SmartFormat(start)
                endpt.Insert("#endregion")
                endpt.SmartFormat(endpt)
                endpt.Insert(Environment.NewLine & Environment.NewLine)
            End If
        Finally
            DTE.UndoContext.Close()
        End Try
    End Sub
End Module

As a quick test highlight some code and double click the MakeRegion macro. A window should appear asking you to enter a name for the region. Enter in a name and press ok. Your highlighted ode should be enclosed with a region tag and have the name you entered beside the tag.

Using an Item Template with predefined Regions

A lot of times I find that I’m always creating the same regions; “Public Properties”, “Constructors”, “Public Methods”, and so on. Rather than having to manually create these all the time I decided to create an item template of a simple class file that already has these regions in it. This way they are there when I create the file and I can either remove them if I don’t need them or just leave them for future code. I’ve tested this with VS 2008 and 2010. It should work with VS 2005 too. To get this template working for you do the following:

1) Download template here: https://cid-e7dba9a4bfd458c5.office.live.com/viewpermissions.aspx/General%20Development/ClassRegionTemplate.zip?ref=11
2) Leave file zipped and copy it to C:\…\Visual Studio 20XX\Templates\ItemTemplates\Visual C#
3) Restart the version of Visual Studios you added this to and either create a new project or open an existing on. When you add a new item to your project you select “Visual C#”. You should see a template called “C# Class with Regions”

If you select this file type and call it “TestClass.cs” you will end up with something like this:

using System;
using System.Collections.Generic;

namespace YourProjectNamespace
{
    public class TestClass
    {
        #region Private Properties

        #endregion

        #region Constructor

        ///<summary>
        /// Constructor
        ///</summary>
        public TestClass()
        {

        }

        #endregion

        #region Public Proeprties

        #endregion

        #region Public Methods

        #endregion

        #region Private Methods

        #endregion
    }
}

 

Regions in JavaScript Code

I recent was working on a rather large JavaScript project and find it a bit annoying that there is no way to collapse blocks of code in Visual Studios. After some looking around on the web I found a nice macro that does the job by using commented out regions syntax (http://blog.devarchive.net/2008/04/using-region-directive-with-javascript.html). I modified the macro based on one of the comments that was left on that page so that I could add a title to the region and have it always visible. It’s not a perfect solution as I always have to run the macro when I open up a JavaScript file but once that’s done my regions are collapsible.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s