Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Automating C# Coding Standards using StyleCop and FxCop


Published on

As organizations grow they usually seek to build a set of coding standards to enforce uniformity and increase the maintainability of their code base. Unfortunately, this often creates a lot of churn in the code review process for simple style issues. This presentation was a session I gave at St. Louis Day of .NET 2010 and talks about how to automate many of the coding standards using two readily available tools.

Published in: Technology

Automating C# Coding Standards using StyleCop and FxCop

  1. 1. <ul><li>James Hare – Application Architect, Scottrade </li></ul>
  2. 2. What are Coding Standards? <ul><li>A set of rules or guidelines used when writing the source code of a computer program. </li></ul><ul><li>Generally dictates: </li></ul><ul><ul><li>Safety mandates to avoid introducing errors. </li></ul></ul><ul><ul><li>Style mandates to increase maintainability. </li></ul></ul><ul><ul><li>Security mandates to avoid vulnerabilities. </li></ul></ul><ul><ul><li>Efficiency mandates to help increase performance. </li></ul></ul><ul><li>Standards may be enforced through code reviews or may simply be “suggestions”. </li></ul>
  3. 3. Standards: Like or Dislike?
  4. 4. But, Isn’t Programming Art? <ul><li>This always has been an interesting point of contention. </li></ul><ul><ul><li>On one extreme development can be thought of as a work of art and any source that reaches a logically correct result is acceptable and everything else is just “style.” </li></ul></ul><ul><ul><li>The other extreme believes that programming is purely a mechanical process and there is only a limited number of correct answers. </li></ul></ul><ul><ul><li>Which is correct? </li></ul></ul>
  5. 5. Reality Lies In Between <ul><li>It may be more accurate to say developers are more like artisans (crafters) than artists, though containing elements of both. </li></ul><ul><ul><li>An artist has a wide range of forms they can adhere to and much is dependent on the interpretation of the viewer. </li></ul></ul><ul><ul><li>In contrast, artisans tend to construct or design for a purpose, and while there are some elements of style in construction, if it fails to achieve its purpose effectively , it is a failure. </li></ul></ul>
  6. 6. The “Art” of Sorting <ul><li>Take sorting, for example. </li></ul><ul><ul><li>Both Bubble sort and Quick sort are valid sorts on a set of data. </li></ul></ul><ul><ul><li>Bubble sort has a complexity of O(n 2 ) and Quick sort is O(n log n). </li></ul></ul><ul><ul><li>Assuming sorting 1 million elements and each check takes 1 µs, roughly this would be: </li></ul></ul><ul><ul><ul><li>Bubble Sort: 11 days </li></ul></ul></ul><ul><ul><ul><li>Quick Sort: 19 seconds </li></ul></ul></ul><ul><ul><li>Both sort data, but one is clearly more useful. </li></ul></ul>
  7. 7. Standardizing an “Art” <ul><li>While there are many ways to solve a given problem, there should be guidelines for effective construction. </li></ul><ul><li>These guidelines are similar to building codes used in building construction to ensure safety and quality. </li></ul><ul><li>These guidelines form the basis for coding standards and are best compiled from group consensus and industry best practices. </li></ul>
  8. 8. Enforcing Standards <ul><li>Standards should be enforced to promote safety, efficiency, and maintainability. </li></ul><ul><li>Standards can be enforced through Code Reviews, but these tend to be applied with varying levels of adherence. </li></ul><ul><li>It’s much better to attempt to automate as much of your standards as possible so that the code is judged more objectively. </li></ul>
  9. 9. Benefits of Automation <ul><li>Standards are applied objectively since only analyzes the source or assembly. </li></ul><ul><li>Just plain faster than trying to catch standards violations manually. </li></ul><ul><li>Code authors don’t feel personally attacked. </li></ul><ul><li>Frees more reviewer time since won’t have to waste as much time in code reviews. </li></ul><ul><li>Frees more time for developers since code spends less time and iterations in review. </li></ul>
  10. 10. Standards Automation Tools <ul><li>There are two primary tools from Microsoft: </li></ul><ul><ul><li>StyleCop – Analyzes source files to determine if source code is correctly formatted. </li></ul></ul><ul><ul><li>FxCop (Static Code Analysis) – Analyzes assemblies to determine if code is constructed safely and optimally. </li></ul></ul><ul><li>These tools overlap in some of their base rules but both have their strengths. </li></ul><ul><li>Other third party and Microsoft tools exist, but beyond this presentation’s scope. </li></ul>
  11. 11. StyleCop <ul><li>Analyzes source files and not compiled code. </li></ul><ul><li>Great for checking elements such as: </li></ul><ul><ul><li>Spacing </li></ul></ul><ul><ul><li>Comments </li></ul></ul><ul><ul><li>File composition </li></ul></ul><ul><ul><li>Naming </li></ul></ul><ul><li>Cannot easily check type hierarchies or program structure. </li></ul><ul><li>Available at </li></ul>
  12. 12. Configuring StyleCop <ul><li>If you have StyleCop installed, you can have Settings.StyleCop files for each project if you want to vary styles per project. </li></ul><ul><li>Will take the first Settings.StyleCop file it finds from working directory on up the path. </li></ul><ul><li>Default will be the Settings.StyleCop file in c:program filesMicrosoft StyleCop… </li></ul><ul><li>Various configurations can make harder to enforce uniform rules, though, so use with caution. </li></ul>
  13. 13. Configuring StyleCop <ul><li>You can configure which base rules you want active by using StyleCopSettingsEditor.exe. </li></ul><ul><li>Let’s take a minute to look at the rules… </li></ul>
  14. 14. Configuring StyleCop <ul><li>You can also get to StyleCop settings in Visual Studio directly by right-clicking a project. </li></ul><ul><li>This creates local copy of rules, use cautiously. </li></ul>
  15. 15. Running StyleCop <ul><li>You can run StyleCop from VS or MSBuild. </li></ul><ul><li>Has no native command-line interface, but one exists at sourceforge called StyleCopCmd . </li></ul>
  16. 16. StyleCop Results <ul><li>Shows in Error List window, can turn on “Warnings as Errors” in VS if you want to break builds on violations. </li></ul>
  17. 17. Suppressing a Rule <ul><li>Most rules are good all the time, sometimes not. </li></ul>
  18. 18. On Suppressing Rules <ul><li>It’s better to keep a rule even if it only applies 95% of the time and force developers to suppress the rule for the one-off exceptions. </li></ul><ul><li>This puts a SuppressMessage attribute in code which must be justified and prevents viewing the exception to the rule as a precedent for ignoring the rule. </li></ul><ul><li>If code reviewer disagrees, can be debated. </li></ul><ul><li>Turning off rules should be avoided unless the rule is invalid most or all of the time. </li></ul>
  19. 19. Custom StyleCop Rules <ul><li>StyleCop rules are fairly easy to write. </li></ul><ul><li>Create class library that references the StyleCop assemblies: </li></ul><ul><ul><li>Located in c:program filesMicrosoft StyleCop… </li></ul></ul><ul><ul><ul><li>Microsoft.StyleCop.dll </li></ul></ul></ul><ul><ul><ul><li>Microsoft.StyleCop.Csharp.dll </li></ul></ul></ul><ul><li>Add a CS (C# source file) for new analyzer. </li></ul><ul><li>Add an XML file for rule configuration. </li></ul>
  20. 20. Custom StyleCop Rules <ul><li>In the CS file, create an analyzer that inherits from SourceAnalyzer and has class attribute also named SourceAnalyzer for C# files.s </li></ul>
  21. 21. Custom StyleCop Rules <ul><li>In the CS file, override AnalyzeDocument and perform your checks. </li></ul>
  22. 22. Custom StyleCop Rules <ul><li>When you see your violation, call the method AddViolation and give it a rule name and args: </li></ul>
  23. 23. Custom Style Cop Rules <ul><li>Then, in the XML file, define the rule and message. Make sure XML file has same name as class name and is Embedded Resource. </li></ul>
  24. 24. Custom StyleCop Rules <ul><li>Then, build the custom assembly. </li></ul><ul><li>Place custom assembly in: </li></ul><ul><ul><li>C:Program FilesMicrosoft StyleCop … </li></ul></ul><ul><li>You should now see custom rules in the StyleCopSettingsEditor. </li></ul><ul><li>If you don’t see custom rules, check that the XML file: </li></ul><ul><ul><li>Is an embedded resource </li></ul></ul><ul><ul><li>Has same filename as the class name (minus extensions) </li></ul></ul><ul><li>Let’s look at the code more closely… </li></ul>
  25. 25. StyleCop for ReSharper <ul><li>JetBrains’s ReSharper is an Visual Studio IDE plug-in that adds a lot of refactoring and aids. </li></ul><ul><li>StyleCop for ReSharper is a ReSharper plug-in that allows for dynamic checking of StyleCop rules as you type. </li></ul><ul><li>Will highlight rule violations with squiggle just like other ReSharper hints. </li></ul><ul><li> </li></ul><ul><li>Let’s look at how this appears in the IDE. </li></ul>
  26. 26. FxCop (aka VS Code Analysis) <ul><li>Great for checking elements such as: </li></ul><ul><ul><li>Non-spacing style issues (naming, etc). </li></ul></ul><ul><ul><li>Code safety and performance issues </li></ul></ul><ul><ul><li>Type hierarchy issues </li></ul></ul><ul><ul><li>Analysis of database objects </li></ul></ul><ul><li>Cannot check source style such as spacing. </li></ul><ul><li>Already baked into Visual Studio 2008/10. </li></ul><ul><li>Can also be used as a stand-alone. </li></ul>
  27. 27. Running FxCop Stand-Alone <ul><li>Start  Programs  Microsoft FxCop </li></ul><ul><li>Create new project, add targets, and Analyze! </li></ul>
  28. 28. Running FxCop From Visual Studio <ul><li>Right click on project or solution and choose Run Code Analysis: </li></ul><ul><li>Let’s look at an example analysis. </li></ul>
  29. 29. Suppressing FxCop Errors <ul><li>Just like in StyleCop, you can suppress one-off exceptions to the rules. </li></ul><ul><li>Can insert manually or automatically from the error list in Visual Studio. </li></ul>
  30. 30. Custom FxCop Rules <ul><li>Create a Class Library in Visual Studio. </li></ul><ul><li>Add references to FxCop assemblies: </li></ul><ul><ul><li>From C:Program FilesMicrosoft FxCop… </li></ul></ul><ul><ul><ul><li>FxCopCommon.dll </li></ul></ul></ul><ul><ul><ul><li>FxCopSdk.dll </li></ul></ul></ul><ul><ul><ul><li>Microsoft.Cci.dll </li></ul></ul></ul><ul><ul><ul><li>Microsoft.VisualStudio.CodeAnalysis </li></ul></ul></ul><ul><li>Add a CS file for the new rule. </li></ul><ul><li>Add an XML file for the rule definition. </li></ul>
  31. 31. Custom FxCop Rules <ul><li>In CS file create class that inherits from BaseIntrospectionRule : </li></ul>
  32. 32. Custom FxCop Rules <ul><li>In CS File, override Check to check rule. </li></ul>
  33. 33. Custom FxCop Rule <ul><li>XML file is Embedded and contains rule detail: </li></ul><ul><li>Remember filename must be same as passed to base constructor of BaseIntrospectionRule. </li></ul>
  34. 34. Custom FxCop Rules <ul><li>To use custom rule, use CTRL+R or Project  Add Rules in FxCop. </li></ul><ul><li>You can verify by clicking on rules tab: </li></ul>
  35. 35. Summary <ul><li>Automating code standards can be very useful for getting rid of a lot of the “noise” in code reviews and allowing reviewers to concentrate on logic bugs. </li></ul><ul><li>Automated code standards take the personal side out of enforcing style, safety, and performance. </li></ul><ul><li>Custom rules can be used in FxCop and StyleCop to allow for your own rules. </li></ul>
  36. 36. Questions? <ul><li>Blog: </li></ul><ul><ul><li> </li></ul></ul><ul><li>Email: </li></ul><ul><ul><li>[email_address] </li></ul></ul><ul><li>Twitter: </li></ul><ul><ul><li> </li></ul></ul>