Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C#
Article

NArrange - .NET Code Organizer/Formatter/Beautifier

Rate me:
Please Sign up or sign in to vote.
4.65/5 (70 votes)
22 Dec 2008CPL8 min read 434.6K   187   157
Using NArrange to organize C# source code.

Introduction

NArrange is a stand-alone, configurable .NET code beautification tool that automatically organizes code members and elements within .NET classes. It allows developers to easily sort class contents according to their style and layout conventions. NArrange works by parsing source code files into a document object model, arranging the elements, then rewriting the arranged source code.

NArrange helps reduce the amount of time developers spend arranging members within source code files, and when used as part of check-in procedures, can also help reduce source code repository conflicts. With NArrange, developers don't need to worry about where they place a new member definition in a class; they can just type away, and run NArrange prior to compilation. After formatting, the new member will be automatically moved to the appropriate location in the source file. NArrange is not only a great time saver, but it also helps enforce coding style standards across a team when a common configuration file is used.

Obtaining NArrange

NArrange is an open source tool, and can be downloaded here.

Using NArrange

To demonstrate the common usage scenarios of NArrange, we'll start by creating a new project in our C# editor, in this case, Visual Studio®, and add a stub class with a constructor. Note that since NArrange is a stand-alone tool without any IDE dependencies, it can be used along with any code editor or within automated build processes.

Demo1Initial2.png

Figure: New Project with a Class Stub

With the project saved, NArrange can then be run against the source code file, project, or solution. For running NArrange from the command line, refer to Command Line Usage, or to integrate with Visual Studio® as an external tool, see Microsoft® Visual Studio® Setup. When running NArrange with an editor, it is recommended to backup or commit your source first, or use the built-in backup feature, which makes reverting formatting changes a snap. Either way, please be sure to protect your time investment in your code prior to running the tool.

Demo2Run2.png

Figure: Running NArrange as a VS External Tool

After running NArrange, the constructor we added to the stub class will automatically be enclosed in a "Constructors" region (see image below).

Demo3OrganizedAnnotated2.png

Figure: After Running NArrange Against the Stub Class

Since our stub class doesn't yet have any functionality, we'll then a new method, called Demo, that writes a friendly message to the console. Note that when adding the new method, we're not taking any care with regards to its placement within the class. In this case, we are adding it as the first member just inside the class body, before the constructor.

Demo4AddMember2.png

Figure: Adding a New Member

After adding the new member, we'll run NArrange again against the source file or project. The new method will be automatically moved to the proper location in the file, and enclosed in an appropriate region (see below). The default configuration for NArrange also sorts members within groups or regions, alphabetically, by member name.

Demo5RearrangedAnnotated2.png

Figure: Rearranged Class with New Method

Scrolling up to the top of the source file, you will also notice that NArrange automatically encloses the header comments in a region, and applies grouping and sorting to using directives (see image below).

DemoHeaderAndUsingsAnnotated2.png

Figure: Header Region and Sorted using Directives

Command Line Usage

To arrange a file, just run the following:

>narrange-console <source file> [optional output file]

If an output file is not specified, the original source file will be overwritten. Alternatively, you can run NArrange against a C# or VB project file or solution. When arranging a project or solution, the original source files will be overwritten.

The command line usage is as follows:

narrange-console <input> [output] [/c:configuration]
        [/b] [/r] [/t]


input   Specifies the source code file, project or solution to arrange.

output  For a single source file, specifies the output file
        to write arranged code to.
        [Optional] If not specified the input source
        file will be overwritten.

/c      Configuration - Specifies the XML configuration file to use.
        [Optional] If not specified the default
        configuration will be used.

/b      Backup - Specifies to create a backup before arranging
        [Optional] If not specified, no backup will be created.
        Only valid if an output file is not specified
        and cannot be used in conjunction with Restore.

/r      Restore - Restores arranged files from the latest backup
        [Optional] When this flag is provided, no files will be arranged.
        Only valid if an output file is not specified
        and cannot be used in conjunction with Backup.

/t      Trace - Detailed logging

Microsoft® Visual Studio® Setup

  1. From the Tools menu, select External Tools.
  2. Add a new entry for NArrange.
    • For the command, select the location of narrange-console.exe.
    • For arguments, pass the solution, project, or file path macro depending on your preference. When choosing this, you may want to take into consideration your revision control system (i.e., whether or not files are marked as read-only). NArrange cannot arrange read-only files. It is recommended to pass the /b argument to specify that an automatic backup be created in your user temp directory.

    Image 7

  3. It is also recommended to setup a restore command using the same parameters, replacing /b with /r. However, be careful when using restore, as it will revert any edits made to a file since the last NArrange.
  4. Image 8

Creating a Custom Configuration File

