Code Lockdown
Before starting on a new project it's always worth while taking a few minutes to configure the build so that we get the benefits of a code analysis early warning system. To do this we can use a combination of Visual Studio code analysis, StyleCop and project build settings.
To lock down your code, follow these steps:
- In VS Solution Explorer, right click on the project and select "Unload Project"
- Right click again and select "Edit
.csproj" - In the first property group add CodeAnalysisTreatWarningsAsErrors and set it to true

- Save the file and close it
- Reload the project in Solution Explorer
- Right click the project and select properties
- In the "Build" tab set "Treat Warnings as Errors" to All

- In the "Code Analysis" tab click the "Enable Code Analysis on Build" checkbox

- If you want to max-out, change the rule set from "Microsoft Minimum Recommended Rules" to "Microsoft All Rules"
Now, when you build your project if any code analysis rules fail, so will your build! For those looking for a Belt-And-Braces approach (and why not!) you can do the same using StyleCop.
- First of all, download and install StyleCop
- In your .csproj file add StyleCopTreatErrorsAsWarnings and set it to false
(NB* This is the opposite way round to the earlier code analysis property)

- At the bottom of the project file add the import to the stylecop build target
(NB* On x32 bit systems use the $(ProgramFiles) variable).

- Save the .csproj and close it
- Reload your project in Solution Explorer
Now when you build your project your code will be thoroughly scrutinised and the slightest deviation from anything other than truly excellent will result in a build failure. Believe you me, it can be pretty picky too...

So why go to all this bother? By locking down our code we get all kinds benefits which are hard to quantify. If all developers on a team are adhering to the same coding rules, then all the code will look the same regardless of who's written it. It avoids the unnecessary and often dreaded "Coding Standards" documentation. This familiarity means code is instantly recognisable allowing the developer to concentrate on the semantics of it.
Another benefit is actually an educational one. A lot of the rules in the code analysis engines are based on avoiding subtle bugs. Understanding the rule means understanding the possible cause of the bug and thereby increases the developers' skill.
So, by implementing code analysis into our builds we are setting up an early warning system for potential bugs. By finding bugs as early as possible in the development lifecycle we are saving time and money later.
One final note on code analysis: Make sure you enable code analysis not just for your production code projects but also for your unit and acceptance test projects too! Test code should always be treated as a first class citizen.

