Saturday 22 February 2014

Using NArrange to structure and arrange C#/VB source code

NArrange is an open source tool to arrange source code. It beautifies the source code by grouping members, properties, events and more, into configurable regions. You can set it up to run as a command or a pre-build event. Lets take a look at it.

We have this code to start with, not dealing with whitespace or anything - it's a mess but for illustration purposes still quite simple.


By running NArrange we then expect to get 3 regions, constructors, methods and fields. A cleanup of the file(s), indenting correctly and removing whitespaces should also happen. Lets take a look at the code afterwards.


The tool is great for consistency in the source code to a project which is under version control, by enforcing NArrange to be run before or as an event during check-in, the formatting will be consistent.

On the down side running as a pre-build event can have some annoying moments. For instance building during a debug session could move your newly typed code around which can be annoying.

Setting it up in Visual Studio

Download NArrange from the website or as a chocolatey package. All the examples takes the solution file as input and arranges all projects in the solution. The parameter can, if needed, be a single project or just a single file.

As an external tool

We will create two external tools, one for arranging / taking a backup, and one for restoring the backup if needed. In Visual Studio select Tools -> External Tools -> Add and you will have to fill in the command, arguments and initial directory fields.



Command: C:\Program Files (x86)\NArrange 0.2.9\narrange-console.exe
Arguments: "$(SolutionFileName)" /b
Initial Directory: $(SolutionDir)
Note that the /b is for taking the backup


Command: C:\Program Files (x86)\NArrange 0.2.9\narrange-console.exe
Arguments: "$(SolutionFileName)" /r
Initial Directory: $(SolutionDir)
Note that the /r is for restoring the backup - it requires a backup is present.

Pre-build event

In properties of your project under build events add the following to the pre-build event.


cd C:\Program Files (x86)\NArrange 0.2.9
narrange-console.exe "$(SolutionPath)"

/JJ