By default, NArrange uses a configuration that is, for the most part, compatible with the member ordering rules defined by the Microsoft StyleCop source analysis tool. An exception to this is file header regions.

To override the default arrangement of source code members, a custom configuration file can be used. To create your own custom configuration file, you should start by creating a copy of DefaultConfig.xml and renaming it appropriately. Note that NArrange does not read DefaultConfig.xml, but rather it is provided as an example for creating a custom configuration. The actual default configuration is embedded within the NArrange core assembly.

The NArrange Configuration Editor, shown below, can be used to ease editing of the XML configuration. It can be launched using narrange-config.exe.

Image 9

Figure: Configuration Editor

The figure below shows sections from a sample XML configuration file. NArrange uses the ordering of Element and Region tags in the configuration file to define the ordering of code members in the output source files.

Image 10

Figure: Sample NArrange Configuration File

By defining a Sort attribute for elements in a region, NArrange will sort those elements alphabetically in the region by the specified attribute. Valid element attributes are:

  • Name - Returns the code element name.
  • Access - Returns the element access.
  • Valid comparison value strings for this attribute are:

    • None
    • Public
    • Protected
    • Internal
    • Protected, Internal
  • Modifier - Returns element modifiers as a comma separated list.
  • Valid comparison value strings for this attribute are:

    • Abstract
    • Sealed
    • Static
    • Unsafe
    • Virtual
    • Override
    • New
    • ReadOnly
    • Constant
    • External
    • Partial
  • ElementType - Returns the NArrange element type.
  • Valid comparison value strings for this attribute are:

    • Comment
    • Attribute
    • Using
    • Namespace
    • Region
    • ConditionDirective
    • Field
    • Constructor
    • Property
    • Method
    • Event
    • Delegate
    • Type
  • Type - Returns the return type of the element (e.g. 'string').
  • For Type elements, this returns the sub-type: 'Class', 'Structure', 'Interface', 'Enum' or 'Module' (VB only).

  • Attributes - Returns a comma separated list of the names of all attributes associated with an element.

Attributes can also be qualified with a scope. For example $(Element.Name) or $(Parent.ElementType).

You may notice that filter conditions can be applied to elements, which are used to filter elements into the appropriate group or region. Filter expressions can use the element attributes above using the $(AttributeHere) syntax. Filter expressions use string comparison, and the following operators are available:

Operator NameSyntax
Equality==
Inequality!=
Contains:
Regular Expression match=~
Logical OrOr
Logical AndAnd
Negate!(inner expression)

Strings in element expressions should be enclosed with single quotes.

Limitations

