Rules to Better Code Quality

​​​

Hold on a second! How would you like to view this content?
Just the title! A brief blurb! Gimme everything!

​​

  1. Do you know the Code Health (Quality Gates) to add?

    ​​​​Code health is all about quality and consistency. Here is how to use various auditors and linters not just in your development environment, but also on your VisualStudio.com build.

    Depending on your development environment and the type of project, you should utilise different auditing tools.
     1) Visual Studio - How to install and modify Visual Studio Analysers
     2) Visual Studio Code - How to include TSLint and CSSLint extensions
     3) VisualStudio.com - How to produce a build script which analyses code as part of the build process​​

    Following the steps should take about 15 minutes to do, but longer to implement depending on the size of your solution. (Requires solution analysis in VS and at least one build on VisualStudio.com)

    Version 1.2
    - Added step to include "PrimaryBuild" variable as a pseudo id for the API
    ​Version 1.1
    - Removed CssLint from VisualStudio.com build definition
    - Added Web Essentials to Visual Studio environment​

    Visual Studio

    Search & Install the NuGet packages:
    ​"Roslyn Security Guard " https://www.nuget.org/packages/RoslynSecurityGuard/
    "StyleCop.Analysers" https://www.nuget.org/packages/StyleCop.Analyzers/1.0.0
    "tslint" https://www.nuget.org/packages/tslint/

    For Visual Studio development on web applications, download Web Essentials, it will provide intellisense for JS, CSS, HTML, Less, Scss, and CoffeeScript. (https://marketplace.visualstudio.com/items?itemName=MadsKristensen.WebEssentials20153​ )
    ​​

    VS-InstallNuGetPackages.png
    Figure: Steps to install NuGet Packages

    ​Here is a quick guide to the steps to install NuGet Packages to the entire solution:
     1) Right click solution
     2) Select "Manage NuGet packages for solution"
     3) Select "Browse"
     4) Search <package name>
     5) Select <package name>
     6) Check all projects
     7) Click "Install"

    Issues from these will now be returned in the Visual Studio analyser error list.

    VS-RoslynRules.png​​​​​Figure: New Roslyn Rule issues raised in Visual Studio Analyser


    Run Code Analysis on the project. Check over all of the warnings, if they are unnecessary or inappropriate, disable them, otherwise modify their severity level to "Error". 
    When the build is run, "Errors" will break the build, while "Warnings" will be reported, but not break the build.
    Rules which have been flagged should also be checked once the build is completed

    Modify Visual Studio Analysis

    ​​The goal is to develop a shared ruleset across projects. (Currently this is just the default settings)
    Any project specific rules should be documented in "_Instructions-CodeHealth.docx" kept in the solution.
    Please also copy the current version number of this rule into the "_Instructions-CodeHealth.docx" in order to track what version your existing solution adheres to.

    ​​​​VS-ModifyRules.png
    ​​​Figure: Steps to open Visual Studio Analyser rules customisation page

    ​Right Click project > Properties > Code Analysis > Open

    VS-ModifyRules2.png
    ​​Figure: How to customize rules. By either enabling / disabling rules or packages. Or by modifying the rule severity level.

    Visual Studio Code

    ​For web projects, we advocate the use of CSSLint for css files and TSLint for typescript files. (Why you should be using TypeScript instead of JavaScript​)

    Linters for these can be easily added to VS Code via extensions.
    Simply select the "Extensions" tab, search for "CSSLint" and "TSLint" and click "Install" on each respectively.​

    VSCode-Extensions.png
    Figure: Addition of CssLint and TSLint to VS Code Project

    If you prefer not to use the Extensions (which are currently a bit out of date). You can install them using npm as normal.​​

    CssLint https://www.npmjs.com/package/csslint​
    TSLint https://www.npmjs.com/package/tslint

    ​Automatically Check your Build in VisualStudio.com

    Ensure utilisation of TeamBuild2015 or higher. (No support for XAML builds)
    Edit the build definition​

    VSO-EditBuild.png
    Figure: Steps to edit an existing build definition on VisualStudio.com ​​

    Select "Build & Release" > Select "Builds" > Click on your existing build > Click "Edit"

    VSO-BuildDefinition-V3.png
    ​​Figure: Example completed build definition.
    VSO-DirectoryExampleV2.png
    ​Figure: Example directory for TSLint run commands

    Under advanced for the Command Line tasks, the Working Directory can be specified if necessary.

    TsLint​

    Npm - Install tslint and typescript
    Name​: npm install tslint
    ​​​Working Folder: <Top Directory>
    Npm Command: install
    Arguments: -g tslint typescript

    Command Line - Check the version ​​​(Useful to determine rule discrepancies across builds)
    Name​: Check tslint version
    Tool: tslint
    Arguments: -v

    Command Line - Builds a default configuration file for the build (Without it issues can differ between build and development environment
    Name​: Create tslint config file
    Tool: tslint
    Arguments: --init

    Command Line - Run tslint, force is required to stop the build from crashing (TSLint will return and exit code of 1 regardless of if issues exist)
    Name​: ​Run tslint
    Tool:​ TSLint
    Arguments: --force <Solution Directory>/**/*.ts{,x}

    If your build is being hosted, then the config file must be reloaded every time. If your build is running on premises, the config file will attempt to load over the existing one and break the build.
    If this is the case, just add a step to delete your config file after the scan is complete.

    VSO-RemoveConfig.png
    ​Figure: Command line step to remove the config file (tslint.json) after the linter has run

    Command Line - Remove the tslint config file, as it will break future scan if the build is on premises if a config file already exists and an attempt to add another one is made.
    ​​Name​: ​Remove tslint config
    Tool:​ del
    Arguments: tslint.json​

    Once complete, save the build definition and run the build.​
    Then check the build is successful.
    If the build fails (due to errors), these should be corrected in the development environment.
    If warnings exist, the rule should be disabled or set as an error. (If it is worth fixing, then it should be required for everyone)

    ​​

    If your project does not contain TypeScript files, then you do not need to include the TSLint build tasks.

    VSO-EnsureTSLintRuns.png​​Figure: Ensure TSLint actually finds files to scan (if the project includes TSLint files) otherwise it will pass without you noticing


    ​For the purposes of reporting, a unique tag must be added to the build definition which the Code Health steps have been applied to. ​
    This is done with the addition of a variable (Name = PrimaryBuild, Value = true)

    VSO-AddVariableTag.pngFigure: Steps to add PrimaryBuild variable to build definition​​​​​​​​​​​​
    VSO-BuildResult-BadV3.png
    ​​​Figu​re: Bad Example - Build broke due to compile errors. Must fix to proceed.​
    ​​VSO-BuildResultV3.png
    ​​​​​​​​​​​Figure: Bad Example - Successful build with warnings. Should be disabled or set as errors.​​
    ​​​​​​VSO-BuildResult-GoodV3.png
    ​​​​​​​​​​Figure: Good Example - Successful build with no warnings.



  2. Do you run the Code Health checks in your VisualStudio.com Continuous Integration Build?Unpublished

    ​The real value of the code health system is that is made improvements in code quality more visible to the team and managers. By including several steps to the build process, the results of the analysers included in previous steps can be extracted out and summarised in a report spanning the project's lifetime. 

    ​​Related Steps to Code Health:​​​

    ​What Steps to Include in the B​​​uild Definition​

    ​​Summary:

    1. Ensure "Restore NuGet Packages" & "Build Solution" are in the build definition to run the Roslyn analysers.
    2. Add several npm and command line steps to the build definition to run tslint. (On premises builds require an additional step).
    3. Include an identifying variable "PrimaryBuild" to the build definition.
    4. Check the build is running without issues.​​​

    The resulting build should look like this.

    ​​​​​VSO-Build-Good-1.png
    Figu​​re: ​Good Example - Build Passing with no summa​​​ry issues
    ​​​
    Ensure utilisation of TeamBuild2015 or higher. (No support for XAML builds)
    Edit the build definition on <CompanyName>.visualstudio.com, and add the following build tasks.
    If your project does not contain TypeScript files, then you do not need to include the TSLint build tasks.
    VSO-BuildDefinition-V3.png
    Figure: Good Examp​​​​​​le - Steps ​​added to build definition.
    ​​​​VSO-DirectoryExampleV2.png
    Figure: Exa​mp​​​le director​​y for TSLint run commands


    Under advanced for the Command Line tasks, the Working Directory can be specified if necessary.

    TsLint​
    Npm - Install tslint and typescript
    Name​: npm install tslint
    ​​​Working Folder: <Top Directory>
    Npm Command: install
    Arguments: -g tslint typescript

    Command Line - Check the version ​​​(Useful to determine rule discrepancies across builds)
    Name​: Check tslint version
    Tool: tslint
    Arguments: -v

    Command Line - Builds a default configuration file for the build (Without it issues can differ between build and development environment
    Name​: Create tslint config file
    Tool: tslint
    Arguments: --init

    Command Line - Run tslint, force is required to stop the build from crashing (TSLint will return and exit code of 1 regardless of if issues exist)
    Name​: ​Run tslint
    Tool:​ TSLint
    Arguments: --force <Solution Directory>/**/*.ts{,x}

    If your build is being hosted, then the config file must be reloaded every time. If your build is running on premises, the config file will attempt to load over the existing one and break the build.
    If this is the case, just add a step to delete your config file after the scan is complete.​

    VSO-RemoveConfig.pngFigure: Command line​ s​​​tep to remove the config file (tslint.json) after the linter has run


    Command Line - Remove the tslint config file, as it will break future scan if the build is on premises if a config file already exists and an attempt to add another one is made.
    ​​​Name​: ​Remove tslint config
    ​Tool:​ del
    Arguments: tslint.json​

    Once complete, save the build definition and run the build.​
    Then check the build is successful.
    If the build fails (due to errors), these should be corrected in the development environment. 

    ​​​​​​Include "PrimaryBuild" variable

    ​For the purposes of reporting, a unique tag must be added to the build definition which the Code Health steps have been applied to. ​
    This is done with the addition of a variable (Name = PrimaryBuild, Value = true)​

    VSO-AddVariableTag.png
    Figure: Steps to add PrimaryBuild​​ variable to build definition​​​​​​​​​​​​

    Check the build is running without issues

    VSO-Build-Bad-1.png
    Figu​re: Bad Code with a Good Code Health Implementation​ - B​uild broke due to com​​​pile errors. Must fix to proceed.​
    ​​​VSO-Build-Ok-1.png
    ​​​​​​​​​​Figure: Bad Code with a Good Code Health Implementation - ​Successful​​​​ build with warnings. ​These should be reprioritised as errors, or removed​
    ​​​​​​​​VSO-Build-Good-1.png
    ​​​​​​​​​Figure:  Good Code with a Good Code Health Implementation - Successful​ build with ​​​no warnings.


  3. Do you use the Code Health Extensions in Visual Studio?Unpublished

    The code quality standard should extend the Visual Studio Analyser. A wide variety of additional​ analysers can be included via Nuget, the minimum standard should include Roslyn Security Guard, Stylecop.Analysers and TSLint.

    Related Steps to Code Health:​​

    Which Packages to Install​​ ​​in Visual Studio

    Search & Install the NuGet packages:

    ​​
    ​​VS-InstallNuGetPackages.png
    Figure: Steps to install NuGet Pa​ckages


    Issues from these will now be returned in the Visual Studio analyser error list.

    VS-RoslynRules.png
    ​​​​​Figure: New Roslyn Rule issue​​​​s raised in Visual Studio Analyser


    Your goal should be to get the issues in a solution down to zero.
    If you believe the issues being raised are not important, please check the section below which outlines how to change the ruleset.

    Modify Visual Studio​​ Analysis Ruleset

    The goal is to develop a shared ruleset across projects. (Currently this is just the default settings). This will ensure the same standard and quality of code is maintained across all of the company's projects.
    Any project specific rules should be documented in "_Instructions-CodeHealth.docx" which is to be kept in the solution.
    Please also copy the current version number of this rule into the "_Instructions-CodeHealth.docx" in order to track what version your existing solution adheres to.

    ​​​​

    VS-ModifyRules.png​​Figure: Steps to open Visual Studi​​​o Analyser rules customisation page

    Steps to open Analyser customisation page:
    Right Click project > Properties > Code Analysis > Open

    ​​​​VS-ModifyRules2.png​Figure: How to customize rules. By either enabling / disabling rules or packages. Or by modifying the rule severity level.
    ​​VS-ModifyRules3.png
    Figure: How to apply custom ruleset to all projects in a solution​​


  4. Do you use the Code Health Extensions in VS Code?Unpublished

    For lightweight web projects such as Angular, often VS Code is more appropriate than Visual Studio. So make sure your code quality remains consistent with CssLint and TSLint.

    Related Steps to Code Health:

    Which Extensions to Use in VS Code

    For web projects, we advocate the use of CSSLint for css files and TSLint for typescript files. (Why you should be using TypeScript instead of JavaScript )
    Linters for these can be easily added to VS Code via extensions.​
    Simply select the "Extensions" tab, search for "CSSLint" and "TSLint" and click "Install" on each respectively.

    VSCode-Extensions.png
    Figure: Addition of CssLi nt and TSLint to VS Code Project

    If you prefer not to use the Extensions (which are currently a bit out of date). You can install them using npm as normal.
    CssLint (Csslint npm guide)
    TSLint (TSlint npm guide )