One of the biggest limitations with the current version of NArrange is that it cannot handle many scenarios involving preprocessor directives (#pragma, #define, etc.). Thus, you will get a warning message indicating that files containing unhandled preprocessor directives cannot be parsed. Note that this is not an issue if the preprocessor directive is within a member body.

For conditional compilation preprocessor directives (#if, #else, etc.), basic support is available. So long as the conditional compilation preprocessor directive completely encloses types/members in their entirety (with all attributes and comments), NArrange will preserve the directive and process any enclosed elements. However, the scenario where a directive starts at the class level and intersects a member declaration in any manner is not supported, and will result in a parsing error.

Supported Languages

NArrange currently supports organization of C# and Visual Basic .NET source code files. Although NArrange has been built and tested under the .NET Framework 2.0, it includes support for many 3.0 and 3.5 language features such as:

  • Partial Methods
  • Extension Methods
  • Object Initializers

Many 3.+ language features are excluded from this list, such as LINQ and Lambda Expressions. However, NArrange does not currently parse to the statement level of constructors, methods, and properties, so these features are inherently supported.

NArrange has been designed with the intention of supporting many .NET languages. If you are interested in implementing a parser/writer for an additional CLI language, please contact an NArrange contributor through the SourceForge project site. NArrange is still in the early stages of development, so any suggestions to help make the framework more compatible with other languages would be greatly appreciated.

Licensing

NArrange is licensed and distributed under the Common Public License Version 1.0. A copy of this license is included with the source distribution, and can also be viewed online here.

Support

Please direct all support questions, feature requests, and bug reports to the NArrange SourceForge project site or to the CodeProject forum for this article.

History

  • 05/12/2008 - Initial authoring for inclusion within the NArrange preliminary documentation and introduction on CodeProject. For the most up-to-date documentation, please refer to www.narrange.net.
  • 05/19/2008 - Reduced image sizes, and fixed/updated the expression operator table.
  • 05/26/2008 - Moved back to the Code Generation category.
  • 06/02/2008 - Added a screenshot of the Configuration Editor.
  • 06/09/2008 - Fixed the documentation for the Type element attribute as well as some formatting issues.
  • 06/29/2008 - Updated the Limitations section for conditional compilation preprocessor directive support.
  • 08/10/2008 - Updated the configuration section to make note of the StyleCop default configuration.
  • 12/22/2008 - Updated external links.

License

This article, along with any associated source code and files, is licensed under The Common Public License Version 1.0 (CPL)


Written By
Software Developer Astral Softworks, LLC
United States United States
James Nies is a graduate of the University of Wyoming's Department of Computer Science. He is currently employed as a software developer and has been programming in C#, his favorite language, for the last 5 years. James recently formed a small software development and web design company, Astral Softworks, LLC.



Comments and Discussions

 
QuestionNArrange in Visual Studio 2012 for C# not working for SVN source control Pin
Vivek Gupta123-Jan-15 1:25
Vivek Gupta123-Jan-15 1:25 
QuestionNice ! Pin
NinjaCross22-Sep-13 7:08
NinjaCross22-Sep-13 7:08 
GeneralMy vote of 3 Pin
eRRaTuM17-Jul-12 2:21
eRRaTuM17-Jul-12 2:21 
GeneralHow-to force narrange keep Com interface Pin
eRRaTuM17-Jul-12 2:17
eRRaTuM17-Jul-12 2:17 
Hi,
Very usefull tool, I have been using it for something linke 18 months.

But Up to now, i just can not figure out how to force narrange to keep the interface member functions in the order that the methods appear in the COM interface.

What I do is group all ComInterfaces in a project (wich is not always possible), and run narrange for every other projects... Sigh | :sigh: , Alternatively, add some #define instruction to every Interface definition.

I crawled every forum post, every related page but I just can't find my answer Frown | :(

Thanks for you reply in advance.
05BEA407F8F0DFDB7A0F1E77F473EE0F


modified 17-Jul-12 14:41pm.

GeneralMy vote of 5 Pin
Jorge Casals30-Mar-12 0:25
Jorge Casals30-Mar-12 0:25 
QuestionDoes this work with VS2010? Pin
rbseattle6-Mar-12 19:03
rbseattle6-Mar-12 19:03 
BugRe: Does this work with VS2010? Pin
tlhIn`toq25-Mar-12 8:57
tlhIn`toq25-Mar-12 8:57 
QuestionAny chance to arrange private members close to properties or functions they are used in? Pin
Oliver Bleckmann21-Oct-11 3:20
Oliver Bleckmann21-Oct-11 3:20 
GeneralMy vote of 5 Pin
Indivara24-Jan-11 19:28
professionalIndivara24-Jan-11 19:28 
GeneralParsing error on field initialized with anonymous delegate Pin
sprucely7-Apr-10 6:24
sprucely7-Apr-10 6:24 
QuestionBreakpoints shifted after NArrange Pin
krravisha25-Feb-10 19:37
krravisha25-Feb-10 19:37 
Generalvery useful.. Pin
mk.developer12-Jan-10 10:49
mk.developer12-Jan-10 10:49 
Questionhow to plug NArrange into SVN or any other source control Pin
krravisha3-Jan-10 22:44
krravisha3-Jan-10 22:44 
NewsNArrange 0.2.9 Released Pin
James Nies5-Dec-09 11:11
James Nies5-Dec-09 11:11 
NewsNArrange 0.2.8 Released Pin
James Nies6-Jul-09 21:20
James Nies6-Jul-09 21:20 
QuestionNArrangin single File in Visual Studio Pin
krravisha11-May-09 0:08
krravisha11-May-09 0:08 
AnswerRe: NArrangin single File in Visual Studio Pin
James Nies15-May-09 18:31
James Nies15-May-09 18:31 
GeneralRe: NArrangin single File in Visual Studio Pin
krravisha25-Feb-10 19:46
krravisha25-Feb-10 19:46 
QuestionHow can I let narrange-console.exe "eat" my customized config? Pin
to recurse29-Apr-09 22:42
to recurse29-Apr-09 22:42 
AnswerRe: How can I let narrange-console.exe "eat" my customized config? Pin
James Nies15-May-09 17:58
James Nies15-May-09 17:58 
QuestionUsing Region Pin
Eadgbe16-Jan-09 3:02
Eadgbe16-Jan-09 3:02 
QuestionPartial Classes Pin
Ed.Poore22-Dec-08 13:30
Ed.Poore22-Dec-08 13:30 
AnswerRe: Partial Classes Pin
James Nies23-Dec-08 7:37
James Nies23-Dec-08 7:37 
QuestionNArrange problems with synchronize with SVN Pin
pindurav6-Nov-08 21:19
pindurav6-Nov-08 21:19 
AnswerRe: NArrange problems with synchronize with SVN Pin
James Nies11-Nov-08 17:30
James Nies11-Nov-08 17:30 

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.