CodeIt.Right Documentation

CodeIt.Right

Code Quality Analysis, Automated Code Review and Refactoring

CodeIt.Right provides a fast, automated way to ensure that your source code adheres to (your) predefined design and style guidelines as well as best coding practices. We take static code quality analysis to the next level by enabling rule violations to be automatically refactored into conforming code. CodeIt.Right helps to improve your software quality, ensure code correctness, find issues early and resolve them quickly.

CodeIt.Right enables you to finally enforce the Team Standards you talk about but only ever do after lots of fighting!

  • Getting Started
  • Tutorials and Resources
  • Release Notes
  • Rule Library documentation
  • Support

Benefits

  • Produce quality code
  • Easily enforce coding guidelines within your team(s)
  • Identify potential issues earlier in development cycle
  • Automatic code reviews
  • With a push of a button get violations fixed instead of just having it nag you about them
  • Big productivity boost by finding issues and automatically resolving them
  • Save time - simply write your code and use CodeIt.Right to identify issues with naming, design, performance, etc
  • Use it as educational tool for those who are new to the .NET Framework or the .NET Design Guidelines
  • more...

Feature Highlights

  • Microsoft .NET Guidelines and best practices - right out of the box
  • Auto correct violations - our rules are smart enough to offer options to automatically correct violation for you
  • Automagical Refactoring to Patterns - find pitfalls and automatically correct coding patterns (e.g. ISerializable, Dispose/Finalize and more)
  • Command line version - yes, we support Continuous Integration!
  • Violation Report Export options
  • Reporting, Pivot View of your solution
  • Custom Rules, Powerful API - develop own rules using SDK
  • Multiple profiles - group them the way you want and quickly switch between
  • Exclude violations - suppress the noise and focus on what's important to you
  • Safely Undo/Redo the changes
  • more...

© 2002-2019 SubMain. All rights reserved.
Designated trademarks and brands are the property of their respective owners.


CodeIt.Right Evaluation Guide

For the most current version of this page please see CodeIt.Right Evaluation Guide.

Part 1: Get a feel for it - Key features of CodeIt.Right
  • What is CodeIt.Right?
  • Profiles
  • Instant Code Review
  • OnDemand Code Review
  • Violations Report
  • Rules and Rule Instances
  • Check-In Policy (EE)
  • Build Process Integration
  • Reporting
  • Metrics
  • Generate Guidelines Document
Part 2: Try it Out - Suggestions for features you can try
  • Start/Stop Instant Review
  • Run an OnDemand Review
  • View an individual violation
  • Correct a violation
  • Correct multiple violations
  • Undo corrections
  • Adjust Severity Thresholds
  • Export a Violations Report
  • Create a Pivot View Report
  • Create a Metrics Report
  • Edit an existing profile
  • Create a new profile
  • Publish a profile
  • Create a Custom Rule
  • Extend an Existing Rule
  • Generate Guidelines Document
Part 3: Get back to us - Questions, Comments, Need more time?
  • Contact Information
  • Request a Quote
  • Need more time to evaluate?
  • Resources Summary


Tutorials and Resources

  • Overview video - 3 minute CodeIt.Right introduction
  • Getting Started and Evaluation Guide
  • CodeIt.Right 101 - Profiles, Rules, Rule Instances and Reports
  • Tutorial: Creating Custom Rules
  • Tutorial: Extending Existing Rules
  • CodeItRight.Cmd.exe Command Line Options
  • (Enteprise) Check-In Policy Integration - check only clean code back into source control
  • (Enteprise) Publishing Custom Configured Coding Standards to Your Team
  • More Tutorials and Resources...

For additional tutorials, please see the Tutorials and Resources page online.


What's New in CodeIt.Right

Note to CodeIt.Right v3.x users: Your v3 license code will not work with the recently released v2109. We have sent out the v2019 license codes to users active Software Assurance subscription. If you have not received or misplaced your new license, you can retrieve it using the My Account page.

What's new in v2019

  • VS2019 support
  • Async extension loading in VS2017 and VS2019
  • Support for the C# 7.2 and VB 2017 changes
  • FIPS compliant encryption

Detailed changes by build:

  • Build 2019.1.19180 (Jun 29, 2019) - v2019 Release

    • VS2019 support and Async extension loading.

    • Added: Support for Visual Studio 2019
    • Added: Visual Studio integration - migrated to Async support with background loading enabled. This minimizes the CodeIt.Right load in VS2017, VS2019, and on startup.
    • Added: Support for the C# 7.2 and VB 2017 language changed
    • Added: CodeIt.Right is now using FIPS compliant encryption
    • Resolved: CodeIt.Right CMD utilities license issue fixed
    • Resolved: TFS policy now works correctly in VS2017 and VS2019
    • Resolved: CodeIt.Right is no longer disabling VS built-in tooltips when Visual Studio is in the debug mode
    • Resolved: Automatic update check no longer runs when Visual Studio is in the debug mode
    • Added: /outSummary switch to the CodeIt.Right CMD utility - defines the output path/name for the Summary Report HTML file
    • Added: /UserDocumentsFolder switch to the CodeIt.Right CMD utility - defines path to the Documents folder when different from the default
    • Added: BlankLine property to XML Comment in the TypesAndMembersShouldHaveXmlComments rule
    • Resolved: Issue when loading some of the excluded violation the command line utility
    • Resolved: Issue with the AsyncMethodShouldReturnTask rule
    • Resolved: Handle the StackOverflowException exception occurring on rare occasion in the RemoveUnusedLocals rule
    • Resolved: Issue in the SetLocaleForDataTypes rule when initializing Local in curly brackets after the constructor
    • Resolved: Issue in the SpecifyCultureInfo rule when adding CultureInfo into an interpolated string
    • Resolved: Issue in the SpecifyCultureInfo rule when adding IFormatProvider to Enum.ToString()
  • Build 3.3.18070 (Mar 9, 2018) - Compatibility Release

    • VS2017 v15.6 compatibility update.

    • Resolved: Fixed VS2017 Update 15.6 compatibility issue - the "Visual Studio still loading the project." message
  • Build 3.2.17340 (Dec 7, 2017) - Performance Release

    • VS2017 performance improvements, minor enhancements and bug fixes.

    • Resolved: Improved performance loading solutions in VS2017 by moving it to an async thread
    • Resolved: Code quality hints now showing up correctly in VS2010-2015 Editor
    • Resolved: DoNotCatchSpecifiedExceptionTypes rule in VB now works correctly when the Catch clause has a When section
    • Resolved: Exception when "Analyze checked out files" is ON and a source file renamed or removed from disk
    • Resolved: AsyncMethodShouldHaveAwaitStatement rule no longer shows a violation when the await statement is on right side of assignment
    • Resolved: Now donâ€™t run new version check when in Debug mode
    • Added: Support for StyleCop VSIX v5.0
  • Build 3.1.17130 (May 10, 2017) - Maintenance Release
    • Resolved: Improved VSIX installation
  • Build 3.1.17100 (April 10, 2017) - Minor Feature Release
    • Added: Support for VS2017 RTM
    • Added: CodeIt.Right is now also available as VSIX for VS2017 (Standard and Personal editions)
    • Resolved: CodeIt.Right integration with StyleCop v4.7.55 now works as expected
    • Resolved: Issue with one of the 'rename' fixes for the IdentifiersShouldNotContainSpecifiedChars violations
  • Build 3.0.16360 (Dec 26, 2016) - v3.0 Release
    • Resolved: Issue with SetLocaleForDataTypes rule
  • Build 3.0.16320 (Nov 15, 2016) - v3.0 Release Candidate
    • Added: VS2017 RC integration
    • Added: Summary report view
    • Added: Option to display Summary report after analysis instead of the violation report
    • Added: File Filtering options feature
      • Analyze files modified: Today/This Week/Last 2 Weeks/This month
      • Analyze files modified since: specific date
      • Analyze opened files
      • Analyze checked out files
      • Analyze only specified files: files matching a list of patterns
    • Added: New menu items - Getting Started Tutorial and Tutorials and Resources
    • Added: Edit buttons in Options - Solution Ignore List and Options - Exclude Region
    • Added: Test button in Options - Solution Ignore List
    • Resolved: Improved VS2015 setup
    • Resolved: Fixed unhandled exception when adding custom rule or creating custom rule project
    • Resolved: "file not part of solution" warning when loading some projects
    • Resolved: Issue documenting VB properties without specifying get/set accessors
    • Resolved: Issue when export CodeIt.Right violation report did not take into account the severity threshold value
    • Resolved: Issue renaming a project under Solution Folder
    • Resolved: Issue displaying Rule Update window when shared dictionary file is in the Shared Folder
    • Resolved: Statistics tab grid not displaying scrollbars
    • Resolved: Fixed auto-correction (mark as 'private') for the ReviewVisibleEventHandlers rule
    • Resolved: Error in ErrorList window when running the Correct Checked action
    • Changed: Renamed Browse button to Change in Options - General - User folder path
  • Build 3.0.16070 (Mar 10, 2016) - v3.0 Beta
    • Added: VS2015 Update 2 support
    • Fixed: Support for ASP.NET 5/ASP.NET Core 1.0 solutions
    • Added: Fresh look and feel for Violations Report and Editor violation markers
    • Changed: Start Analysis is now Review Code
    • Added: Review Code - Analyze Open Files command - analyze only the files opened in Visual Studio tabs
    • Added: Review Code - Analyze Checked Out Files command - analyze only files that that are checked out from the source control
    • Added: Violations Report - result filtering options - only opened files, only checked out files, only files modified after specific date
    • Added: Profile Editor - advanced rule filtering by rule id, title, name, severity, scope, target, and programming language
    • Added: Profile Editor - show totals for the profile rules - total, active, and filtered
    • Added: 6 new Globalization rules
      • DoNotPassLiteralsAsLocalizedParameters (Globalization)
      • NormalizeStringsToUppercase (Globalization)
      • DoNotHardcodeLocaleSpecificStrings (Globalization)
      • UseOrdinalStringComparison (Globalization) w/ auto-correct
      • SpecifyMarshalingForPInvokeStringArguments (Globalization) w/ auto-correct
      • SetLocaleForDataTypes (Globalization) w/ auto-correct
    • Fixed: Issue with not saving user folder location when it is changed form a network location to a local folder
    • Added: Option in Team Configuration Module to sync modified files and rule libraries from the Shared Folder - Options -> Auto-Update
    • Added: Setting to keep OnDemand and Instant Review profiles in sync - Options -> Instant Review
    • Added: Violations Report context menu item to reset grid layout to the default
    • Fixed: Violations Report - the Severity column sorting now works as expected
    • Added: Current profile name is now saved in the CRData file and selected when the solution is open again
    • Added: Registry key allowing to move the CodeIt.Right product folder away from My Documents
    • Fixed: Spell checker now ignores URLs
    • Added: <include> section for the CRData file for CodeIt.Right.Cmd. When the section is defined, CodeIt.Right.Cmd only analyzes the files and file patterns defined within the section
    • Fixed: PathTooLongException when loading solution/project
    • Fixed: Issue in the SpecifyStringComparison and SpecifyCultureInfo rules with methods that have named arguments
    • Fixed: New version notification - the download URL is now pointing at the correct edition download page
    • Changed: Profile Editor - the guidelines document created via the Generate Document command - changed the "CodeIt.Right Profile Template" to "CodeIt.Right Coding Guidelines Document Template"
    • Changed: Profile Editor - Save As now saves current profile including unsaved changes
    • Fixed: Profile Editor - improved adding rules with multiple categories
    • Added: New CodeIt.Right.Cmd parameter /dateAfter forces CodeIt.Right to analyze only the source code file modified after the specified date
    • Added: New /UnlockCode parameter to the SubMain.CodeItRight.Registration utility
    • Added: New Jenkins Integration plugin
    • Fixed: Issue with auto-fix for rule AsyncMethodShouldReturnTask
    • Added: Ability to change user folder from User\Documents
    • Added: Setting to turn logging off - Options -> General -> Enable Error Log
    • Added: Ignore Files by Pattern to Solution Ignore list - new feature allows to list whole folders or
    • Changed: The batch correction actions are now hidden by default
    • Added: Option to show batch correction action options in the Violations Report
    • Added: Most most every CodeIt.Right action/command is listed in the Visual Studio list to assign a keyboard shortcut
    • Added: Support for SQL Server projects
    • Added: devenv /setup logging for easier troubleshooting
    • Added: CurrentUICulture and InstalledUICulture to the correction options list in SpecifyCultureInfo globalization rule
    • Fixed: The warning/error growl notification is no longer taking focus from the Visual Studio editor
    • Fixed: Issue with SpecifyCultureInfo globalization rule to analyzing nullable type ToString method calls
    • Fixed: Resolved issue when CodeIt.Right toolbar is hidden in Visual Studio it used to show up again after VS is restarted

Version v2.7

  • Support for VS2013 Update 3
  • Improved compatibility with Shared/Universal App projects
  • Exported Violation Report enhancements
  • Other improvements and fixes

Detailed changes by build:

  • Build 2.7.14268 (Sep 25, 2014) - v2.7 Release
    • Added: VS2013 Update 3 support
    • Added: Exported Violation Report now includes profile name, severity threshold, version of CodeIt.Right and duration of the analysis
    • Added: Exported Violation Report now includes information about Excluded Projects, Files, Rules and Violations
    • Added: When auto-correction fails, CodeIt.Right shows a Growl notification with the reason refactoring could not be completed
    • Added: Command line version console output shows profile name as well as number of excluded projects, files, rules and violations
    • Changed: Exported Violation Report version changed from "1.0" to "2.0"
    • Fixed: Issues with Shared/Universal App projects
    • Fixed: Issue with Visual Studio hanging up when loading C++ project in VS2013 Update 3
    • Fixed: Issue displaying description in Violation Details of the Instant Code Review
    • Fixed: Issue with resolving references in command line version
    • Fixed: Issue with command line version not ignoring some of excluded violations
    • Fixed: Other fixes

Version 2.6

  • Support for SharedProject introduced in VS2013 Update 2
  • In v2.5 we added StyleCop integration into CodeIt.Right analysis. In v2.6 we are adding 93 auto-fix refactorings for StyleCop violations and currently covering automatic correction for 85% of StyleCop based violations (143 out of 164)
  • Improved performance of the built-in profiles by turning off few processing intensive optional rules. You can turn them back on by creating custom profiles
  • Tweaked a number of rules and instances for better conformance to Microsoft Design Guidelines
  • SuppressMessage improvements for local variables

Detailed changes by build:

  • Build 2.6.14124 (May 4, 2014) - v2.6 Release
    • Added: Support for SharedProject introduced in VS2013 Update 2
    • Added: SuppressMessage Scope to exclude local variables (in code) from analysis
    • Added: New auto-fixes for 8 StyleCop Maintainability rules (total 10 out of 13)
    • Added: New auto-fixes for 18 StyleCop Readability rules (total 22 out of 26)
    • Added: New auto-fixes for 19 StyleCop Layout rules (total 19 out of 19)
    • Added: New auto-fix for 1 StyleCop Naming rule (total 11 out of 11)
    • Added: New auto-fixes for 39 StyleCop Documentation rules (total 45 out of 51)
    • Added: New auto-fixes for 8 StyleCop Ordering rules (total 8 out of 16)
    • Added: Modified rule FieldIdentifiersShouldBeCasedCorrectly (Naming) to be StyleCop compliant
    • Added: Rule instance "Variable name must not have "m_" prefix" (Naming) to built-in profiles
    • Added: Rule instance "Variable name must not have "s_" prefix" (Naming) to built-in profiles
    • Added: Rule instance "Field names should not contain underscores" (Naming) to built-in profiles. This instance is inactive (unchecked) and will not trigger violations unless you turn it on
    • Added: Configuration property ProcessEventHandlers to rule IdentifiersShouldBeCasedCorrectly - enables processing event handler methods separately
    • Added: Rule instance "Local constant identifiers should be cased correctly" (Naming) to built-in profiles - with Pascal casing default for local contants. This instance is inactive (unchecked) and will not trigger violations unless you turn it on
    • Changed: Rule instance "Local variable identifiers should be cased correctly" (Naming) - removed LocalConstant from the list of targets
    • Changed: Rule RemoveUnusedLocals is now inactive in the "Microsoft Guidelines" built-in profile but still active in the Instant Review built-in profile
    • Changed: Rule RemoveUnusedPrivateMethods is now inactive in the "Microsoft Guidelines" built-in profile
    • Changed: Rule RemoveUnusedParameters is not inactive in the built-in profiles.
    • Fixed: Issue with rule AsyncMethodShouldHaveAwaitStatement
    • Fixed: Issue with rule AvoidSingleLineIfStatement in VB.NET
    • Fixed: Misspelling in rule ProvideDefaultForEachSwitchStatement rule
    • Fixed: Issue with rule RemoveUnusedLocals
    • Fixed: Issue renaming WebMethod parameters
    • Fixed: IXamlTag.Region now has correct value

Version 2.5

  • Official Visual Studio 2013 support
  • New plugin integrates StyleCop into CodeIt.Right analysis
    • Run StyleCop rules as part of CodeIt.Right Analysis
    • CodeIt.Right auto-corrections for StyleCop rules
    • Exclude StyleCop rules or violations
    • On Demand Analysis - include StyleCop violations into CodeIt.Right Violations Report
    • Instant Code Review - include StyleCop violations as part of CodeIt.Right Violations Report
    • Instant Code Review - show StyleCop violations in VS Editor and violations bar
  • Revamped XSLT stylesheet for Violations Report Export to XML
  • Auto-corrections in Instant Code Review mode now show "growl" type warnings
  • CRDATA file format change - your existing CRDATA files will convert automatically
  • Async loading of saved violation reports for improved performance

Detailed changes by build:

  • Build 2.5.13316 (Nov 12, 2013) - v2.5 Release
    • Added: Official Visual Studio 2013 support
    • Added: OnDemand Analysis: run StyleCop rules and StyleCop auto-corrections
    • Added: Instant Code Review: run StyleCop rules and StyleCop auto-corrections
    • Added: StyleCop Spacing Rules corrections
    • Added: On Demand Analysis progress window: added "Found violations" counter
    • Added: Growl type warnings for auto-corrections in Instant Code Review mode
    • Added: Offline activation: new button that generates XML in Notepad for computers without email client that are also behind firewall
    • Changed: Revamped XSLT stylesheet for Violations Report Export to XML
    • Changed: Refreshed Severity icons
    • Changed: Modified CRDATA file format from binary to XML with some binary. Your existing CRDATA files will convert automatically
    • Changed: Saved violation report is now loaded asynchronously on Visual Studio load
    • Fixed: Instant Review no longer analyzes file more than once after correction undo
    • Fixed: Run Instant Review for all opened VS Editor windows when user changes Instant Review profile profile
    • Fixed: NullReferenceException issue with the AwaitForTaskCompletion rule
    • Fixed: AssembliesShouldHaveValidStrongNames rule issue on machine with no VS installed
    • Fixed: Severity icons now appearing in the violations report grid
    • Fixed: Instant Review can't run correction violation when code element context has changed
    • Fixed: Issue wit references unloading slow in VS when CodeIt.Right installed
    • Fixed: Excluded violations now always loading after restarting VS
    • Fixed: Resolved - in some cases Instant Review violation detail windows used to take focus from VS Editor

Version 2.0

  • New (!) Instant Code Review feature - allows to run select set of rules in the background and get real-time code issues feedback to developers in the Visual Studio Editor. Highlights code element that raised violation, shows complete list of file issues in the right violations bar (next to the scrollbar). Each issue shows description, offers auto-refactoring options, option to ignore (exclude) the violation. The feature can be turned on/off with a single click, supports multiple user configured profiles which can be switched from within right margin violations bar context menu.
  • Added support for Visual Studio 11 Developer Preview
  • Copy Rule feature - Enables to copy existing rule instance and reconfigure it under a new name
  • Added Multiselect in Violations Report - helps when need to exclude or copy many violations at once
  • Added SDK support for multiple categories for a single rule. No breaking changes, new SDK is still compatible with your existing custom rules.
  • Added XAML Parser - XAML Parser enables creation of Silverlight/WPF specific rules
  • Added 8 new Silverlight/WPF/XAML rules
    • Assign object should define To member (Xaml)
    • Assign object should define Value member (Xaml)
    • ControlTemplate object should define TargetType member (Xaml)
    • Delay object should define Duration member (Xaml)
    • Parallel object should define Branches member (Xaml)
    • Sequence object should define Activities member (Xaml)
    • Xaml file should be well-formed (Xaml)
    • Property should be set once (Xaml)
  • Added 27 new ASP.NET/Security rules
    • Avoid setting the AutoPostBack property to True (AspNet;Security)
    • Always define a global error handler (AspNet;Security)
    • EnableEventValidation should be True (AspNet;Security)
    • ValidateRequest should be True (AspNet;Security)
    • ViewStateEncryptionMode should be Always (AspNet;Security)
    • EnableViewStateMac should be True (AspNet;Security)
    • EnableViewState should be True (AspNet;Security)
    • Compilation Debug should be False in web.config (AspNet;Security)
    • Do not disable custom errors in web.config (AspNet;Security)
    • Form authentication Protection should be All in web.config (AspNet;Security)
    • Disable form authentication EnableCrossAppRedirects in web.config (AspNet;Security)
    • Form authentication RequireSSL should be True in web.config (AspNet;Security)
    • Http cookies HttpOnlyCookies should be True in web.config (AspNet;Security)
    • Http cookies RequireSSL should be True in web.config (AspNet;Security)
    • Trace should be disabled in web.config (AspNet;Security)
    • Role manager CookieProtection should be All in web.config (AspNet;Security)
    • Role manager CookieRequireSSL should be True in web.config (AspNet;Security)
    • Role manager CookieSlidingExpiration should be False in web.config (AspNet;Security)
    • Page EnableViewStateMac should be True in web.config (AspNet;Security)
    • Page EnableEventValidation should be True in web.config (AspNet;Security)
    • Page ValidateRequest should be True in web.config (AspNet;Security)
    • Page ViewStateEncryptionMode should be Always in web.config (AspNet;Security)
    • Http runtime EnableHeaderChecking should be True in web.config (AspNet;Security)
    • Custom errors DefaultRedirect should be specified in web.config (AspNet;Security)
    • Form authentication should not contain credentials in web.config (AspNet;Security)
    • Form authentication SlidingExpiration should be False in web.config (AspNet;Security)
    • Disable anonymous access in web.config (AspNet;Security)
    • Enable request validation in MVC controller action (AspNet;Security)
    • Use ValidateAntiforgeryTokenAttribute to protect against potential CSRF attacks in MVC controller action (AspNet;Security)
  • New rule - Remove Unused Classes
  • (EE) Option to publish custom dictionary - Enterprise Edition introduces Shared dictionary (in addition to User dictionary). Shared dictionary can be published and distributed to all Analysis Module users
  • (EE)(Cmd) Added Auto Update parameter /RuleUpdate to pull published rules and profiles to a build server in a command line version only ("no Visual Studio") setup
  • (EE)(Cmd) Added "Project Configuration" parameter /projectConfiguration
  • (EE)(Cmd) Added "MailSubjectSuffix" for email in command line version
  • (EE)(Cmd) Email metrics report - enables command line version to distribute metrics report output via email; /sendto parameter now works with the /metrics parameter
  • (EE) Improved handing of non-unique RuleIds in Statistics.db - you will no longer get unhandled error dialog if use existing RuleId in your custom rule. Still a unique (GUID-based recommended) RuleId is required for custom rules
  • Profile Editor - Added filter for selected/unselected rules
  • Added Option to Require Exclude Comments. The date/time stamped comments show up within the Excluded -> Violations tab
  • Improved Auto Update - it no longer requires Admin permission to check for an update. It will only ask to elevate permissions if there is update found and you choose to install it.
  • Improved Auto Update mechanism - Introduce Update frequency option. For SE, PE and EE TCM choices are Manual/Every Month/Every Week(default), for EE AM Manual/Every Month/Every Week(default)/Every Day/Every Hour
  • Added Offline License Activation option - launch it from Registration Window or use separate EXE version
  • Improved VS Debug windows (for the IDE version) and console (for the Cmd version) output - it now displays accurate numbers of issues found without excluded violations
  • Added option to "hard" exclude file/project. In the regular ("soft") exclude scenario, CodeIt.Right will still analyze the file/project and will show number of violations within the Excluded tab, not in the violations report. With "hard" exclude the file/project will be completely ignored during the analysis. Use "hard" excludes with caution - it is useful for CodeGen code that cannot be excluded using GeneratedCode attribute or regions but not recommended for regular source code as this may result in missed violations.
  • Improved ASP.NET MVC support - now fully compatible with ASP.NET MVC 3 syntax
  • Improved Exclude file/project - these now store relative path instead of absolute - helps in a team environment when solution source folders differ on developer workstations
  • Tweaked UX and refreshed icons
  • Added Search tab in Help file
  • Added manifest to setup file - no more "The program did not install properly" messages on Windows 7
  • Note for Standard Edition users - we have added "Standard" edition name to all folder locations (Program Files, My Documents, etc) and registry keys
  • Changed Show Analysis Window to Show Violations Report and added Show Report toolbar button
  • Added new product edition - Personal Edition - includes all features of Standard Edition and Code Metrics from Enterprise Edition. Priced for personal use, one license max, nontransferable
  • Number of existing rule fixes

Version 1.9.10111

  • Major performance improvements throughout the rule base
  • Added support for GlobalSuppressions - syntax is the same as the VSTS GlobalSuppressions file. This new feature is supported in both Standard and Enterprise editions.
  • SuppressMessage attribute for class now applied to all member of the class (see example at the bottom of the post)
  • New Rules:
    • Avoid the Page.DataBind method (AspNet)
    • Avoid the DataBinder.Eval method (AspNet)
    • Do not use SaveAs method to store uploaded files (AspNet)
    • Always define a global error handler (AspNet)
    • Do not disable custom errors (AspNet)
    • Avoid setting the AutoPostBack property to True (AspNet)
    • Interface methods should be callable by child types (Design)
    • Remove unused parameters (Usage)
  • Corrected download redirect link in the Enterprise Edition when new version is available. In the past versions it would incorrectly open the Standard Edition download page
  • Fixed Encapsulate Field refactoring issue
  • Other fixes for the reported issues

The following code sample on how class level SuppressMessage attribute excludes TypesAndMembersShouldHaveXmlComments rule for the class and all its members (bullet #3 above):

[SuppressMessage("SubMain.CodeItRight.Rules.General", "GE00005:TypesAndMembersShouldHaveXmlComments")]
public class MyUndocumentedClass
{
    public void MyUndocumentedMethod1{}
    public void MyUndocumentedMethod2{}
}

Version 1.9.09355

  • New Merge Profiles feature allows to compare and merge user configured profiles
  • (EE) New "Add WorkItem" feature - create TFS WorkItem from a violation
  • (EE)(Cmd) Added /metrics parameter to the command line utility to generate XML output for three metrics reports – "Member", "Type" and "Code"
  • (EE)(Cmd) Added /sendto parameter to the command line utility - send the violation/metrics output via email
  • CodeIt.Right can now be loaded/unloaded in the menu and Add-In Manager
  • (EE) Build server setup doesn't require Visual Studio on the build machine anymore
  • (EE) "Built-in profile" option now is not selectable in the Analysis Module when one or more custom profiles deployed via Team Configuration Module
  • New Rules:
    • Specify CultureInfo (Globalization)
    • Specify IFormatProvider (Globalization)
    • Specify StringComparison (Globalization)
    • (EE) Avoid excessive complexity (Maintainability)
    • (EE) Avoid excessive inheritance (Maintainability)
    • Do not use deprecated properties of Response object (AspNet)
  • Fixed a number of bugs in the application and the rules...

Version 1.8

  • Now compatible with VS2010 Beta 2, VS2008, VS2005 and VS2003
  • Finally complete ASP.NET support including refactorings in HTML markup.
  • Added Memory Optimization mode – allows to minimize the memory use at slightly lower reduces performance. This allows to solve the "Out of Memory" issue on large solutions.
  • Added Performance tab to the Options window – Best Performance/Memory Optimization.
  • Added new Exclude tab and moved all exclude tabs there
  • All Exclude tabs now support multi-select
  • New option to Exclude a Project
  • Added new "Add" button in Exclude Rule, Exclude File and Exclude Project tabs – the dialogs support multi-select.
  • Profile Editor -> Add Rule dialog has new option Hide Rules in the Profile which removes from the selection the rules that already exist in the selected profile.
  • Profile Editor -> Add Rule dialog has new Quick Search that filters the list for the rules that contain entered substring
    AddRule-QuickSearch
  • Added RuleID to rule help documentation.
  • Product license codes when entered are now activated on the SubMain server.
  • Auto Update wizard now shows Software Assurance & Gold Support subscription expiration date.
  • About window now shows Software Assurance & Gold Support subscription expiration date.
  • All web services – Auto Update, Error Reporting, Statistics and Activation – are now accessed over SSL protected HTTPS connection.
  • Removed Sealed modifier for all built-in rules. This allows for new easier way to extend and customize existing rules by simply overriding specific methods. See Tutorial: Extending Existing Rules for a sample.
  • Addressed issues related to incorrect source file encoding when Byte Order Mark (BOM) attribute was missing.
  • New Rules:
    • Abstract class should have at least one derive class (Design)
    • Interface should have at least one implementation (Design)
    • Project should have AssemblyInfo file (Design)
    • Do not place assembly attributes outside of AssemblyInfo file (Design)
    • Do not include multiple statements on a single line (CodingStyle)
    • Avoid single line If statement (CodingStyle)
    • Do not check for empty strings using Equals (Performance)
    • XML Comments should be spelled correctly (Spelling)
    • Avoid non-public fields in ComVisible value types (Interoperability)
    • Avoid static members in ComVisible types (Interoperability)
    • PInvokes should not be visible (Interoperability)
  • Fixed a number of bugs in the application and the rules...


Rules

This section will guide you through the set of the rule categories.

Click on any of the links below to go directly to the corresponding rule category.

Asp.Net Rules

Async Rules

Coding Style Rules

Design Rules

Exception Handling Rules

General Rules

Globalization Rules

Interoperability Rules

Maintainability Rules

Naming Rules

Performance Rules

Security Rules

Spelling Rules

Usage Rules


Asp.Net Rules

This section will guide you through the set of Asp.Net Rules.

Click on any of the links below to go directly to the corresponding rule.

Always define a global error handler

Avoid the DataBinder.Eval method

Avoid the Page.DataBind method

Avoid setting the AutoPostBack property to True

Compilation Debug should be False in web.config

Custom errors DefaultRedirect should be specified in web.config

Disable anonymous access in web.config

Disable form authentication EnableCrossAppRedirects in web.config

Do not disable custom errors in web.config

Do not use deprecated properties of Response object

Do not use SaveAs method to store uploaded files

Enable request validation in MVC controller action

EnableEventValidation should be True

EnableViewState should be True

EnableViewStateMac should be True

Form authentication Protection should be All in web.config

Form authentication RequireSSL should be True in web.config

Form authentication should not contain credentials in web.config

Form authentication SlidingExpiration should be False in web.config

Http cookies HttpOnlyCookies should be True in web.config

Http cookies RequireSSL should be True in web.config

Http runtime EnableHeaderChecking should be True in web.config

Page EnableEventValidation should be True in web.config

Page EnableViewStateMac should be True in web.config

Page ValidateRequest should be True in web.config

Page ViewStateEncryptionMode should be Always in web.config

Role manager CookieProtection should be All in web.config

Role manager CookieRequireSSL should be True in web.config

Role manager CookieSlidingExpiration should be False in web.config

Trace should be disabled in web.config

Use ValidateAntiforgeryTokenAttribute to protect against potential CSRF attacks in MVC controller action

ValidateRequest should be True

ViewStateEncryptionMode should be Always


Always define a global error handler

Rule ID: AN00006

Problem

Global.asax file does not contain global error handler.

Rule Description

Global error handler in Global.asax file should always be defined. It will allow to recover from an unhandled exception that occured in the current ASP.NET application.

Having a global error handler enables you to implement a common error recovery strategy for the entire application and and saves you from trapping the Error event in each page.

The code inside the Error event handler can access all the usual properties in the Request object, what helps to find the source of the problem, and the methods of the Response object, which allow sending an alternative error message.

Correcting Violations

The rule provides the following auto-correct options:
  • Add global error handler.

Rule Instances

Instances of this rule in the built-in profile:
  • Always define a global error handler.

Example

The following examples show code that implement global error handler.

[Visual Basic]

' Custom error page implemtnation

  Private Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Error

    ' Prepare an error report.
    Response.Clear()
    Response.Write("<h1>An exception has occurred:</h1>")

    ' Display information on the page being processed.
    Response.Write("<b>URL = </b>> & Request.Path & "<br />")
    Response.Write("<b>QueryString = </b>" & Request.QueryString.ToString() & "<p>")
    Response.Write("<b>Error details</b><p>")

    ' Display information on the (real) error that occurred.
    Dim ex As Exception = Server.GetLastError.InnerException
    Dim errMsg As String = Server.HtmlEncode(ex.ToString)
    errMsg = errMsg.Replace(ControlChars.CrLf, "<br />")
    Response.Write(errMsg)
    Response.End()

  End Sub

[C#]

// Custom error page implemtnation

  private void Application_Error(object sender, EventArgs e)
  {
     // Prepare an error report.
     Response.Clear();
     Response.Write("<h1>An exception has occurred:</h1>");

     // Display information on the page being processed.
     Response.Write("<b>URL = </b>" + Request.Path + "<br />");
     Response.Write("<b>QueryString = </b>" + Request.QueryString.ToString() + "<p>");
     Response.Write("<b>Error details</b><p>");

     // Display information on the (real) error that occurred.
     Exception ex = Server.GetLastError().InnerException;
     string errMsg = Server.HtmlEncode(ex.ToString());
     errMsg = errMsg.Replace("\n", "<br />");
     Response.Write(errMsg);
     Response.End();
  }

Related Rules

Do not disable custom errors


Avoid the DataBinder.Eval method

Rule ID: AN00002

Problem

System.Web.UI.DataBinder.Eval method is invoked.

Rule Description

Avoid using System.Web.UI.DataBinder.Eval method. It uses reflection and, therefore, is slower than strong-typed access.

Cast the Container.DataItem object to DataRowView object when binding to a DataSet, DataTable, or DataView, or cast to a DbDataRecord object if you are binding to a DataReader.

Correcting Violations

The rule provides the following auto-correct options:
  • Modify your code manually to cast the Container.DataItem object to a specific object.

Rule Instances

Instances of this rule in the built-in profile:
  • Avoid the DataBinder.Eval method.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

<ItemTemplate>
  <asp:Label runat="server"
    Text='<%# DataBinder.Eval(Container, "DataItem.ProductID") %>'>
  </asp:Label>
</ItemTemplate>

' This is the correct implementation

<ItemTemplate>
  <asp:Label runat="server"
    Text='<%# DirectCast(Container.DataItem, System.Data.DataRowView)("ProductID") %>'>
  </asp:Label>
</ItemTemplate>

[C#]

// This code will trigger the rule violation

<ItemTemplate>
  <asp:Label runat="server"
    Text='<%# DataBinder.Eval(Container, "DataItem.ProductID") %>'>
  </asp:Label>
</ItemTemplate>

// This is the correct implementation

<ItemTemplate>
  <asp:Label runat="server"
    Text='<%# (Container.DataItem as System.Data.DataRowView)["ProductID"] %>'>
  </asp:Label>
</ItemTemplate>


Avoid the Page.DataBind method

Rule ID: AN00003

Problem

Page.DataBind method is invoked.

Rule Description

Avoid Page.DataBind method; instead, invoke the DataBind method for each control that you want to bind to its data source.

The page-level DataBind method must recursively call the DataBind method of all controls on the page.

Correcting Violations

The rule provides the following auto-correct options:
  • Invoke the DataBind method for each control that you want to bind to its data source.

Rule Instances

Instances of this rule in the built-in profile:
  • Avoid the Page.DataBind method.


Avoid setting the AutoPostBack property to True

Rule ID: AN00005

Problem

AutoPostBack property of a server control is set to True.

Rule Description

The AutoPostBack feature relies on client-side JavaScript code; if a Web Forms page contains one or more controls whose AutoPostBack property is set to True and the user has disabled JavaScript support, the user has no means to submit the form unless you also provide one or more button controls.

Correcting Violations

The rule provides the following auto-correct options:
  • Make sure that user can submit form if client-side JavaScript support is disabled.

Rule Instances

Instances of this rule in the built-in profile:
  • Avoid setting the AutoPostBack property to True.


Compilation Debug should be False in web.config

Rule ID: AN00018

Problem

Debug compilation must be disabled in web.config.

Rule Description

Make sure that debug compilation is set to false in web.config. This eliminates potential performance and security issues related to debug code enabled and additional extensive error messages being returned.

This rule is similar to FxCop rule 'DebugCompilationMustBeDisabled', CheckId CA5400

Correcting Violations

The rule provides the following auto-correct options:
  • Set debug attribute value of the compilation element to false in web.config

Rule Instances

Instances of this rule in the built-in profile:
  • Compilation Debug should be False in web.config.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<configuration>
 <system.web>
  <compilation debug="true" />
 </system.web>
</configuration>

<!-- This is the correct implementation -->

<configuration>
 <system.web>
  <compilation debug="false" />
 </system.web>
</configuration>


Custom errors DefaultRedirect should be specified in web.config

Rule ID: AN00010

Problem

Custom error page should be specified in web.config.

Rule Description

Make sure that the CustomErrors section is configured to have a default url for redirecting uses in case of error.

This rule is similar to FxCop rule 'CustomErrorPageShouldBeSpecified', CheckId CA5401

Correcting Violations

The rule provides the following auto-correct options:
  • Modify your code manually to set defaultRedirect attribute of the system.web.customErrors element in web.config

Rule Instances

Instances of this rule in the built-in profile:
  • Custom errors DefaultRedirect should be specified in web.config.

Example

The following example show code that triggers the rule violation.

<!-- This is the correct implementation -->

<configuration>
 <system.web>
  <customErrors mode="On" defaultRedirect="/Error.aspx" />
 </system.web>
</configuration>


Disable anonymous access in web.config

Rule ID: AN00035

Problem

Authorization section in web.config allows anonymous access.

Rule Description

Make sure that web.config authorization section is configured to disallow anonymous access.

This rule is similar to FxCop rule 'AnonymousAccessIsEnabled', CheckId CA5410

Correcting Violations

The rule provides the following auto-correct options:
  • Set users attribute value of the system.web.authorization.deny element to ? in web.config

Rule Instances

Instances of this rule in the built-in profile:
  • Disable anonymous access in web.config.

Example

The following example show code that triggers the rule violation.

<!-- This is the correct implementation -->

<configuration>
 <system.web>
  <authorization>
   <allow users="Kim" />
   <allow users="Admins" />
   <!-- Deny all anonymous users-->
   <deny users="?"/>
  </authorization>
 </system.web>
</configuration>


Disable form authentication EnableCrossAppRedirects in web.config

Rule ID: AN00021

Problem

Form authentication EnableCrossAppRedirects should be disabled in web.config.

Rule Description

Make sure that the system.web.authentication.forms enableCrossAppRedirects is set to false.
The settings indicate if the user should be redirected to another application url after the authentication process. If the setting is false, the authentication process will not allow redirection to another application or host.

This rule is similar to FxCop rule 'EnableCrossAppRedirectsShouldBeTrue', CheckId CA5403

Correcting Violations

The rule provides the following auto-correct options:
  • Set enableCrossAppRedirects attribute value of the system.web.authentication.forms element to false in web.config

Rule Instances

Instances of this rule in the built-in profile:
  • Disable form authentication EnableCrossAppRedirects in web.config.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<configuration>
 <system.web>
  <authentication mode="Forms">
   <forms loginUrl="~/login.aspx" protection="All" requireSSL="true" enableCrossAppRedirects="true" />
  </authentication>
 </system.web>
</configuration>

<!-- This is the correct implementation -->

<configuration>
 <system.web>
  <authentication mode="Forms">
   <forms loginUrl="~/login.aspx" protection="All" requireSSL="true" enableCrossAppRedirects="false" />
  </authentication>
 </system.web>
</configuration>


Do not disable custom errors in web.config

Rule ID: AN00019

Problem

Custom errors should be enabled in web.config.

Rule Description

Make sure that the customErrors mode is set to On or RemoteOnly. This disable detailed error message returned by ASP.NET to remote users.

This rule is similar to FxCop rule 'CustomErrorsModeShouldBeOn', CheckId CA5419

Correcting Violations

The rule provides the following auto-correct options:
  • Set mode attribute value of the customErrors element to On in web.config
  • Set mode attribute value of the customErrors element to RemoteOnly in web.config

Rule Instances

Instances of this rule in the built-in profile:
  • Do not disable custom errors in web.config.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<configuration>
 <system.web>
  <customErrors mode="Off" />
 </system.web>
</configuration>

<!-- This is the correct implementation -->

<configuration>
 <system.web>
  <customErrors mode="On" />
 </system.web>
</configuration>


Do not use deprecated properties of Response object

Rule ID: AN00001

Problem

There is used deprecated property of System.Web.HttpResponse class.

Rule Description

The following properties of the Response object are deprecated and should not be used:
  • System.Web.HttpResponse.CacheControl (methods of System.Web.HttpCachePolicy class should be used instead).
  • System.Web.HttpResponse.Expires (methods of System.Web.HttpCachePolicy class should be used instead).
  • System.Web.HttpResponse.ExpiresAbsolute (methods of System.Web.HttpCachePolicy class should be used instead).
  • System.Web.HttpResponse.Buffer (System.Web.HttpResponse.BufferOutput property should be used instead).

Correcting Violations

The rule provides the following auto-correct options:
  • Use recommended property or class instead of deprecated property.

Rule Instances

Instances of this rule in the built-in profile:
  • Do not use deprecated properties of Response object.


Do not use SaveAs method to store uploaded files

Rule ID: AN00004

Problem

System.Web.HttpPostedFile.SaveAs method is invoked.

Rule Description

Avoid using System.Web.HttpPostedFile.SaveAs method to store the incoming data to temporary files on the server's hard disk. Instead, read data from the incoming stream and save it directly to the appropriate data store, for example, a database.

The System.Web.HttpPostedFile.SaveAs method requires that you grant ASP.NET an identity with the permission to write to the server's hard disk.

Correcting Violations

The rule provides the following auto-correct options:
  • Manually read data from the incoming stream and save it directly to the appropriate data store.

Rule Instances

Instances of this rule in the built-in profile:
  • Do not use SaveAs method to store uploaded files.


Enable request validation in MVC controller action

Rule ID: AN00012

Problem

Make sure that the ValidateInputAttribute is used properly to protect against XSS attacks.

Rule Description

The rule verifies if the ValidateInputAttribute is used properly to protect against XSS attacks.
ValidateInputAttribute attribute can be used to mark action methods whose input must be validated.

This rule is similar to FxCop rule 'ControllerActionShouldValidateInput', CheckId CA5333

Correcting Violations

The rule provides the following auto-correct options:
  • Set ValidateRequestAttribute value to true.

Rule Instances

Instances of this rule in the built-in profile:
  • Enable request validation in MVC controller action.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

<ValidateInput(False)> _
Public Function Create() As ActionResult

  ' Do something...

End Function

' This is the correct implementation

<ValidateInput(True)> _
Public Function Create() As ActionResult

  ' Do something...

End Function

[C#]

// This code will trigger the rule violation

[ValidateInput(false)]
public ActionResult Create()
{

  // Do something...

}

// This is the correct implementation

[ValidateInput(true)]
public ActionResult Create()
{

  // Do something...

}


EnableEventValidation should be True

Rule ID: AN00013

Problem

EnableEventValidation directive is disabled on the page.

Rule Description

Make sure that event validation is enabled. If so, the page validates postback and callback events.

This rule is similar to FxCop rule 'EnableEventValidationShouldBeTrue', CheckId CA5327

Correcting Violations

The rule provides the following auto-correct options:
  • Set EnableEventValidation directive value to true on the page

Rule Instances

Instances of this rule in the built-in profile:
  • EnableEventValidation should be True.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<%@ Page language="C#" EnableEventValidation="False" %>

<!-- This is the correct implementation -->

<%@ Page language="C#" EnableEventValidation="True" %>


EnableViewState should be True

Rule ID: AN00017

Problem

EnableViewState directive is disabled on the page.

Rule Description

The directive should be set to True. EnableViewState directive specifies whether view state is enabled and maintained across page requests.

This rule is similar to FxCop rule 'EnableViewStateShouldBeTrue', CheckId CA5331

Correcting Violations

The rule provides the following auto-correct options:
  • Set EnableViewState directive value to true on the page

Rule Instances

Instances of this rule in the built-in profile:
  • EnableViewState should be True.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<%@ Page language="C#" EnableViewState="False" %>

<!-- This is the correct implementation -->

<%@ Page language="C#" EnableViewState="True" %>


EnableViewStateMac should be True

Rule ID: AN00016

Problem

EnableViewStateMac directive is disabled on the page.

Rule Description

EnableViewStateMac directive specifies whether ASP.NET should run a message authentication code (MAC) on the view state for the page when the page is posted back from the client. The directive should be set to True. If so, the encrypted view state is checked to verify that it has not been tampered with on the client.

This rule is similar to FxCop rule 'EnableViewStateMacShouldBeTrue', CheckId CA5330

Correcting Violations

The rule provides the following auto-correct options:
  • Set EnableViewStateMac directive value to true on the page

Rule Instances

Instances of this rule in the built-in profile:
  • EnableViewStateMac should be True.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<%@ Page language="C#" EnableViewStateMac="False" %>

<!-- This is the correct implementation -->

<%@ Page language="C#" EnableViewStateMac="True" %>


Form authentication Protection should be All in web.config

Rule ID: AN00020

Problem

protection attribute on the system.web.authentication.forms protection should be set to All.

Rule Description

The rule verifies that the protection attribute on the system.web.authentication.forms protection is set to All which specifies that the application use both data validation and encryption to help protect the authentication cookie.

This rule is similar to FxCop rule 'FormAuthenticationProtectionShouldBeAll', CheckId CA5404

Correcting Violations

The rule provides the following auto-correct options:
  • Set protection attribute value of the system.web.authentication.forms element to All in web.config

Rule Instances

Instances of this rule in the built-in profile:
  • Form authentication Protection should be All in web.config.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<configuration>
 <system.web>
  <authentication mode="Forms">
   <forms loginUrl="~/login.aspx" protection="None" />
  </authentication>
 </system.web>
</configuration>

<!-- This is the correct implementation -->

<configuration>
 <system.web>
  <authentication mode="Forms">
   <forms loginUrl="~/login.aspx" protection="All" />
  </authentication>
 </system.web>
</configuration>


Form authentication RequireSSL should be True in web.config

Rule ID: AN00022

Problem

requireSSL attribute on the system.web.authentication.forms configuration element should be set to true.

Rule Description

The rule verifies that the RequireSSL attribute on the system.web.authentication.forms configuration element is set to true which force the authentication cookie to specify the secure attribute.
This indicates the browser to only provide the cookie over SSL.

This rule is similar to FxCop rule 'FormAuthenticationRequireSSLShouldBeTrue', CheckId CA5405

Correcting Violations

The rule provides the following auto-correct options:
  • Set RequireSSL attribute value of the system.web.authentication.forms element to true in web.config

Rule Instances

Instances of this rule in the built-in profile:
  • Form authentication RequireSSL should be True in web.config.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<configuration>
 <system.web>
  <authentication mode="Forms">
   <forms loginUrl="~/login.aspx" protection="All" requireSSL="false" />
  </authentication>
 </system.web>
</configuration>

<!-- This is the correct implementation -->

<configuration>
 <system.web>
  <authentication mode="Forms">
   <forms loginUrl="~/login.aspx" protection="All" requireSSL="true" />
  </authentication>
 </system.web>
</configuration>


Form authentication should not contain credentials in web.config

Rule ID: AN00011

Problem

Make sure that no credentials are specified under the form authentication configuration.

Rule Description

The rule verifies that no credentials are specified under the form authentication configuration.

This rule is similar to FxCop rule 'FormAuthenticationShouldNotContainFormAuthenticationCredentials', CheckId CA5402

Correcting Violations

The rule provides the following auto-correct options:
  • Modify your code manually to remove users nodes from form authentication credentials in web.config

Rule Instances

Instances of this rule in the built-in profile:
  • Form authentication should not contain credentials in web.config.

Example

The following example show code that triggers the rule violation.

<!-- This is the correct implementation -->

<configuration>
 <system.web>
  <authentication mode="Forms">
   <forms />
  </authentication>
 </system.web>>
</configuration>


Form authentication SlidingExpiration should be False in web.config

Rule ID: AN00034

Problem

system.web.authentication.forms slidingExpiration should be set to false when the site is being serviced over HTTP.

Rule Description

The rule verifies that if the system.web.authentication.forms slidingExpiration be set to false when the site is being serviced over HTTP.
This will force the authentication cookie to have a fix timeout value instead of being refreshed by each request. Since the cookie will traverse over clear text network and can be sniffed, having a fix timeout value on the cookie will limit the amount of time the cookie can be replayed. If the cookie is traversing over HTTPS, it is less likely to be intercepted and having the slidingExpiration setting to True will cause the timeout to be refreshed after each request which gives a better user experience.

This rule is similar to FxCop rule 'FormAuthenticationSlidingExpirationShouldBeFalse', CheckId CA5406

Correcting Violations

The rule provides the following auto-correct options:
  • Set slidingExpiration attribute value of the system.web.authentication.forms element to false in web.config

Rule Instances

Instances of this rule in the built-in profile:
  • Form authentication SlidingExpiration should be False in web.config.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<configuration>
 <system.web>
  <authentication mode="Forms">
   <forms loginUrl="~/login.aspx" protection="All" slidingExpiration="true" />
  </authentication>
 </system.web>
</configuration>

<!-- This is the correct implementation -->

<configuration>
 <system.web>
  <authentication mode="Forms">
   <forms loginUrl="~/login.aspx" protection="All" slidingExpiration="false" />
  </authentication>
 </system.web>
</configuration>


Http cookies HttpOnlyCookies should be True in web.config

Rule ID: AN00023

Problem

system.web.httpCookies.httpOnlyCookies configuration should be set to true.

Rule Description

The rule verifies that the system.web.httpCookies httpOnlyCookies configuration is set to true which force all cookies to be sent with the HttpOnly attribute.

This rule is similar to FxCop rule 'HttpCookiesHttpOnlyCookiesShouldBeTrue', CheckId CA5407

Correcting Violations

The rule provides the following auto-correct options:
  • Set httpOnlyCookies attribute value of the system.web.httpCookies element to true in web.config

Rule Instances

Instances of this rule in the built-in profile:
  • Http cookies HttpOnlyCookies should be True in web.config.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<configuration>
 <system.web>
  <httpCookies requireSSL="true" httpOnlyCookies="false" />
 </system.web>
</configuration>

<!-- This is the correct implementation -->

<configuration>
 <system.web>
  <httpCookies requireSSL="true" httpOnlyCookies="true" />
 </system.web>
</configuration>


Http cookies RequireSSL should be True in web.config

Rule ID: AN00024

Problem

system.web.httpCookies requireSSL configuration should be set to true.

Rule Description

The rule verifies that the system.web.httpCookies requireSSL configuration is set to true which force all cookies to be sent with the secure attribute.
This indicates the browser to only provide the cookie over SSL.

This rule is similar to FxCop rule 'HttpCookiesRequireSSLShouldBeTrue', CheckId CA5408

Correcting Violations

The rule provides the following auto-correct options:
  • Set requireSSL attribute value of the system.web.httpCookies element to true in web.config

Rule Instances

Instances of this rule in the built-in profile:
  • Http cookies RequireSSL should be True in web.config.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<configuration>
 <system.web>
  <httpCookies requireSSL="false" />
 </system.web>
</configuration>

<!-- This is the correct implementation -->

<configuration>
 <system.web>
  <httpCookies requireSSL="true" />
 </system.web>
</configuration>


Http runtime EnableHeaderChecking should be True in web.config

Rule ID: AN00033

Problem

system.web.httpRuntime.enableHeaderChecking attribute is disabled in web.config.

Rule Description

The rule verifies that the system.web.httpRuntime enableHeaderChecking attribute is set to true.
The setting indicates whether ASP.NET should check the request header for potential injection attacks. If an attack is detected, ASP.NET responds with an error. This forces ASP.NET to apply the ValidateRequest protection to headers sent by the client. If an attack is detected the application throws HttpRequestValidationException.

This rule is similar to FxCop rule 'HttpRuntimeEnableHeaderCheckingShouldBeTrue', CheckId CA5416

Correcting Violations

The rule provides the following auto-correct options:
  • Set enableHeaderChecking attribute value of the system.web.httpRuntime element to true in web.config

Rule Instances

Instances of this rule in the built-in profile:
  • Http runtime EnableHeaderChecking should be True in web.config.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<configuration>
 <system.web>
  <httpRuntime enableHeaderChecking="false" />
 </system.web>
</configuration>

<!-- This is the correct implementation -->

<configuration>
 <system.web>
  <httpRuntime enableHeaderChecking="true" />
 </system.web>
</configuration>


Page EnableEventValidation should be True in web.config

Rule ID: AN00030

Problem

system.web.pages.enableEventValidation attribute is disabled in web.config.

Rule Description

Make sure that event validation is enabled. If so, the page validates postback and callback events.

This rule is similar to FxCop rule 'PagesEnableEventValidationMustBeTrue', CheckId CA5415

Correcting Violations

The rule provides the following auto-correct options:
  • Set enableEventValidation attribute value of the system.web.pages element to true in web.config

Rule Instances

Instances of this rule in the built-in profile:
  • Page EnableEventValidation should be True in web.config.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<configuration>
 <system.web>
  <pages enableEventValidation="false" />
 </system.web>
</configuration>

<!-- This is the correct implementation -->

<configuration>
 <system.web>
  <pages enableEventValidation="true" />
 </system.web>
</configuration>


Page EnableViewStateMac should be True in web.config

Rule ID: AN00029

Problem

system.web.pages.enableViewStateMac attribute is disabled in web.config.

Rule Description

EnableViewStateMac attribute specifies whether ASP.NET should run a message authentication code (MAC) on the view state for the page when the page is posted back from the client. The directive should be set to True. If so, the encrypted view state is checked to verify that it has not been tampered with on the client.

This rule is similar to FxCop rule 'PagesEnableViewStateMacShouldBeTrue', CheckId CA5414

Correcting Violations

The rule provides the following auto-correct options:
  • Set enableViewStateMac attribute value of the system.web.pages element to true in web.config

Rule Instances

Instances of this rule in the built-in profile:
  • Page EnableViewStateMac should be True in web.config.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<configuration>
 <system.web>
  <pages enableViewStateMac="false" />
 </system.web>
</configuration>

<!-- This is the correct implementation -->

<configuration>
 <system.web>
  <pages enableViewStateMac="true" />
 </system.web>
</configuration>


Page ValidateRequest should be True in web.config

Rule ID: AN00031

Problem

system.web.pages.validateRequest attribute is disabled in web.config.

Rule Description

The rule verifies that system.web.pages.validateRequest attribute is set to true which indicates that ASP.NET examines all input from the browser for potentially dangerous data. Request validation is performed by comparing all input data to a list of potentially dangerous values. If a match occurs, ASP.NET raises an HttpRequestValidationException exception.

This rule is similar to FxCop rule 'PagesValidateRequestShouldBeEnabled', CheckId CA5417

Correcting Violations

The rule provides the following auto-correct options:
  • Set validateRequest attribute value of the system.web.pages element to true in web.config

Rule Instances

Instances of this rule in the built-in profile:
  • Page ValidateRequest should be True in web.config.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<configuration>
 <system.web>
  <pages validateRequest="false" />
 </system.web>
</configuration>

<!-- This is the correct implementation -->

<configuration>
 <system.web>
  <pages validateRequest="true" />
 </system.web>
</configuration>


Page ViewStateEncryptionMode should be Always in web.config

Rule ID: AN00032

Problem

system.web.pages.viewStateEncryptionMode attribute should be configured to Always in web.config.

Rule Description

The rule verifies that the view state is always encrypted.

This rule is similar to FxCop rule 'PagesViewStateEncryptionModeShouldBeAlways', CheckId CA5418

Correcting Violations

The rule provides the following auto-correct options:
  • Set viewStateEncryptionMode attribute value of the system.web.pages element to Always in web.config

Rule Instances

Instances of this rule in the built-in profile:
  • Page ViewStateEncryptionMode should be Always in web.config.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<configuration>
 <system.web>
  <pages viewStateEncryptionMode="Auto" />
 </system.web>
</configuration>

<!-- This is the correct implementation -->

<configuration>
 <system.web>
  <pages viewStateEncryptionMode="Always" />
 </system.web>
</configuration>


Role manager CookieProtection should be All in web.config

Rule ID: AN00026

Problem

system.web.rolemanager cookieProtection should be set to All.

Rule Description

The rule verifies that the system.web.roleManager cookieProtection is set to All which enforce both the cookie to be encrypted and validated by the server.

This rule is similar to FxCop rule 'RoleManagerCookieProtectionShouldBeAll', CheckId CA5411

Correcting Violations

The rule provides the following auto-correct options:
  • Set cookieProtection attribute value of the system.web.roleManager element to All in web.config

Rule Instances

Instances of this rule in the built-in profile:
  • Role manager CookieProtection should be All in web.config.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<configuration>
 <system.web>
  <roleManager enabled="true" cookieProtection="None" />
 </system.web>
</configuration>

<!-- This is the correct implementation -->

<configuration>
 <system.web>
  <roleManager enabled="true" cookieProtection="All" />
 </system.web>
</configuration>


Role manager CookieRequireSSL should be True in web.config

Rule ID: AN00027

Problem

system.web.rolemanager cookieRequireSSL attribute should be set to true.

Rule Description

The rule verifies that the system.web.roleManager cookieRequireSSL attribute is set to true which force the role manager cookie to specify the secure attribute.
This indicates the browser to only provide the cookie over SSL.

This rule is similar to FxCop rule 'RoleManagerCookieRequireSSLShouldBeTrue', CheckId CA5412

Correcting Violations

The rule provides the following auto-correct options:
  • Set cookieRequireSSL attribute value of the system.web.roleManager element to true in web.config

Rule Instances

Instances of this rule in the built-in profile:
  • Role manager CookieRequireSSL should be True in web.config.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<configuration>
 <system.web>
  <roleManager enabled="true" cookieRequireSSL="false" />
 </system.web>
</configuration>

<!-- This is the correct implementation -->

<configuration>
 <system.web>
  <roleManager enabled="true" cookieRequireSSL="true" />
 </system.web>
</configuration>


Role manager CookieSlidingExpiration should be False in web.config

Rule ID: AN00028

Problem

system.web.rolemanager cookieSlidingExpiration should be set to false.

Rule Description

The rule verifies that the system.web.roleManager cookieSlidingExpiration is set to false when the site is being serviced over HTTP.
This will force the authentication cookie to have a fix timeout value instead of being refreshed by each request. Since the cookie will traverse over clear text network and can be sniffed, having a fix timeout value on the cookie will limit the amount of time the cookie can be replayed. If the cookie is traversing over HTTPS, it is less likely to be intercepted and having the cookieSlidingExpiration setting to True will cause the timeout to be refreshed after each request which gives a better user experience.

This rule is similar to FxCop rule 'RoleManagerCookieSlidingExpirationShouldBeFalse', CheckId CA5413

Correcting Violations

The rule provides the following auto-correct options:
  • Set cookieSlidingExpiration attribute value of the system.web.roleManager element to false in web.config

Rule Instances

Instances of this rule in the built-in profile:
  • Role manager CookieSlidingExpiration should be False in web.config.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<configuration>
 <system.web>
  <roleManager enabled="true" cookieRequireSSL="true" cookieSlidingExpiration="true" />
 </system.web>
</configuration>

<!-- This is the correct implementation -->

<configuration>
 <system.web>
  <roleManager enabled="true" cookieRequireSSL="true" cookieSlidingExpiration="false" />
 </system.web>
</configuration>


Trace should be disabled in web.config

Rule ID: AN00025

Problem

system.web.trace should be set to false.

Rule Description

The rule verifies that the system.web.trace is set to false which disable tracing. It is recommended to disable tracing on production servers to make sure that an attacker cannot gain information from the trace about your application. Trace information can help an attacker probe and compromise your application.

This rule is similar to FxCop rule 'TraceShouldBeDisabled', CheckId CA5409

Correcting Violations

The rule provides the following auto-correct options:
  • Set enabled attribute value of the system.web.trace element to false in web.config

Rule Instances

Instances of this rule in the built-in profile:
  • Trace should be disabled in web.config.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<configuration>
 <system.web>
  <trace enabled="true" />
 </system.web>
</configuration>

<!-- This is the correct implementation -->

<configuration>
 <system.web>
  <trace enabled="false" />
 </system.web>
</configuration>


Use ValidateAntiforgeryTokenAttribute to protect against potential CSRF attacks in MVC controller action

Rule ID: AN00036

Problem

MVC Controller action method does not contain System.Web.Mvc.ValidateAntiForgeryTokenAttribute but defined HttpVerbs.Post.

Rule Description

Rule that verifies that if the System.Web.Mvc.ValidateAntiForgeryTokenAttribute is used to protect against Potential CSRF attack in MVC.

This rule is similar to FxCop rule 'MarkVerbHandlersWithValidateAntiforgeryToken', CheckId CA5332

Correcting Violations

The rule provides the following auto-correct options:
  • Add System.Web.Mvc.HttpGetAttribute to method
  • Add System.Web.Mvc.ValidateAntiForgeryTokenAttribute and System.Web.Mvc.HttpPostAttribute to method
  • Add System.Web.Mvc.HttpPostAttribute to method
  • Comment out System.Web.Mvc.HttpGetAttribute in method
  • Comment out System.Web.Mvc.ValidateAntiForgeryTokenAttribute in method

Rule Instances

Instances of this rule in the built-in profile:
  • Use ValidateAntiforgeryTokenAttribute to protect against potential CSRF attacks in MVC controller action.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Public Function SubmitUpdate() As ViewResult

  ...

End Function

' This is the correct implementation

<HttpPost> _
<ValidateAntiForgeryToken> _
Public Function SubmitUpdate() As ViewResult

  ...

End Function

[C#]

// This code will trigger the rule violation

public ViewResult SubmitUpdate()
{

  ...

}

// This is the correct implementation

[HttpPost]
[ValidateAntiForgeryToken]
public ViewResult SubmitUpdate()
{

  ...

}


ValidateRequest should be True

Rule ID: AN00014

Problem

ValidateRequest directive is disabled on the page.

Rule Description

The rule verifies that ValidateRequest directive is enabled on the page which indicates that ASP.NET examines all input from the browser for potentially dangerous data. Request validation is performed by comparing all input data to a list of potentially dangerous values. If a match occurs, ASP.NET raises an HttpRequestValidationException exception.

This rule is similar to FxCop rule 'ValidateRequestShouldBeEnabled', CheckId CA5328

Correcting Violations

The rule provides the following auto-correct options:
  • Set ValidateRequest directive value to true on the page

Rule Instances

Instances of this rule in the built-in profile:
  • ValidateRequest should be True.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<%@ Page language="C#" AutoEventWireup="true" ValidateRequest="False" %>

<!-- This is the correct implementation -->

<%@ Page language="C#" AutoEventWireup="true" ValidateRequest="True" %>


ViewStateEncryptionMode should be Always

Rule ID: AN00015

Problem

ViewStateEncryptionMode should be Always on the page.

Rule Description

The rule verifies that the view state is always encrypted.

This rule is similar to FxCop rule 'ViewStateEncryptionModeShouldBeAlways', CheckId CA5329

Correcting Violations

The rule provides the following auto-correct options:
  • Set ViewStateEncryptionMode directive value to Always on the page

Rule Instances

Instances of this rule in the built-in profile:
  • ViewStateEncryptionMode should be Always.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<%@ Page language="C#" AutoEventWireup="true" ViewStateEncryptionMode="Auto" %>

<!-- This is the correct implementation -->

<%@ Page language="C#" AutoEventWireup="true" ViewStateEncryptionMode="Always" %>


Async Rules

This section will guide you through the set of Async Rules.

Click on any of the links below to go directly to the corresponding rule.

Async method should have "Async" suffix

Async method should have await statement

Async method should return Task or Task<T>

Avoid "out" and "ref" parameters in async method

Await for completion of an API which returns a Task

Await statement method should be async

Call Start on the Task object before instantiating

Do not call specified await method in async method

Do not call specified user method in async method

Do not create async Sub method

TAP method parameters should be the same

Transform simple async method to non-async


Async method should have Async suffix

Rule ID: AS00002

Problem

Public method is marked as async modifier but does ends with an Async suffix.

Rule Description

Initiation and completion of an asynchronous operation in the TAP are represented by a single method, and thus there is only one method to name. Asynchronous methods in the TAP are named with an Async suffix that follows the operation's name, e.g. MethodNameAsync. (If adding a TAP method to a class that already contains a method MethodNameAsync, the suffix TaskAsync may be used instead, resulting in MethodNameTaskAsync.)

Correcting Violations

The rule provides the following auto-correct options:
  • Rename code element MethodName and its references to MethodNameAsync.
  • Rename code element MethodName and its references to the specified name.

Rule Instances

Instances of this rule in the built-in profile:
  • Async method should have Async suffix.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation
    Namespace AsyncMethodsShouldHaveTheSuffixAsync.Test
      Public Class SomeClass
        ' Violates the rule
        Public Function SomeMethod() As Task
          Dim tsk = Task.Factory.StartNew(Function()
                                          End Function)
          Await tsk
        End Function
      End Class
    End Namespace

' This is the correct implementation
    Namespace AsyncMethodsShouldHaveTheSuffixAsync.Test
      Public Class SomeClass
        Public Function SomeMethodAsync() As Task ' FIX: Add Async suffix
          Dim tsk = Task.Factory.StartNew(Function()
                                          End Function)
          Await tsk
        End Function
      End Class
    End Namespace

[C#]

// This code will trigger the rule violation
    namespace AsyncMethodsShouldHaveTheSuffixAsync.Test
    {
      public class SomeClass
      {
        // Violates the rule
        public async Task SomeMethod()
        {
          var tsk = Task.Factory.StartNew(() => {});
          await tsk;
        }
      }
    }

// This is the correct implementation
    namespace AsyncMethodsShouldHaveTheSuffixAsync.Test
    {
      public class SomeClass
      {
        public async Task SomeMethodAsync() // FIX: Add Async suffix
        {
          var tsk = Task.Factory.StartNew(() => {});
          await tsk;
        }
      }
    }

Related Rules

Async method should have await statement

Async methods should return Task or Task<T>

Await for completion of an API which returns a Task

Await statement method should be async


Async method should have await statement

Rule ID: AS00009

Problem

Public method is marked as async but no await statement is found in its body.

Rule Description

If you call an API which returns a Task, you should almost always await it either immediately or later on or indirectly through something like Task.Wait. Compilers have a warning in some cases but not all.

Correcting Violations

The rule provides the following auto-correct options:
  • Remove async modifier from the async method.
  • Add await statement to the async method manually.

Rule Instances

Instances of this rule in the built-in profile:
  • Async method should have await statement.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation
    Namespace AsyncMethodShouldHaveAwaitStatement.Test
      Public Class SomeClass
        ' Violates the rule
        Public Function SomeMethodAsync() As Task
        End Function
      End Class
    End Namespace

' This is the correct implementation
    Namespace AsyncMethodShouldHaveAwaitStatement.Test
      Public Class SomeClass
        Public Function SomeMethodAsync() As Task
          ' FIX: Added async code invocation
          Dim tsk = Task.Factory.StartNew(Function()
                                          End Function)
          Await tsk
        End Function
      End Class
    End Namespace

[C#]

// This code will trigger the rule violation
    namespace AsyncMethodShouldHaveAwaitStatement.Test
    {
      public class SomeClass
      {
        // Violates the rule
        public async Task SomeMethodAsync()
        {
        }
      }
    }

// This is the correct implementation
    namespace AsyncMethodShouldHaveAwaitStatement.Test
    {
      public class SomeClass
      {
        public async Task SomeMethodAsync()
        {
          // FIX: Added async code invocation
          var tsk = Task.Factory.StartNew(() => {});
          await tsk;
        }
      }
    }

Related Rules

Async method should have Async suffix

Async methods should return Task or Task<T>

Await for completion of an API which returns a Task

Await statement method should be async


Async methods should return Task or Task<T>

Rule ID: AS00003

Problem

Public method is marked as async but return type is not System.Threading.Tasks.Task or System.Threading.Tasks.Task<T>

Rule Description

In TAP the singular method returns either a Task or a Task<TResult>, based on whether the corresponding synchronous method would return void or a type TResult, respectively.

Correcting Violations

The rule provides the following auto-correct options:
  • Specify Task or Task<T> return type for the method.

Rule Instances

Instances of this rule in the built-in profile:
  • Async methods should return Task or Task<T>.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation
    Namespace AsyncMethodsShouldReturnTask.Tests
      Public Class SomeClass
        ' Violates the rule
        Public Function SomeMethodAsync() As Integer
          Return 0
        End Function
      End Class
    End Namespace

' This is the correct implementation
    Namespace AsyncMethodsShouldReturnTask.Tests
      Public Class SomeClass
        Public Function SomeMethodAsync() As Task(Of Integer)
          Dim value As Integer = Await Task.Factory.StartNew(Function() 0)
          Return value
        End Function
      End Class
    End Namespace

[C#]

// This code will trigger the rule violation
    namespace AsyncMethodsShouldReturnTask.Tests
    {
      public class SomeClass
      {
        // Violates the rule
        public async int SomeMethodAsync()
        {
          return 0;
        }
      }
    }

// This is the correct implementation
    namespace AsyncMethodsShouldReturnTask.Tests
    {
      public class SomeClass
      {
        public async Task<int> SomeMethodAsync()
        {
          int value = await Task.Factory.StartNew(() => 0);
          return value;
        }
      }
    }

Related Rules

Async method should have await statement

Async method should have Async suffix

Await for completion of an API which returns a Task

Await statement method should be async

Don't create "Async Sub" methods


Avoid "out" and "ref" parameters in async method

Rule ID: AS00004

Problem

Public method is marked as async has one or many out or ref parameters.

Rule Description

The parameters to a TAP method should be the same parameters provided to the synchronous counterpart, in the same order. However, out and ref parameters are exempted from this rule and should be avoided entirely. Any data that would have been returned through an out or ref parameter should instead be returned as part of the returned Task<TResult>'s Result, utilizing a Tuple or a custom data structure in order to accommodate multiple values.

Correcting Violations

The rule provides the following auto-correct options:
  • Remove ref or out parameters from the method manually.

Rule Instances

Instances of this rule in the built-in profile:
  • Avoid "out" and "ref" parameters in async method

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation
    Namespace AvoidOutAndRefParametersInAsyncMethods.Test
      Public Class SomeClass
        ' Violates the rule
        Public Function SomeMethodAsync(ByRef a As Integer, ByRef b As Integer) As Task
          a = 42
          b += 42
        End Function
      End Class
    End Namespace

' This is the correct implementation
    Namespace AvoidOutAndRefParametersInAsyncMethods.Test
      Public Class SomeClass
        Public Function SomeMethodAsync(b As Integer) As Task(Of Tuple(Of Integer, Integer))
          Return New Tuple(Of Integer, Integer)(42, b + 42)
        End Function
      End Class
    End Namespace

[C#]

// This code will trigger the rule violation
    namespace AvoidOutAndRefParametersInAsyncMethods.Test
    {
      public class SomeClass
      {
        // Violates the rule
        public async Task SomeMethodAsync(out int a, ref int b)
        {
          a = 42;
          b += 42;
        }
      }
    }

// This is the correct implementation
    namespace AvoidOutAndRefParametersInAsyncMethods.Test
    {
      public class SomeClass
      {
        public async Task<Tuple<int, int>> SomeMethodAsync(int b)
        {
          return new Tuple<int, int>(42, b + 42);
        }
      }
    }

Related Rules

TAP method parameters should be the same


Await for completion of an API which returns a Task

Rule ID: AS00007

Problem

Async method is called but is not awaited with either:
  • await
  • Task.Wait, Task.WaitAll, Task.WaitAny
  • Task.WhenAll, Task.WhenAny

Rule Description

If you call an API which returns a Task, you should almost always await it either immediately or later on or indirectly through something like Task.Wait.

Correcting Violations

The rule provides the following auto-correct options:
  • Specify await for the method call that returns Task manually

Rule Instances

Instances of this rule in the built-in profile:
  • Await for completion of an API which returns a Task.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation
    Namespace AwaitForCompletionOfTask.Test
      Public Class SomeClass
        Private Function IoBoundOperationAsync() As Task(Of Integer)
          Return Task(Of Integer).Factory.StartNew(Function() 42)
        End Function

        Public Function SomeMethodAsync() As Task(Of Integer)
          ' Violates the rule
          Dim value As Integer = IoBoundOperationAsync().Result
          Return value
        End Function
      End Class
    End Namespace

' This is the correct implementation
    Namespace AwaitForCompletionOfTask.Tests
      Public Class SomeClass
        Private Function IoBoundOperationAsync() As Task(Of Integer)
          Return Task(Of Integer).Factory.StartNew(Function() 42)
        End Function

        Public Function SomeMethodAsync() As Task(Of Integer)
          ' FIX: Await for completion of operation
          Dim value As Integer = Await IoBoundOperationAsync()
          Return value
        End Function
      End Class
    End Namespace

[C#]

// This code will trigger the rule violation
    namespace AwaitForCompletionOfTask.Test
    {
      public class SomeClass
      {
        private Task IoBoundOperationAsync()
        {
          return Task.Factory.StartNew(() => 42);
        }

        public async Task SomeMethodAsync()
        {
          // Violates the rule
          int value = IoBoundOperationAsync().Result;
          return value;
        }
      }
    }

// This is the correct implementation
    namespace AwaitForCompletionOfTask.Tests
    {
      public class SomeClass
      {
        private Task IoBoundOperationAsync()
        {
          return Task.Factory.StartNew(() => 42);
        }

        public async Task SomeMethodAsync()
        {
          // FIX: await for completion of operation
          int value = await IoBoundOperationAsync();
          return value;
        }
      }
    }

Related Rules

Await statement method should be async


Await statement method should be async

Rule ID: AS00010

Problem

Method contains await statement but not marked with async modifier.

Rule Description

The asynchronous method in which await is used must be modified by the async keyword. Such a method, defined by using the async modifier, and usually containing one or more await expressions, is referred to as an async method.

Correcting Violations

The rule provides the following auto-correct options:
  • Add async modifier to the async method.

Rule Instances

Instances of this rule in the built-in profile:
  • Await statement method should be async.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation
    Namespace AwaitStatementMethodShouldBeAsync.Test
      Class SomeClass
        ' Violates the rule
        Public Function SomeMethod() As Task
          Dim tsk As Task = Task.Run(Function()
                                     End Function)
          Await tsk
        End Function
      End Class
    End Namespace

' This is the correct implementation
    Namespace AwaitStatementMethodShouldBeAsync.Test
      Class SomeClass
        ' FIX: add Async modifier
        Public Async Function SomeMethod() As Task
          Dim tsk As Task = Task.Run(Function()
                                     End Function)
          Await tsk
        End Function
      End Class
    End Namespace

[C#]

// This code will trigger the rule violation
    namespace AwaitStatementMethodShouldBeAsync.Test
    {
      class SomeClass
      {
        // Violates the rule
        public Task SomeMethod()
        {
          Task tsk = Task.Run(() => { });
          await tsk;
        }
      }
    }

// This is the correct implementation
    namespace AwaitStatementMethodShouldBeAsync.Test
    {
      class SomeClass
      {
        // FIX: add async modifier
        public async Task SomeMethod()
        {
          Task tsk = Task.Run(() => { });
          await tsk;
        }
      }
    }

Related Rules

Await for completion of an API which returns a Task


Call Start on the Task object before instantiating

Rule ID: AS00001

Problem

Method returns Task which is not started with either:
  • Start
  • Task.Factory.StartNew
  • Task.Run

Rule Description

All tasks that are returned from TAP methods must be activated. If a TAP method internally uses a task’s constructor to instantiate the task to be returned, the TAP method must call Start on the Task object before returning it. Consumers of a TAP method may safely assume that the returned task is active and should not try to call Start on any Task that is returned from a TAP method. Calling Start on an active task results in an InvalidOperationException exception.

Correcting Violations

The rule provides the following auto-correct options:
  • Call Start on the Task object before instantiating manually.

Rule Instances

Instances of this rule in the built-in profile:
  • Call Start on the Task object before instantiating

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation
    Namespace CallStartOnTaskBeforeInstantiating.Tests
      Class SomeClass
        Public Function SomeMethod() As Task
          ' Violates the rule
          Dim task = New Task(Function()
                              End Function)
          Return task
        End Function
      End Class
    End Namespace

' This is the correct implementation
    Namespace CallStartOnTaskBeforeInstantiating.Tests
      Class SomeClass
        Public Function SomeMethod() As Task
          Dim task = New Task(Function()
                              End Function)
          ' FIX: Call Start
          task.Start()
          Return task
        End Function
      End Class
    End Namespace

[C#]

// This code will trigger the rule violation
    namespace CallStartOnTaskBeforeInstantiating.Tests
    {
      class SomeClass
      {
        public Task SomeMethod()
        {
          // Violates the rule
          var task = new Task(() => {});
          return task;
        }
      }
    }

// This is the correct implementation
    namespace CallStartOnTaskBeforeInstantiating.Tests
    {
      class SomeClass
      {
        public Task SomeMethod()
        {
          var task = new Task(() => {});
          // FIX: Call Start
          task.Start();
          return task;
        }
      }
    }

Related Rules

© 2002-2019 SubMain. All rights reserved.
Designated trademarks and brands are the property of their respective owners.


Do not await call user method in async method

Rule ID: AS0011

Problem

Specific async method is called and awaited.

Rule Description

API should not lie to the caller. If an API says it is synchronous: it shouldn't be queuing and waiting. If it claims async, it should be using async.

Correcting Violations

The rule provides the following auto-correct options:
  • Do not await the method call of the class in the async method. Remove the call manually.

Rule Instances

Instances of this rule in the built-in profile:
  • Do not use Task.Yield in async method.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation
    Namespace DoNotCallSpecifiedAwaitMethodInAsyncMethod.Test
      Public Class SomeClass
        Public Sub SomeMethodAsync()
          For i As Integer = 0 To 999
            If i Mod 10 = 0 Then
              ' .. Some code
              Await Task.Yield() ' Violates the rule
            End If
          Next
        End Sub
      End Class
    End Namespace

' This is the correct implementation
    Namespace DoNotCallSpecifiedAwaitMethodInAsyncMethod.Test
      Public Class SomeClass
        Public Sub SomeMethod()
          For i As Integer = 0 To 999
            ' .. Some code
          Next
        End Sub
      End Class
    End Namespace

[C#]

// This code will trigger the rule violation
    namespace DoNotCallSpecifiedAwaitMethodInAsyncMethod.Test
    {
      public class SomeClass
      {
        public async void SomeMethodAsync()
        {
          for (int i = 0; i < 1000; i++)
          {
            // .. Some code
            if (i % 10 == 0)
              await Task.Yield(); // Violates the rule
          }
        }
      }
    }

// This is the correct implementation
    namespace DoNotCallSpecifiedAwaitMethodInAsyncMethod.Test
    {
      public class SomeClass
      {
        public void SomeMethod()
        {
          for (int i = 0; i < 1000; i++)
          {
            // .. Some code
          }
        }
      }
    }

Related Rules

Do not call user method in async method


Do not call user method in async method

Rule ID: AS0012

Problem

Specific async method is called.

Rule Description

API should not lie to the caller. If an API says it is synchronous: it shouldn't be queuing and waiting. If it claims async, it should be using async.

Correcting Violations

The rule provides the following auto-correct options:
  • Do not call the method of the class in the async method. Remove the call manually.

Rule Instances

Instances of this rule in the built-in profile:
  • Do not use Task.Wait in async method.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation
 Namespace DoNotUseTaskYieldInAsyncMethod.Test
  Public Class SomeClass
    Public Sub SomeMethodAsync()
      ' Violates the rule
      Task.WaitAll(Task.Run(Function() Console.ReadLine()))
    End Sub
  End Class
End Namespace

' This is the correct implementation
    Namespace DoNotUseTaskYieldInAsyncMethod.Test
      Public Class SomeClass
        Public Sub SomeMethodAsync()
          ' FIX1: add await
          Await Task.Run(Function() Console.ReadLine())
        End Sub

        Public Sub SomeMethod()
          ' FIX2: make whole method synchronous
          Console.ReadLine()
        End Sub
      End Class
    End Namespace

[C#]

// This code will trigger the rule violation
    namespace DoNotUseTaskYieldInAsyncMethod.Test
    {
      public class SomeClass
      {
        public async void SomeMethodAsync()
        {
          // Violates the rule
          Task.WaitAll(Task.Run(() => Console.ReadLine()));
        }
      }
    }

// This is the correct implementation
    namespace DoNotUseTaskYieldInAsyncMethod.Test
    {
      public class SomeClass
      {
        public async void SomeMethodAsync()
        {
          // FIX1: add await
          await Task.Run(() => Console.ReadLine());
        }

        public void SomeMethod()
        {
          // FIX2: make whole method synchronous
          Console.ReadLine();
        }
      }
    }

Related Rules

Do not await call user method in async method


Don't create "Async Sub" methods

Rule ID: AS00006

Problem

Method with async modifier returns void

Rule Description

Don't create "Async Sub" methods (as known as void-returning asyncs) except for top-level event handlers.

Correcting Violations

The rule provides the following auto-correct options:
  • Specify Task or Task<T> return type for the method.

Rule Instances

Instances of this rule in the built-in profile:
  • Do not create async Sub method

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation
    Namespace DontCreateAsyncSubMethods.Test
      Public Class SomeClass
        ' Violates the rule
        Public Sub SomeMethodAsync()
          ' .. Some code
          Await IoBoundOperation()
        End Sub
      End Class
    End Namespace

' This is the correct implementation
    Namespace DontCreateAsyncSubMethods.Test
      Public Class SomeClass
        ' FIX: Change sub to Task returning function
        Public Function SomeMethodAsync() As Task
          ' .. Some code
          Await IoBoundOperation()
        End Function
      End Class
    End Namespace

[C#]

// This code will trigger the rule violation
    namespace DontCreateAsyncSubMethods.Test
    {
      public class SomeClass
      {
        // Violates the rule
        public async void SomeMethodAsync()
        {
          // .. Some code
          await IoBoundOperation();
        }
      }
    }

// This is the correct implementation
    namespace DontCreateAsyncSubMethods.Test
    {
      public class SomeClass
      {
        // FIX: Change void to Task
        public async Task SomeMethodAsync()
        {
          // .. Some code
          await IoBoundOperation();
        }
      }
    }

Related Rules

Async methods should return Task or Task<T>


TAP method parameters should be the same

Rule ID: AS00006

Problem

Counterpart asynchronous method has different parameters set than the synchronous one.

- OR -

Counterpart asynchronous method parameters order is defferent then the synchronous one.

Rule Description

The parameters to a basic TAP method should be the same parameters provided to the synchronous counterpart, in the same order. However, out and ref parameters are exempted from this rule and should be avoided entirely. Any data that would have been returned through an out or ref parameter should instead be returned as part of the returned Task<TResult>'s Result, utilizing a tuple or a custom data structure in order to accommodate multiple values.

Correcting Violations

The rule provides the following auto-correct options:
  • Specify the same parameters for the method as for its synchronous counterpart manually.

Rule Instances

Instances of this rule in the built-in profile:
  • TAP method parameters should be the same

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation
    Namespace TapMethodParametersShouldBeSame.Tests
      Public Class SomeClassDifferentNames
        Public Sub SomeMethod(a As Integer, b As Double)
        End Sub

        ' Violates the rule - names must be the same
        Public Function SomeMethodAsync(a As Integer, c As Double) As Task
        End Function

        ' Violates the rule - types must be the same
        Public Function SomeMethodAsync(a As Double, b As Double) As Task
        End Function

        ' Violates the rule - order must be the same
        Public Function SomeMethodAsync(b As Double, a As Integer) As Task
        End Function
      End Class
    End Namespace

' This is the correct implementation
    Namespace TapMethodParametersShouldBeSame.Tests
      Public Class SomeClassDifferentNames
        Public Sub SomeMethod(a As Integer, b As Double)
        End Sub

        ' FIX: types, names and order are the same
        Public Function SomeMethodAsync(a As Integer, b As Double) As Task
        End Function
      End Class
    End Namespace

[C#]

// This code will trigger the rule violation
    namespace TapMethodParametersShouldBeSame.Tests
    {
      public class SomeClassDifferentNames
      {
        public void SomeMethod(int a, double b)
        {
        }

        // Violates the rule - names must be the same
        public async Task SomeMethodAsync(int a, double c)
        {
        }

        // Violates the rule - types must be the same
        public async Task SomeMethodAsync(double a, double b)
        {
        }

        // Violates the rule - order must be the same
        public async Task SomeMethodAsync(double b, int a)
        {
        }
      }
    }
// This is the correct implementation
    namespace TapMethodParametersShouldBeSame.Tests
    {
      public class SomeClassDifferentNames
      {
        public void SomeMethod(int a, double b)
        {
        }

        // FIX: types, names and order are the same
        public async Task SomeMethodAsync(int a, double b)
        {
        }
      }
    }

Related Rules

Avoid "out" and "ref" parameters in async method


Transform simple async methods to non-async

Rule ID: AS00006

Problem

Return await is the only awaited async method call in the method.

Rule Description

If an async method contains only one await operator, and it's in the form return await <expr>, then you should just return <expr> and make your method non-async.

Correcting Violations

The rule provides the following auto-correct options:
  • Return <expr> and make your method non-async manually.

Rule Instances

Instances of this rule in the built-in profile:
  • Transform simple async methods to non-async

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation
  Namespace TransformSimpleAsyncMethodsToNonAsync.Test
    Public Class SomeClass
      Public Function SomeMethod() As Task(Of Integer)
        ' Violates the rule
        Return Await IoBoundOperationAsync()
      End Function

      Public Function IoBoundOperationAsync() As Task(Of Integer)
        Return Task(Of Integer).Factory.StartNew(Function() 42)
      End Function
    End Class
  End Namespace

' This is the correct implementation
    Namespace TransformSimpleAsyncMethodsToNonAsync.Test
      Public Class SomeClass
        ' FIX: Convert to synchronous method
        Public Function SomeMethod() As Task(Of Integer)
          Return IoBoundOperationAsync()
        End Function

        Public Function IoBoundOperationAsync() As Task(Of Integer)
          Return Task(Of Integer).Factory.StartNew(Function() 42)
        End Function
      End Class
    End Namespace

[C#]

// This code will trigger the rule violation
    namespace TransformSimpleAsyncMethodsToNonAsync.Test
    {
      public class SomeClass
      {
        public async Task SomeMethod()
        {
          // Violates the rule
          return await IoBoundOperationAsync();
        }

        public Task IoBoundOperationAsync()
        {
          return Task.Factory.StartNew(() => 42);
        }
      }
    }

// This is the correct implementation
    namespace TransformSimpleAsyncMethodsToNonAsync.Test
    {
      public class SomeClass
      {
        // FIX: Convert to synchronous method
        public Task SomeMethod()
        {
          return IoBoundOperationAsync();
        }

        public Task IoBoundOperationAsync()
        {
          return Task.Factory.StartNew(() => 42);
        }
      }
    }

Related Rules

© 2002-2019 SubMain. All rights reserved.
Designated trademarks and brands are the property of their respective owners.


Coding Style Rules

This section will guide you through the set of Coding Style Rules.

Click on any of the links below to go directly to the corresponding rule.

Avoid single-line If statement

Do not include multiple statements on a single line


Avoid single-line If statement

Rule ID: CS00002

Problem

Method should not contain single-statement If block.

Rule Description

According to Microsoft .NET Framework guidelines, it is recommended to avoid single-line If statements.

If statement should be always closed with an End If keyword (for C#, curly braces should be used for if blocks that contain single line). By doing so, it is easier to add comments and other statements later in the development and debugging process.

Correcting Violations

The rule provides the following auto-correct options:
  • Split If block into a multiline statement.

Rule Instances

Instances of this rule in the built-in profile:
  • Avoid single line If statement.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

    ' Violates the rule
    If x > 0 Then y = 0

' This is the correct implementation

    If x > 0 Then
      y = 0
    End If

[C#]

// This code will trigger the rule violation

    // Violates the rule
    if (x > 0) y = 0;

// This is the correct implementation

    if (x > 0)
    {
      y = 0;
    }

Related Rules

Do not include multiple statements on a single line


Do not include multiple statements on a single line

Rule ID: CS00001

Problem

Method should not contain multiple statements on a single line.

Rule Description

According to Microsoft .NET Framework guidelines, it is not recommended to include multiple statements on a single line.

Lines containing single statements make the code more readable and enable you to add a comment for each individual statement.

Correcting Violations

The rule provides the following auto-correct options:
  • Split statements into multiple lines.

Rule Instances

Instances of this rule in the built-in profile:
  • Do not include multiple statements on a single line.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

    ' Violates the rule
    x = 1 : y = 2

' This is the correct implementation

    x = 1 ' separate comment for the statement
    y = 2 ' separate comment for the statement

[C#]

// This code will trigger the rule violation

    // Violates the rule
    x = 1; y = 2;

// This is the correct implementation

    x = 1; // separate comment for the statement
    y = 2; // separate comment for the statement

Related Rules

Avoid single-line If statement


Design Rules

This section will guide you through the set of Design Rules.

Click on any of the links below to go directly to the corresponding rule.

Abstract class should have at least one derived class

Abstract types should not have public constructors

Assemblies should have valid strong names

Do not declare externally visible instance fields

Do not declare protected members in sealed types

Do not hide base class methods

Do not override operator equals on reference types

Do not place assembly attributes outside of AssemblyInfo file

Enum underlying type should be System.Int32 or one of the CLS-compliant integral types.

Implement Finalizer Correctly

Implement IDisposable Correctly

Interface methods should be callable by child types

Interface should have an implementation

Mark assembly with a specified attribute

Nested types should not be visible

Project should have AssemblyInfo file

Type that contains only static members should be sealed (NotInheritable)

Type that contains only static members should not have public or protected constructors

Types that own disposable fields should be disposable

Types that own unmanaged resources should be disposable


Abstract class should have at least one derived class

Rule ID: DE00017

Problem

An abstract class should have at least one derived class.

Rule Description

Provide at least one concrete type that inherits from each abstract class that you ship.

Doing this helps to validate the design of the abstract class. For example, System.IO.FileStream is an implementation of the System.IO.Stream abstract class.

Correcting Violations

The rule provides the following auto-correct options:
  • Comment out an abstract class.

Rule Instances

Instances of this rule in the built-in profile:
  • Abstract class should have at least one derived class.

Related Rules

Abstract types should not have public constructors


Abstract types should not have public constructors

Rule ID: DE00001

Problem

An abstract public class has a public constructor.

Rule Description

According to Microsoft .NET Framework guidelines, an abstract class (MustInherit in Visual Basic) must have a constructor with protected scope.

The constructor in an abstract class is meant to be called by derived types only. Therefore, it should have protected visibility.

You must add an explicit protected constructor in an abstract class to keep the Visual Basic compiler from mistakenly creating a parameterless public constructor.

This rule is similar to FxCop rule 'Abstract types should not have constructors', CheckId CA1012

Correcting Violations

The rule provides the following auto-correct options:
  • Search for constructor(s) and change one(s) modifier.
  • Remove modifier for the type.

Rule Instances

Instances of this rule in the built-in profile:
  • Abstract types should not have public constructors.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System

Namespace SampleClasses

  ' Violates the rule: the compiler creates a default public constructor
  Public MustInherit Class Sample1Base

    ...

  End Class

  ' Violates the rule
  Public MustInherit Class Sample2Base

    Public Sub New()
    End Sub

    ...

  End Class

End Namespace

' This is the correct implementation
Imports System

Namespace SampleClasses

  ' Explicit protected constructor added
  Public MustInherit Class Sample1Base

    Protected Sub New()
    End Sub

    ...

  End Class

  ' Constructor is protected
  Public MustInherit Class Sample2Base

    Protected Sub New()
    End Sub

    ...

  End Class

End Namespace

[C#]

// This code will trigger the rule violation

using System;

namespace SampleClasses
{

  // Violates the rule: the compiler creates a default public constructor
  public abstract class Sample1Base
  {

    ...

  }

  // Violates the rule
  public abstract class Sample2Base
  {

    public Sample2Base()
    {
    }

    ...

  }

}

// This is the correct implementation
using System;

namespace SampleClasses
{

  // Explicit protected constructor added
  public abstract class Sample1Base
  {

    protected Sample1Base()
    {
    }

    ...

  }

  // Constructor is protected
  public abstract class Sample2Base
  {

    protected Sample2Base()
    {
    }

    ...

  }

}

Related Rules

bstract class should have at least one derived class


Assemblies should have valid strong names

Rule ID: DE00016

Problem

An assembly is not signed with a strong name.

Rule Description

According to Microsoft .NET Framework guidelines, assembly should always be signed with a strong name. This rule applies to both DLL and EXE executables.

This rule offers several long-term advantages:
  • you can register the assembly in the global assembly cache (GAC);
  • the .NET runtime can detect whether the assembly has been tampered with;
  • assemblies called by your assembly can check the caller's identity.
Finally, if you use the assembly in a Smart Client application, a strong name enables the administrator of the client computer to relax Code Access Security (CAS) policy for only that specific assembly (or for all assemblies from your company).

This rule is similar to FxCop rule 'Assemblies should have valid strong names', CheckId CA2210

Correcting Violations

The rule provides the following auto-correct options:
  • Create .snk key file and sign assembly with a strong name using System.Reflection.AssemblyKeyFileAttribute attribute.
  • Use existing .snk key file for signing assembly with a strong name using System.Reflection.AssemblyKeyFileAttribute attribute.

Rule Instances

Instances of this rule in the built-in profile:
  • Assemblies should have valid strong names.


Do not declare externally visible instance fields

Rule ID: DE00014

Problem

An externally visible instance field declared in the public class.

Rule Description

According to Microsoft .NET Framework guidelines, public instance fields should neve be defined. Private fields wrapped inside public properties should be used instead. Such approach will allow to validate the incoming value before it's assigned to the private field. Even if the validation of the value in the current class do not required, using a property enables inheritors to apply more restrictive validation criteria. Fields do not enable values validation.

This rule is similar to FxCop rule 'Do not declare visible instance fields', CheckId CA1051

Correcting Violations

The rule provides the following auto-correct options:
  • Change field modifier.
  • Create property from the field and set its modifier.
  • Create property from the field with name and modifier specified.

Rule Instances

Instances of this rule in the built-in profile:
  • Do not declare externally visible instance fields.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System.Drawing

Public Class Sample

  Public BackColor As Color

  ...

End Class

' This is the correct implementation

Imports System.Drawing

Public Class Sample

  Private m_BackColor As Color

  Public Property BackColor() As Color
    Get
        Return m_BackColor
    End Get
    Set (ByVal Value As Color)
      If Value = Color.Black Then
        Throw New ArgumentException("Invalid color value.")
      End If
      m_BackColor = Value
    End Set
  End Property

End Class

[C#]

// This code will trigger the rule violation

using System.Drawing;

public class Sample
{

  public Color BackColor;

  ...

}

// This is the correct implementation

using System.Drawing;

public class Sample
{

  private Color m_BackColor;

  public Color BackColor
  {
    get
    {
        return m_BackColor;
    }

    set
    {
      if (value == Color.Black)
      {
        throw new ArgumentException("Invalid color value.");
      }
      m_BackColor = value;
    }
  }

}


Do not declare protected members in sealed types

Rule ID: DE00002

Problem

A sealed (NotInheritable in Visual basic) public type declares a protected member.

Rule Description

According to Microsoft .NET Framework guidelines, a field, a property or a method should not be made public if that is not necessary.

Inheriting class can access or override protected member of the base class. A class marked as sealed (NotInheritable in Visual basic) cannot be used as a base class i.e. it cannot be inherited. So protected methods on sealed types cannot be called.

This rule is similar to FxCop rule 'Do not declare protected members in sealed types', CheckId CA1047

Correcting Violations

The rule provides the following auto-correct options:
  • Change type to inheritable.
  • Change the member(s) access level to specified.

Rule Instances

Instances of this rule in the built-in profile:
  • Do not declare protected members in sealed types.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System

Public NotInheritable Class Sample

    ' Violates the rule
    Protected Sub SomeMethod()

      ...

    End Sub

End Class

' This is the correct implementation

Imports System

Public NotInheritable Class Sample

    Public Sub SomeMethod()

      ...

    End Sub

End Class

- Or -

Imports System

' NotInheritable modifier has been removed
Public Class Sample

    Protected Sub SomeMethod()

      ...

    End Sub

End Class

[C#]

// This code will trigger the rule violation

using System;

public sealed class Sample
{

    // Violates the rule
    protected void SomeMethod()
    {

      ...

    }

}

// This is the correct implementation

using System;

public sealed class Sample
{

    public void SomeMethod()
    {

      ...

    }

}

- Or -

Imports System

// sealed modifier has been removed
public class Sample
{

    protected void SomeMethod()
    {

      ...

    }

}


Do not hide base class methods

Rule ID: DE00015

Problem

Type declares method with the same name and with the same number of parameters as one of its base methods.

Rule Description

A method in a derived type hides an identically named method in a base type, when derived method has the same number of parameters and type of one of parameters is a base type of the corresponding parameter in the base method.

This rule is similar to FxCop rule 'Do not hide base class methods', CheckId CA1061

Correcting Violations

The rule provides the following auto-correct options:
  • Rename the method and its references to the specified name.
  • Comment out the implementation of the method.

Rule Instances

Instances of this rule in the built-in profile:
  • Do not hide base class methods.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' Base class that will be inherited

Imports System

Public Class BaseType

    Public Sub SomeMethod(ByVal Param1 As Integer, ByVal Param2 As String, ByVal Param3 As String)

      ...

    End Sub

End Class

' This code will trigger the rule violation

Imports System

Public Class DerivedType
    Inherits BaseType

    ' The following method implementation hides base type method
    Public Sub SomeMethod(ByVal Param1 As Integer, ByVal Param2 As String, ByVal Param3 As Object)

      ...

    End Sub

End Class

' This is the correct implementation

Imports System

Public Class DerivedType
    Inherits BaseType

    ' The method renamed and does not hide base type method
    Public Sub RenamedMethod(ByVal Param1 As Integer, ByVal Param2 As String, ByVal Param3 As Object)

      ...

    End Sub

End Class

[C#]

// Base class that will be inherited

using System;

public class BaseType
{

    public void SomeMethod(int param1, string param2, string param3)
    {

      ...

    }

}

// This code will trigger the rule violation

using System;

public class DerivedType : BaseType
{

    // The following method implementation hides base type method
    public void SomeMethod(int param1, string param2, object param3)
    {

      ...

    }

}

// This is the correct implementation

using System;

public class DerivedType : BaseType
{

    // The method renamed and does not hide base type method
    public void RenamedMethod(int param1, string param2, object param3)
    {

      ...

    }

}


Do not override operator equals on reference types

Rule ID: DE00003

Problem

A public or nested public reference type overloads the equality operator or System.Object.Equals method.

Rule Description

Two references are equal only if they point to the same object. The default implementation of the equality operator is almost always correct for reference types.

If the reference type behaves like a built-in value type, then this rule can be excluded from the analysis.

This rule is similar to FxCop rule 'Do not override operator equals on reference types', CheckId CA1046

Correcting Violations

The rule provides the following auto-correct options:
  • Comment out the implementation of the System.Object.Equals method.
  • Comment out the implementation of the equality operator.
  • Comment out the implementation of the System.Object.Equals method and the implementation of the equality operator.

Rule Instances

Instances of this rule in the built-in profile:
  • Do not override operator equals on reference types.


Do not place assembly attributes outside of AssemblyInfo file

Rule ID: DE00020

Problem

Assembly-level attribute is placed outside of AssemblyInfo file.

Rule Description

AssemblyInfo.vb (AssemblyInfo.cs in C#) file is created automatically when you create an application with Microsoft Visual Studio. AssemblyInfo file should contain all assembly-level attributes such as assembly identity attributes, informational attributes, assembly manifest attributes, and strong name attributes.

The rule was specially created to ensure that all assembly-level attributes are placed in the AssemblyInfo file.

Correcting Violations

The rule provides the following auto-correct options:
  • Move assembly-level attribute to the AssemblyInfo file.

Rule Instances

Instances of this rule in the built-in profile:
  • Do not place assembly attributes outside of AssemblyInfo file.

Related Rules

Project should have AssemblyInfo file


Enum underlying type should be System.Int32 or one of the CLS-compliant integral types.

Rule ID: DE00004

Problem

The underlying type of a public enumeration is not System.Int32 or one of the CLS-compliant integral types.

Rule Description

According to Microsoft .NET Framework guidelines, System.Int32 should be used as a base type for the enumeration type.

For some specific reasons it may be necessary to use a nondefault base type. One of the CLS-compliant integral types, System.Byte, System.Int16, System.Int32, or System.Int64, should be used in that case. A non-CLS-compliant integral types such as System.UInt32, or System.UInt64 should never be used.

This rule is similar to FxCop rule 'Enum Storage should be Int32', CheckId CA1028

Correcting Violations

The rule provides the following auto-correct options:
  • Change the enumeration member type to System.Int32.
  • Change the enumeration member type to System.Int64.
  • Change the enumeration member type to System.Int16.
  • Change the enumeration member type to System.Byte.

Rule Instances

Instances of this rule in the built-in profile:
  • Enum underlying type should be Int32 or one of the CLS-compliant integral types.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

    ' Violation: non-CLS-compliant integral type is used
    Public Enum Answer As SByte
      No = 0
      Yes = 1
      Unknown = 3
    End Enum

' This is the correct implementation

    Public Enum Answer As Integer
      No = 0
      Yes = 1
      Unknown = 3
    End Enum

- Or -

    ' System.Int32 used by default
    Public Enum Answer
      No = 0
      Yes = 1
      Unknown = 3
    End Enum

[C#]

// This code will trigger the rule violation

    // Violation: non-CLS-compliant integral type is used
    public enum Answer : sbyte
    {
      No = 0,
      Yes = 1,
      Unknown = 3
    }

// This is the correct implementation

    public enum Answer : int
    {
      No = 0,
      Yes = 1,
      Unknown = 3
    }

- Or -

    // System.Int32 used by default
    public enum Answer
    {
      No = 0,
      Yes = 1,
      Unknown = 3
    }

Related Rules

Avoid name enum members with specified name


Implement Finalizer Correctly

Rule ID: DE00005

Problem

Finalize method is not implemented correctly. Some reasons for this problem are listed below:
  • Type derives from a type that implements the System.IDisposable interface and overrides a finalizer.
  • Type implements the System.IDisposable interface and has incorrect a destructor implementation.
  • Type implements the System.IDisposable interface and has incorrect a finalizer implementation.

Rule Description

According to Microsoft .NET Framework guidelines, types exposing both the Finalize method and the System.IDisposable interface must adopt the recommended Dispose-Finalize pattern.

This rule is similar to FxCop rule 'Implement IDisposable Correctly', CheckId CA1063

Correcting Violations

The rule provides the following auto-correct options:
  • Comment out destructor (finalizer) of the type, override (if needed) System.IDisposable.Dispose(Boolean) method and put the finalization snippet in the code path where disposing is False.
  • Find destructor and modify it so that it calls Dispose(False) and then returns.
  • Find finalizer and modify it so that it calls Dispose(False), calls base finalizer and then returns.

Rule Instances

Instances of this rule in the built-in profile:
  • Implement Finalizer Correctly.

Example

[Visual Basic]

' The following code shows Dispose-Finalize design pattern for a base class:

Public Class DisposableType
  Implements IDisposable

  ' Keep track of when the object is disposed.
  Protected disposed As Boolean = False

  ' This method disposes the base object's resources.
  Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        SyncLock Me
      If Not Me.disposed Then
        If disposing Then
          ' Release disposable objects used by this instance here.

          ...

        End If
        ' Release unmanaged resources here.

        ...

        Me.disposed = True
      End If
    End SyncLock
  End Sub

  Public Sub Dispose() Implements IDisposable.Dispose
    Dispose(True)

    ' Unregister object for finalization
    GC.SuppressFinalize(Me)
  End Sub

  Protected Overrides Sub Finalize()
    Try
      Dispose(False)
    Catch
      ' Deal with errors or just ignore them
    Finally
      ' Invoke the base object's Finalize method
      MyBase.Finalize()
    End Try
  End Sub

End Class

' The following code shows Dispose-Finalize design pattern for derived class:

Public Class DerivedDisposableType
  Inherits DisposableType

  ' This method disposes the derived object's resources.
  Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        SyncLock Me
      If Not Me.disposed Then
        If disposing Then
          ' Release disposable objects used by this instance here.

          ...

        End If
        ' Release unmanaged resources here.

        ...

        ' Call the base object's Dispose protected method.
        MyBase.Dispose(disposing)

      End If
    End SyncLock
  End Sub

  ' The derived class does not have a Finalize method
  ' or a Dispose method with parameters because it inherits
  ' them from the base class.
End Class

[C#]

// The following code shows Dispose-Finalize design pattern for a base class:

public class DisposableType: IDisposable
{

  // Keep track of when the object is disposed.
  protected bool disposed = false;

  // This method disposes the base object's resources.
  protected virtual void Dispose(bool disposing)
  {
        lock(this)
        {
      if (!this.disposed)
      {
        if (disposing)
        {
          // Release disposable objects used by this instance here.

          ...

        }
        // Release unmanaged resources here.

        ...

        this.disposed = true;
      }
    }
  }

  public void Dispose()
  {
    Dispose(true);

    // Unregister object for finalization
    GC.SuppressFinalize(this);
  }

  ~DisposableType()
  {
    Dispose(false);
  }

}

// The following code shows Dispose-Finalize design pattern for derived class:

public class DerivedDisposableType: DisposableType
{

  // This method disposes the derived object's resources.
  protected override void Dispose(bool disposing)
  {
    lock(this)
    {
      if (!this.disposed)
      {
        if (disposing)
        {
          // Release disposable objects used by this instance here.

          ...

        }
        // Release unmanaged resources here.

        ...

        // Call the base object's Dispose protected method.
        base.Dispose(disposing);

      }
    }

  }

  // The derived class does not have a Finalize method
  // or a Dispose method with parameters because it inherits
  // them from the base class.
}

Related Rules

Implement IDisposable Correctly


Implement IDisposable Correctly

Rule ID: DE00006

Problem

The System.IDisposable interface is not implemented correctly. Some reasons for this problem are listed below:
  • Type derives from type that implements the System.IDisposable interface and implements System.IDisposable interface repeatedly.
  • Type implements System.IDisposable interface and has Dispose() method with non Public modifier.
  • Type derives from type that implements the System.IDisposable and overrides Dispose() method.
  • Type implements the System.IDisposable interface and has incorrect Dispose() method implementation.
  • Type implements the System.IDisposable interface and has Dispose(Boolean) method with incorrect modifiers.

Rule Description

According to Microsoft .NET Framework guidelines, types exposing both the Finalize method and the System.IDisposable interface must adopt the recommended Dispose-Finalize pattern.

This rule is similar to FxCop rule 'Implement IDisposable Correctly', CheckId CA1063

Correcting Violations

The rule provides the following auto-correct options:
  • Remove System.IDisposable interface from the list of interfaces implemented by the type and add (if needed) overridden base class Dispose implementation (System.IDisposable.Dispose(Boolean)).
  • Find Dispose() method and change its modifier to Public
  • Remove overridden Dispose() method, add (if needed) overridden Dispose(Boolean) method and put the dispose snippet in the code path where disposing is True.
  • Modify Dispose() method so that it calls Dispose(True), then calls GC.SuppressFinalize() on the current object instance, and then returns.
  • Find Dispose(Boolean) method and change its modifier.

Rule Instances

Instances of this rule in the built-in profile:
  • Implement IDisposable Correctly.

Example

[Visual Basic]

' The following code shows Dispose-Finalize design pattern for a base class:

Public Class DisposableType
  Implements IDisposable

  ' Keep track of when the object is disposed.
  Protected disposed As Boolean = False

  ' This method disposes the base object's resources.
  Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        SyncLock Me
      If Not Me.disposed Then
        If disposing Then
          ' Release disposable objects used by this instance here.

          ...

        End If
        ' Release unmanaged resources here.

        ...

        Me.disposed = True
      End If
    End SyncLock
  End Sub

  Public Sub Dispose() Implements IDisposable.Dispose
    Dispose(True)

    ' Unregister object for finalization
    GC.SuppressFinalize(Me)
  End Sub

  Protected Overrides Sub Finalize()
    Try
      Dispose(False)
    Catch
      ' Deal with errors or just ignore them
    Finally
      ' Invoke the base object's Finalize method
      MyBase.Finalize()
    End Try
  End Sub

End Class

' The following code shows Dispose-Finalize design pattern for derived class:

Public Class DerivedDisposableType
  Inherits DisposableType

  ' This method disposes the derived object's resources.
  Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        SyncLock Me
      If Not Me.disposed Then
        If disposing Then
          ' Release disposable objects used by this instance here.

          ...

        End If
        ' Release unmanaged resources here.

        ...

        ' Call the base object's Dispose protected method.
        MyBase.Dispose(disposing)

      End If
    End SyncLock
  End Sub

  ' The derived class does not have a Finalize method
  ' or a Dispose method with parameters because it inherits
  ' them from the base class.
End Class

[C#]

// The following code shows Dispose-Finalize design pattern for a base class:

public class DisposableType: IDisposable
{

  // Keep track of when the object is disposed.
  protected bool disposed = false;

  // This method disposes the base object's resources.
  protected virtual void Dispose(bool disposing)
  {
        lock(this)
        {
      if (!this.disposed)
      {
        if (disposing)
        {
          // Release disposable objects used by this instance here.

          ...

        }
        // Release unmanaged resources here.

        ...

        this.disposed = true;
      }
    }
  }

  public void Dispose()
  {
    Dispose(true);

    // Unregister object for finalization
    GC.SuppressFinalize(this);
  }

  ~DisposableType()
  {
    Dispose(false);
  }

}

// The following code shows Dispose-Finalize design pattern for derived class:

public class DerivedDisposableType: DisposableType
{

  // This method disposes the derived object's resources.
  protected override void Dispose(bool disposing)
  {
    lock(this)
    {
      if (!this.disposed)
      {
        if (disposing)
        {
          // Release disposable objects used by this instance here.

          ...

        }
        // Release unmanaged resources here.

        ...

        // Call the base object's Dispose protected method.
        base.Dispose(disposing);

      }
    }

  }

  // The derived class does not have a Finalize method
  // or a Dispose method with parameters because it inherits
  // them from the base class.
}

Related Rules

Implement Finalizer Correctly


Interface methods should be callable by child types

Rule ID: DE00020

Problem

An unsealed public type implements explicitly a method of a public interface and does not provide an alternative access to the base implementation of the method.

Rule Description

If a base type, which is not sealed and externally visible, explicitly implements an interface with nonpublic members, ensure that derived types can access and override these members.

This rule is similar to FxCop rule 'Do not override operator equals on reference types', CheckId CA1033

Correcting Violations

The rule provides the following auto-correct options:
  • Mark a type as NotInheritable (sealed in C#)
  • Change method modifier to Protected Overridable (Visual Basic only)
  • Add a new method which is visible to derived types (C# only)

Rule Instances

Instances of this rule in the built-in profile:
  • Interface methods should be callable by child types.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Public Class TestClass
  Implements IComparable

  ' Violates the rule
  Private Function CompareTo(ByVal obj As Object) As Integer _
    Implements System.IComparable.CompareTo

    ' ...

  End Function

End Class

' This is the correct implementation

Public Class TestClass
  Implements IComparable

  Protected Overridable Function CompareTo(ByVal obj As Object) As Integer _
    Implements System.IComparable.CompareTo

    ' ...

  End Function

End Class

[C#]

// This code will trigger the rule violation

public class TestClass: IComparable
{

  // Violates the rule
  int IComparable.CompareTo(object obj)
  {
    // Actual comparison
    return 0;
  }
}

// This is the correct implementation

public class TestClass: IComparable
{
  int IComparable.CompareTo(object obj)
  {

    return CompareTo(obj);

  }

  protected virtual int CompareTo(object obj)
  {
    // Actual comparison
    return 0;
  }

}


Interface should have an implementation

Rule ID: DE00018

Problem

Interface should have an implementation.

Rule Description

Provide at least one type that is an implementation of an interface.

Doing this helps to validate the design of the interface. For example, System.Collections.Generic.List<T> is an implementation of the System.Collections.Generic.IList<T> interface.

Correcting Violations

The rule provides the following auto-correct options:
  • Comment out an interface.

Rule Instances

Instances of this rule in the built-in profile:
  • Interface should have an implementation.


Mark assembly with a specified attribute

Rule ID: DE00007

Problem

An assembly does not have one of the following attributes applied to it: System.CLSCompliantAttribute, System.AssemblyVersionAttribute, or System.Runtime.InteropServices.ComVisibleAttribute.

Rule Description

According to Microsoft .NET Framework guidelines, an assembly should have the following attributes applied:
  • System.CLSCompliantAttribute: Mark the assembly with a System.CLSCompliantAttribute attribute in a class library project to ensure that all its types and members are compliant with the Common Language Specification (CLS) and can be called by any other .NET language.
  • System.AssemblyVersionAttribute: The version number concurs to create the strong name of an assembly. If System.AssemblyVersionAttribute attribute is omitted, the assembly has no version. If an asterisk ("*") is used in the version number, the version number will change each time the assembly is recompiled. The version number should be changed when a new version of the assembly is published.
  • System.Runtime.InteropServices.ComVisibleAttribute: Attribute controls accessibility of an individual managed type or member, or of all types within an assembly, to COM. Assemblies should explicitly indicate COM visibility. The contents of the assembly are visible to COM clients by default, if the attribute is not present.
This rule is similar to the following FxCop rules:
  • 'Mark assemblies with assembly version', CheckId CA1016
  • 'Mark assemblies with CLSCompliant', CheckId CA1014
  • 'Mark assemblies with ComVisible', CheckId CA1017

Correcting Violations

The rule provides the following auto-correct options:
  • Apply missing attribute to the assembly.

Configurable Properties

  • AttributeToCheck - Certain Attribute to be checked.

Rule Instances

Instances of this rule in the built-in profile:
  • Mark assemblies with assembly version.
  • Mark assemblies with CLSCompliant
  • Mark assemblies with ComVisible

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

<Assembly:AssemblyVersion("1.2.*")>

' This is the correct implementation

<Assembly:AssemblyVersion("1.2.3.4")>

<Assembly:CLSCompliant(True)>

<Assembly:System.Runtime.InteropServices.ComVisible(False)>

[C#]

// This code will trigger the rule violation

[assembly:AssemblyVersion("1.2.*")]

// This is the correct implementation

[assembly:AssemblyVersion("1.2.3.4")]

[assembly:CLSCompliant(true)]

[assembly:System.Runtime.InteropServices.ComVisible(false)]


Nested types should not be visible

Rule ID: DE00009

Problem

Public type contains the nested public type that does not implement System.Collections.IEnumerator interface.

Rule Description

According to Microsoft .NET Framework guidelines, private or internal (Friend in Visual Basic) scope qulifier should be used for nested types.

Nested types are useful for encapsulating private implementation details of the containing type and should not be externally visible. A type should be nested if it is used only by the type that encloses it; therefore, in most cases there is no reason for making the nested type public.

Exception: Nested enumerators and comparers can be given public scope.

This rule is similar to FxCop rule 'Nested types should not be visible', CheckId CA1034

Correcting Violations

The rule provides the following auto-correct options:
  • Change the nested type modifier.
  • Move the nested type from its parent type.

Rule Instances

Instances of this rule in the built-in profile:
  • Nested types should not be visible.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

  Imports System

  Namespace SampleLibrary

    Public Class ParentSample

      ' Violation: nested type should not be public
      Public Class NestedSample

        Public Sub New()

          ...

        End Sub

      End Class

      Public Sub New()

        ...

      End Sub

    End Class

  End Namespace

' This is the correct implementation

  Imports System

  Namespace SampleLibrary

    Public Class ParentSample

      Private Class NestedSample

        Public Sub New()

          ...

        End Sub

      End Class

      Public Sub New()

        ...

      End Sub

    End Class

  End Namespace

Or

  Imports System

  Namespace SampleLibrary

    Public Class ParentSample

      Public Sub New()

        ...

      End Sub

    End Class

    ' nested class moved from its parent type
    Public Class NestedSample

      Public Sub New()

        ...

      End Sub

    End Class

  End Namespace

[C#]

// This code will trigger the rule violation

  using System;

  namespace SampleLibrary
  {

    public class ParentSample
    {

      // Violation: nested type should not be public
      public class NestedSample
      {

        public NestedSample()
        {

          ...

        }

      }

      public ParentSample()
      {

        ...

      }

    }

  }

// This is the correct implementation

  using System;

  namespace SampleLibrary
  {

    public class ParentSample
    {

      private class NestedSample
      {

        public ParentSample()
        {

          ...

        }

      }

      public ParentSample()
      {

        ...

      }

    }

  }

Or

  using System;

  mamespace SampleLibrary
  {

    public class ParentSample
    {

      public ParentSample()
      {

        ...

      }

    }

    // nested class moved from its parent type
    public class NestedSample
    {

      public NestedSample()
      {

        ...

      }

    }

  }


Project should have AssemblyInfo file

Rule ID: DE00019

Problem

Project does not contain AssemblyInfo file.

Rule Description

AssemblyInfo.vb (AssemblyInfo.cs in C#) file is created automatically when you create an application with Microsoft Visual Studio. AssemblyInfo file should contain all assembly-level attributes such as assembly identity attributes, informational attributes, assembly manifest attributes, and strong name attributes.

The rule was specially created to ensure that project contains AssemblyInfo file.

Correcting Violations

The rule provides the following auto-correct options:
  • Add AssemblyInfo file to project.

Rule Instances

Instances of this rule in the built-in profile:
  • Project should have AssemblyInfo file.

Related Rules

Do not place assembly attributes outside of AssemblyInfo file


Type that contains only static members should be sealed (NotInheritable)

Rule ID: DE00010

Problem

A sealed (NotInheritable for Visual Basic) modifier does not set for a public or protected type that contains static members only.

Rule Description

According to Microsoft .NET Framework guidelines, a type that is not meant to be inherited should be marked with the sealed (C#) or NotInheritable (Visual Basic) modifier. If a type containing static members only, then it does not provide any functionality that can be overridden in a derived type; therefore, it is not designed to be inherited.

A sealed type performs slightly better because all its properties and methods are implicitly sealed and the compiler can often inline them.

This rule is similar to FxCop rule 'Static holder types should be sealed', CheckId CA1052

Correcting Violations

The rule provides the following auto-correct options:
  • Change type modifier to sealed (NotInheritable for Visual Basic).

Rule Instances

Instances of this rule in the built-in profile:
  • Type that contains only static members should be sealed (NotInheritable).

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System

Namespace SampleLibrary

  Public Class StaticsOnly

      Private Shared _staticField As String

      Shared Property StaticProperty As String
          Get
              Return _staticField
          End Get
          Set
              _staticField = Value
          End Set
      End Property

      Private Sub New()
      End Sub

      Shared Sub StaticMethod()
      End Sub

  End Class

End Namespace

' This is the correct implementation

Imports System

Namespace SampleLibrary

  Public NotInheritable Class StaticsOnly

      Private Shared _staticField As String

      Shared Property StaticProperty As String
          Get
              Return _staticField
          End Get
          Set
              _staticField = Value
          End Set
      End Property

      Private Sub New()
      End Sub

      Shared Sub StaticMethod()
      End Sub

  End Class

End Namespace

[C#]

// This code will trigger the rule violation

using System;

namespace SampleLibrary
{

  public class StaticsOnly
  {

      private static string_staticField;

      public static string StaticProperty
      {
          get
          {
              return _staticField;
          }
          set
          {
              _staticField = value;
          }
      }

      private StaticsOnly()
      {
      }

      public static void StaticMethod()
      {
      }

  }

}

// This is the correct implementation

using System;

namespace SampleLibrary
{

  public sealed class StaticsOnly
  {

      private static string_staticField;

      public static string StaticProperty
      {
          get
          {
              return _staticField;
          }
          set
          {
              _staticField = value;
          }
      }

      private StaticsOnly()
      {
      }

      public static void StaticMethod()
      {
      }

  }

}

Related Rules

Type that contains only static members should not have public or protected constructors


Type that contains only static members should not have public or protected constructors

Rule ID: DE00011

Problem

A public or nested public type contains static members only, but has a public or protected default constructor.

Rule Description

Creating an instance does not provide access to any of the type's members, if the type contains static members only. Calling static members does not require an instance of the type; therefore the constructor is unnecessary.

This rule is similar to FxCop rule 'Static holder types should not have constructors', CheckId CA1053

Correcting Violations

The rule provides the following auto-correct options:
  • Change constructor(s) modifier to Private.
  • Comment out constructor(s) in the type.

Rule Instances

Instances of this rule in the built-in profile:
  • Type that contains only static members should not have public or protected constructors.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System

Namespace SampleLibrary

  Public Class StaticsOnly

      Private Shared _staticField As String

      Shared Property StaticProperty As String
          Get
              Return _staticField
          End Get
          Set
              _staticField = Value
          End Set
      End Property

      ' Violation: unnecessary public constructor
      Public Sub New()
      End Sub

      Shared Sub StaticMethod()
      End Sub

  End Class

End Namespace

- Or -

Imports System

Namespace SampleLibrary

  ' Violation: the Visual Basic compiler
  ' will create a default public constructor.
  Public Class StaticsOnly

      Private Shared _staticField As String

      Shared Property StaticProperty As String
          Get
              Return _staticField
          End Get
          Set
              _staticField = Value
          End Set
      End Property

      Shared Sub StaticMethod()
      End Sub

  End Class

End Namespace

' This is the correct implementation

Imports System

Namespace SampleLibrary

  Public Class StaticsOnly

      Private Shared _staticField As String

      Shared Property StaticProperty As String
          Get
              Return _staticField
          End Get
          Set
              _staticField = Value
          End Set
      End Property

      Private Sub New()
      End Sub

      Shared Sub StaticMethod()
      End Sub

  End Class

End Namespace

[C#]

// This code will trigger the rule violation

using System;

namespace SampleLibrary
{

  public class StaticsOnly
  {

      private static string _staticField;

      public static string StaticProperty
      {
          get
          {
              return _staticField;
          }
          set
          {
              _staticField = value;
          }
      }

      // Violation: unnecessary public constructor
      public StaticsOnly()
      {
      }

      public static void StaticMethod()
      {
      }

  }

}

- Or -

using System;

namespace SampleLibrary
{

  // Violation: C# compiler will create
  // a default public constructor.
  public class StaticsOnly
  {

      private static string _staticField;

      public static string StaticProperty
      {
          get
          {
              return _staticField;
          }
          set
          {
              _staticField = value;
          }
      }

      public static void StaticMethod()
      {
      }

  }

}

// This is the correct implementation

using System;

namespace SampleLibrary
{

  public class StaticsOnly
  {

      private static string _staticField;

      public static string StaticProperty
      {
          get
          {
              return _staticField;
          }
          set
          {
              _staticField = value;
          }
      }

      private StaticsOnly()
      {
      }

      public static void StaticMethod()
      {
      }

  }

}

Related Rules

Type that contains only static members should be sealed (NotInheritable)


Types that own disposable fields should be disposable

Rule ID: DE00012

Problem

Type has an instance field that is the System.IDisposable type, but does not implement the System.IDisposable interface.

Rule Description

According to Microsoft .NET Framework guidelines, the System.IDisposable interface should be implemented if a method in the type creates one or more instances of other disposable objects (a disposable object is an object that implements the System.IDisposable interface) and the method doesn't invoke the objects' Dispose method before returning to the caller. A class that declares a System.IDisposable field should implement the System.IDisposable interface, because it indirectly owns an unmanaged resources.

This rule is similar to FxCop rule 'Types that own disposable fields should be disposable', CheckId CA1001

Correcting Violations

The rule provides the following auto-correct options:
  • Implement Dispose-Finalize pattern for the type.

Rule Instances

Instances of this rule in the built-in profile:
  • Types that own disposable fields should be disposable.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System
Imports System.Data
Imports System.Data.OleDb

Namespace SampleLibrary

  Public Class DbManipulator

    Private _con As OleDbConnection

    Public Sub BeginDbProcess()
      ' Create and use the connection, leave it open
      _con = New OleDbConnection()

      ...

    End Sub

    Public Sub EndDbProcess()
      ' use the connection, then close it
      If Not _con Is Nothing Then

        ...

        _con.Close()
      End If
    End Sub

  End Class

End Namespace

' This is the correct implementation

Imports System
Imports System.Data
Imports System.Data.OleDb

Namespace SampleLibrary

  Public Class DbManipulator
    Implements IDisposable

    Private _con As OleDbConnection

    Public Sub BeginDbProcess()
      ' Create and use the connection, leave it open
      _con = New OleDbConnection()

      ...

    End Sub

    Public Sub EndDbProcess()
      ' use the connection, then close it
      If Not _con Is Nothing Then

        ...

        _con.Close()
      End If
    End Sub

    Public Sub Dispose() Implements IDisposable.Dispose
      If Not _con Is Nothing Then
        _con.Close()
      End If
    End Sub

  End Class

End Namespace

[C#]

// This code will trigger the rule violation

using System;
using System.Data;
using System.Data.OleDb;

namespace SampleLibrary
{

  public class DbManipulator
  {

    private OleDbConnection _con;

    public void BeginDbProcess()
    {
      // Create and use the connection, leave it open
      _con = new OleDbConnection();

      ...

    }

    public void EndDbProcess()
    {
      // use the connection, then close it
      if (_con != null)
      {

        ...

        _con.Close();
      }
    }

  }

}

// This is the correct implementation

using System;
using System.Data;
using System.Data.OleDb;

namespace SampleLibrary
{

  public class DbManipulator: IDisposable
  {

    private OleDbConnection _con;

    public void BeginDbProcess()
    {
      // Create and use the connection, leave it open
      _con = new OleDbConnection();

      ...

    }

    public void EndDbProcess()
    {
      // use the connection, then close it
      if (_con != null)
      {

        ...

        _con.Close();
      }
    }

    public void Dispose()
    {
      if (_con != null)
      {
        _con.Close();
      }
    }

  }

}

Related Rules

Types that own unmanaged resources should be disposable


Types that own unmanaged resources should be disposable

Rule ID: DE00013

Problem

A type has unmanaged field, but does not implement the System.IDisposable interface.

Rule Description

If a type has System.IntPtr, System.UIntPtr, and System.Runtime.InteropServices.HandleRef fields, than it most likely stores pointers to unmanaged resources. Such types should implement the System.IDisposable interface to allow callers to release allocated unmanaged resources.

Types must adopt the recommended Dispose-Finalize design pattern to implement the System.IDisposable interface and clean up unmanaged resources.

The recommended design pattern to clean up unmanaged resources is to provide both an implicit and an explicit means to free those resources using the System.Object.Finalize method and the System.IDisposable.Dispose method, respectively. that allocate unmanaged resources should implement IDisposable According to Microsoft .NET Framework guidelines, the System.IDisposable interface should be implemented if a method in the type creates one or more instances of other disposable objects (a disposable object is an object that implements the System.IDisposable interface) and the method doesn't invoke the objects' Dispose method before returning to the caller. A class that declares a System.IDisposable field should implement the System.IDisposable interface, because it indirectly owns an unmanaged resources.

This rule is similar to FxCop rule 'Types that own native resources should be disposable', CheckId CA1049

Correcting Violations

The rule provides the following auto-correct options:
  • Implement Dispose-Finalize pattern for the type.

Rule Instances

Instances of this rule in the built-in profile:
  • Types that own unmanaged resources should be disposable.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Public Class IncorrectType

  Private _someUnmanagedResource As UIntPtr

  Sub New()
    ' Allocate the unmanaged resource
    _someUnmanagedResource = ...
  End Sub

End Class

' This is the correct implementation

  Public Class CorrectType
    Implements IDisposable

    Private _someUnmanagedResource As UIntPtr
    Protected disposed As Boolean = False

    Sub New()
      ' Allocate the unmanaged resource ...
      _someUnmanagedResource = ...
    End Sub

    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
      If Not Me.disposed Then
        If disposing Then

          ...

        End If

        ' Release unmanaged resources
        ...

        _someUnmanagedResource = IntPtr.Zero

        Me.disposed = True

      End If
    End Sub

    Public Sub Dispose() Implements IDisposable.Dispose
      Dispose(True)
      GC.SuppressFinalize(Me)
    End Sub

    Protected Overrides Sub Finalize()
      Try
        Dispose(False)
      Catch
        ' Deal with errors or just ignore them
      Finally
        ' Invoke the base object's Finalize method
        MyBase.Finalize()
      End Try
    End Sub

  End Class

[C#]

// This code will trigger the rule violation

public class IncorrectType
{

  private UIntPtr _someUnmanagedResource;

  IncorrectType()
  {
    // Allocate the unmanaged resource
    _someUnmanagedResource = ...
  }

}

// This is the correct implementation

  public class CorrectType : IDisposable
  {

    private UIntPtr _someUnmanagedResource;
    protected bool disposed = false;

    CorrectType()
    {
      // Allocate the unmanaged resource ...
      _someUnmanagedResource = ...
    }

    protected virtual void Dispose(bool disposing)
    {
          lock(this)
          {
        if (!this.disposed)
        {
          if (disposing)
          {
            // Release disposable objects used by this instance here.

            ...

          }
          // Release unmanaged resources here.

          ...

          _someUnmanagedResource = IntPtr.Zero;

          this.disposed = true;
        }
      }
    }

    public void Dispose()
    {
      Dispose(true);

      // Unregister object for finalization
      GC.SuppressFinalize(this);
    }

    ~DisposableType()
    {
      Dispose(false);
    }

  }

Related Rules

Types that own disposable fields should be disposable


Exception Handling Rules

This section will guide you through the set of Exception Handling Rules.

Click on any of the links below to go directly to the corresponding rule.

Do not catch general exception types

Do not handle non-CLS-compliant exceptions

Do not raise specified exception types

Do not re-throw exceptions explicitly


Do not catch general exception types

Rule ID: EX00001

Problem

General exception type (System.Exception or System.SystemException) is caught in a catch statement.

Or

A general catch clause is used.

Rule Description

According to Microsoft .NET Framework guidelines, it is not recommended to catch general System.Exception or System.SystemException. More specific exception should be caught. For the second case, the general exception should be re-thrown in the catch block.

This rule is similar to FxCop rule 'Do not catch general exception types', CheckId CA1031

Correcting Violations

The rule provides the following auto-correct options:
  • Change type of the exception to the specified type.

Configurable Properties

  • CheckForRethrow - Check for re-throw the exception;
  • Exceptions - A comma-separated list of the exception types.

Rule Instances

Instances of this rule in the built-in profile:
  • Do not catch general exception types.
  • Do not catch the specific exception types.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

  Imports System
  Imports System.IO
  Imports System.Text

  Public Class SampleFileReader

    Private _path As String = "c:\temp\TestFile.txt"

    Public Sub ReadData()

      Dim inputStream As FileStream

      ' Violation: General System.SystemException has been caught.
      Try
        inputStream = OpenRead(_path)
      Catch ex As SystemException
        Console.WriteLine("Unable to open file.")
      End Try

      Dim buffer(1024) As Byte
      Dim utf8 As UTF8Encoding = New UTF8Encoding(True)

      ' Violation: a non-specific exception has been caught.
      Try
        Do While inputStream.Read(buffer, 0, buffer.Length) > 0
            Console.WriteLine(utf8.GetString(buffer))
        Loop
      Catch
        Console.WriteLine("Unable to read file.")
      End Try

      inputStream.Close()

    End Sub
  End Class

' This is the correct implementation

  Imports System
  Imports System.IO
  Imports System.Text

  Public Class SampleFileReader

    Private _path As String = "c:\temp\TestFile.txt"

    Public Sub ReadData()

      Dim inputStream As FileStream

      Try
        inputStream = OpenRead(_path)
      Catch ex As FileNotFoundException
        Console.WriteLine("Unable to open file.")
      End Try

      Dim buffer(1024) As Byte
      Dim utf8 As UTF8Encoding = New UTF8Encoding(True)

      Try
        Do While inputStream.Read(buffer, 0, buffer.Length) > 0
            Console.WriteLine(utf8.GetString(buffer))
        Loop
      Catch
        Console.WriteLine("Unable to read file.")
        Throw
      End Try

      inputStream.Close()

    End Sub
  End Class

[C#]

// This code will trigger the rule violation

  using System;
  using System.IO;
  using System.Text;

  public class SampleFileReader
  {

    private string _path = @"c:\temp\TestFile.txt";

    public void ReadData()
    {

      FileStream inputStream;

      // Violation: General System.SystemException has been caught.
      try
      {
        inputStream = OpenRead(_path);
      }
      catch (SystemException ex)
      {
        Console.WriteLine("Unable to open file.");
      }

      byte[] buffer = new byte[1024];
      UTF8Encoding utf8 = new UTF8Encoding(true);

      // Violation: a non-specific exception has been caught.
      try
      {
        while (inputStream.Read(buffer, 0, buffer.Length) > 0)
        {
            Console.WriteLine(utf8.GetString(buffer));
        }
      }
      catch
      {
        Console.WriteLine("Unable to read file.");
      }

      inputStream.Close();

    }
  }

// This is the correct implementation

  using System;
  using System.IO;
  using System.Text;

  public class SampleFileReader
  {

    private string _path = @"c:\temp\TestFile.txt";

    public void ReadData()
    {

      FileStream inputStream;

      try
      {
        inputStream = OpenRead(_path);
      }
      catch (FileNotFoundException ex)
      {
        Console.WriteLine("Unable to open file.");
      }

      byte[] buffer = new byte[1024];
      UTF8Encoding utf8 = new UTF8Encoding(true);

      try
      {
        while (inputStream.Read(buffer, 0, buffer.Length) > 0)
        {
            Console.WriteLine(utf8.GetString(buffer));
        }
      }
      catch
      {
        Console.WriteLine("Unable to read file.");
        throw;
      }

      inputStream.Close();

    }

  }

Related Rules

Do not handle non-CLS-compliant exceptions

Do not raise specified exception types

Do not re-throw exceptions explicitly


Do not handle non-CLS-compliant exceptions

Rule ID: EX00002

Problem

Non-CLS-compliant exceptions (exceptions that don't derive from System.Exception) caught using parameterless catch block.

Rule Description

Catching non-CLS-compliant exceptions can hide run-time problems from the library user.

This rule is similar to FxCop rule 'Do not catch general exception types', CheckId CA1031

Correcting Violations

The rule provides the following auto-correct options:
  • Catch the specific exception using a parameter catch block.

Rule Instances

Instances of this rule in the built-in profile:
  • Do not handle non-CLS-compliant exceptions.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System.IO
Imports System.Text
Imports System.Diagnostics

Public Class FileUtility

  Public Function GetFileContentIncorrectly(fileName As String) As String

    Dim returnValue As String = ""

    Try

      Using sr As New StreamReader(fileName, Encoding.ASCII)
        returnValue = sr.ReadToEnd()
      End Using

    Catch ' Violated the rule because catched a non-specific exception.
        Debug.WriteLine("Unhandled exception.")
    End Try

    GetFileContentIncorrectly = returnValue

  End Function

End Class

' This is the correct implementation

Imports System.IO
Imports System.Text
Imports System.Diagnostics

Public Class FileUtility

  Public Function GetFileContentCorrectly1(fileName As String) As String

    Dim returnValue As String = ""

    Try

      Using sr As new StreamReader(fileName, Encoding.ASCII)
        returnValue = sr.ReadToEnd()
      End Using
    ' Do not violate because catched a specific exception.
    Catch ex As FileNotFoundException
      Debug.WriteLine("File not found: " + fileName)
    End Try

    GetFileContentCorrectly1 = returnValue
  End Function

  Public Function GetFileContentCorrectly2(fileName As String) As String

    Dim returnValue As String = ""

    Try
        Using sr As new StreamReader(fileName, Encoding.ASCII)
            returnValue = sr.ReadToEnd()
        End Using
    ' Do not violate because re-throwed the generic exception
    Catch

        Debug.WriteLine("Unhandled exception in " + fileName)
        Throw

    End Try

    GetFileContentCorrectly2 = returnValue
  End Function

End Class

[C#]

// This code will trigger the rule violation

using System.IO;
using System.Text;
using System.Diagnostics;

class FileUtility
{
    public string GetFileContentIncorrectly(string fileName)
    {
        try
        {
            using (StreamReader sr = new StreamReader(fileName, Encoding.ASCII))
            {
                return sr.ReadToEnd();
            }
        }
        catch // Violated the rule because catched a non-specific exception.
        {
            Debug.WriteLine("Unhandled exception.");
        }

        return string.Empty;
    }
}

// This is the correct implementation

using System.IO;
using System.Text;
using System.Diagnostics;

class FileUtility
{
    public string GetFileContentCorrectly1(string fileName)
    {
        try
        {
            using (StreamReader sr = new StreamReader(fileName, Encoding.ASCII))
            {
                return sr.ReadToEnd();
            }
        }
        // Do not violate because catched a specific exception.
        catch (FileNotFoundException)
        {
            Debug.WriteLine("File not found: \"" + fileName + "\"");
        }

        return string.Empty;
    }

    public string GetFileContentCorrectly2(string fileName)
    {
        try
        {
            using (StreamReader sr = new StreamReader(fileName, Encoding.ASCII))
            {
                return sr.ReadToEnd();
            }
        }
        // Did not violate because re-throwed the generic exception
        catch
        {
            Debug.WriteLine("Unhandled exception in \"" + fileName + "\"");

            throw;
        }

        return string.Empty;
    }
}

Related Rules

Do not catch general exception types

Do not raise specified exception types

Do not re-throw exceptions explicitly


Do not raise specified exception types

Rule ID: EX00003

Problem

A method raises one of the special .NET exceptions or exception that is too general.

Rule Description

According to Microsoft .NET Framework guidelines, the following too general exceptions should not be thrown:
  • System.ApplicationException
  • System.Exception
  • System.SystemException
These exceptions are too general and therefore cannot provide the user with the sufficient information.

The following special .NET exception types should be thrown by the common language runtime only:
  • System.ExecutionEngineException
  • System.IndexOutOfRangeException
  • System.NullReferenceException
  • System.OutOfMemoryException
This rule is similar to FxCop rule 'Do not raise reserved exception types', CheckId CA2201

Correcting Violations

The rule provides the following auto-correct options:
  • Change type of the exception to the specified type.

Configurable Properties

  • ExceptionCategory - The category of the exception to check. Possible values: General, Reserved;
  • Exceptions - A comma-separated list of the exception types.

Rule Instances

Instances of this rule in the built-in profile:
  • Do not raise general exception types
  • Do not raise reserved exception types

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

  Imports System
  Imports System.IO
  Imports System.Text

  Public Class SampleFileReader

    Private _path As String

    Public Property Path() As Boolean

      Get
        Return _path
      End Get

      Set(ByVal value As String)
        If value Is Nothing Then
          ' Violation: reserved System.NullReferenceException exception raised
          Throw New System.NullReferenceException("Incorrect Path value")
        End If
        _path = value
      End Set

    End Property

  End Class

' This is the correct implementation

  Imports System
  Imports System.IO
  Imports System.Text

  Public Class SampleFileReader

    Private _path As String

    Public Property Path() As Boolean

      Get
        Return _path
      End Get

      Set(ByVal value As String)
        If value Is Nothing Then
          ' The type of the thrown exception changed to more specific type
          Throw New System.ArgumentNullException("Incorrect Path value")
        End If
        _path = value
      End Set

    End Property

  End Class

[C#]

// This code will trigger the rule violation

  using System;
  using System.IO;
  using System.Text;

  public class SampleFileReader
  {

    private string _path;

    public bool Path
    {

      get
      {
        return _path;
      }

      set
      {
        if (value == null)
        {
          // Violation: reserved System.NullReferenceException exception raised
          throw new System.NullReferenceException("Incorrect Path value");
        }
        _path = value;
      }

    }

  }

// This is the correct implementation

  using System;
  using System.IO;
  using System.Text;

  public class SampleFileReader
  {
    private string _path;

    public bool Path
    {

      get
      {
        return _path;
      }

      set
      {
        if (value == null)
        {
          // The type of the thrown exception changed to more specific type
          throw new System.ArgumentNullException("Incorrect Path value");
        }
        _path = value;
      }

    }

  }

Related Rules

Do not catch general exception types

Do not handle non-CLS-compliant exceptions

Do not re-throw exceptions explicitly


Do not re-throw exceptions explicitly

Rule ID: EX00004

Problem

The method throws exception that is explicitly specified in the throw statement.

Rule Description

The original exception object should not be re-throwed explicitly. Violation of this rule will complicate debugging and ruin the exception's stack trace.

This rule is similar to FxCop rule 'Rethrow to preserve stack details', CheckId CA2200

Correcting Violations

The rule provides the following auto-correct options:
  • Re-throw the exception without specifying the exception explicitly.

Rule Instances

Instances of this rule in the built-in profile:
  • Do not re-throw exceptions explicitly.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Sub SomeMethod()

  Try

    ' Do something

  Catch Ex As SpecificException

    ' Violation: re-throw exceptions explicitly
    Throw Ex

  End Try

End Sub

' This is the correct implementation

Sub SomeMethod()

  Try

    ' Do something

  Catch Ex As SpecificException

    Throw

  End Try

End Sub

[C#]

// This code will trigger the rule violation

void SomeMethod()
{

  try
  {

    // Do something

  }
  catch (SpecificException ex)
  {

    // Violation: re-throw exceptions explicitly
    throw ex;

  }

}

// This is the correct implementation

void SomeMethod()
{

  try
  {

    // Do something

  }
  catch (SpecificException ex)
  {

    throw;

  }

}

Related Rules

Do not catch general exception types

Do not handle non-CLS-compliant exceptions

Do not raise specified exception types


General Rules

This section will guide you through the set of General Rules.

Click on any of the links below to go directly to the corresponding rule.

Enforce Option Compare

Enforce Option Explicit

Enforce Option Strict

Enable Treat Compiler Warnings As Errors option

Enforce Warning Level 4

Externally visible types and members should have XML comments

Set all Windows Forms Designer settings correctly

Source file name should be pascal cased

Source file name should match public type name

Source file should contain only one public type

Source file should have a header


Enforce Option Compare

Rule ID: GE00001

Problem

The Option Compare statement does not specified explicitly.

Rule Description

The Option Compare statement declares the default comparison method to use when comparing string data. The Option Compare statement specifies the string comparison method (Binary or Text) for a class, module or structure. If an Option Compare statement is not included, the default text comparison method is Binary.

According to the coding guidelines and best practices for projects and solutions, the Option Compare statement should be explicitly specified.

Correcting Violations

The rule provides the following auto-correct options:
  • Set compiler option and VS IDE default Option Compare

Configurable Properties

  • OptionUsage - Set desired value for this compiler option. Possible values: Binary (set by default), Text.

Rule Instances

Instances of this rule in the built-in profile:
  • Enforce Option Compare.

Related Rules

Enforce Option Explicit

Enforce Option Strict

Set all Windows Forms Designer settings correctly


Enforce Option Explicit

Rule ID: GE00002

Problem

The Option Explicit statement does not specified explicitly.

Rule Description

The Option Explicit statement forces explicit declaration of all variables in a file. When Option Explicit appears in a file, you must explicitly declare all variables using the Dim or ReDim statements. If you attempt to use an undeclared variable name, an error occurs at compile time.

According to the coding guidelines and best practices for projects and solutions, the Option Explicit On statement should be explicitly specified. It will help to avoid incorrectly typing the name of an existing variable or to avoid confusion in code where the scope of the variable is not clear.

Correcting Violations

The rule provides the following auto-correct options:
  • Set compiler option and VS IDE default Option Explicit

Configurable Properties for the Rule

  • OptionUsage - Set desired value for this compiler option. Possible values: Off, On (set by default).

Rule Instances

Instances of this rule in the built-in profile:
  • Enforce Option Explicit.

Related Rules

Enforce Option Compare

Enforce Option Strict

Set all Windows Forms Designer settings correctly


Enforce Option Strict

Rule ID: GE00003

Problem

The Option Strict statement does not specified explicitly.

Rule Description

Visual Basic allows conversions of many data types to other data types. Data loss can occur when the value of one data type is converted to a data type with less precision or smaller capacity. A run-time error occurs if such a narrowing conversion fails. Option Strict ensures compile-time notification of these narrowing conversions so they can be avoided.

In addition to disallowing implicit narrowing conversions, Option Strict generates an error for late binding. An object is late bound when it is assigned to a variable that is declared to be of type Object.

According to the coding guidelines and best practices for projects and solutions, the Option Strict On statement should be explicitly specified, because Option Strict On provides strong typing, prevents unintended type conversions with data loss, disallows late binding, and improves performance.

Correcting Violations

The rule provides the following auto-correct options:
  • Set compiler option and VS IDE default Option Strict

Configurable Properties for the Rule

  • OptionUsage - Set desired value for this compiler option. Possible values: Off, On (set by default).

Rule Instances

Instances of this rule in the built-in profile:
  • Enforce Option Strict.

Related Rules

Enforce Option Compare

Enforce Option Explicit

Set all Windows Forms Designer settings correctly


Enable Treat Compiler Warnings As Errors option

Rule ID: GE00009

Problem

The Treat warnings as errors option is disabled for the project.

Rule Description

It is recommended practice to always have Treat Compiler Warnings As Errors option enabled.
Treating warnings as errors is a simple way to spot many potential problems and bugs in the source code.

Correcting Violations

The rule provides the following auto-correct options:
  • Enable the Treat warnings as errors option for the project.

Rule Instances

Instances of this rule in the built-in profile:
  • Enable Treat Compiler Warnings As Errors option.

Related Rules

Enforce Warning Level 4


Enforce Warning Level 4

Rule ID: GE00010

Problem

The project has Warning level value less than 4.

Rule Description

It is recommended practice to always compile the project with Warning Level 4.
Warning Level 4 option enforces compiler never suppress specific warnings.

Correcting Violations

The rule provides the following auto-correct options:
  • Set Warning level option to 4 for the project.

Rule Instances

Instances of this rule in the built-in profile:
  • Enforce Warning Level 4.

Related Rules

Enable Treat Compiler Warnings As Errors option


Externally visible types and members should have XML comments

Rule ID: GE00005

Problem

Externally visible type or member does not have XML comments.

Rule Description

XML comments should be used to document all public types and their public members in class libraries, Windows Forms control projects, and ASP.NET Web control projects.

XML comments have the following advantages:
  • XML documentation file can be easily generated, if enabled the XML Documentation File option on the Build page of the Project Properties dialog box. By deploying this file in the same directory as the DLL executable, developers using your types or controls can read your comments in Visual Studio .NET's Object Browser.
  • The NDoc can be used to create the technical documentation of the class library or control.

Correcting Violations

The rule provides the following auto-correct options:
  • Add XML Comment with IntelliComment content to the type.
  • Add XML Comment stub to the type or member.

Configurable Properties

  • EnforceCheckingAllProjects - Ignore 'XML Documentation' flag. Enforce the XML Comments rule on the entire project regardless of the 'XML documentation file' option setting.
  • IntelliCommentTemplate - T4 template for XML Comment with IntelliComment content. IntelliComments feature is based on the GhostDoc algorithm.
  • StubTemplate - XML Comment Stub Template. T4 template for XML Comment stub.

Rule Instances

Instances of this rule in the built-in profile:
  • Externally visible types and members should have XML comments.

Example

The following examples show public method with XML comment.

[Visual Basic]

''' <summary>
''' Retrieves a substring from this instance.
''' </summary>
''' <param name="startIndex">The index of the start of the substring.</param>
''' <param name="length">The number of characters in the substring.</param>
''' <returns>A substring that starts at a specified character position and has a specified length.</returns>
Public Function Substring (startIndex As Integer, length As Integer) As String

    ...

End Function

[C#]

/// <summary>
/// Retrieves a substring from this instance.
/// </summary>
/// <param name="startIndex">The index of the start of the substring.</param>
/// <param name="length">The number of characters in the substring.</param>
/// <returns>A substring that starts at a specified character position and has a specified length.</returns>
public string Substring(int startIndex, int length)
{

    ...

}


Set all Windows Forms Designer settings correctly

Rule ID: GE00004

Problem

Windows Forms Designer settings are incorrect.

Rule Description

You can set preferences for all the forms and projects you work with in the Windows Forms Designer.

Grid Size - Sets the spacing, in pixels, between horizontal and vertical gridlines on the designer. The default size is 8, 8.

Show Grid - Specifies whether designers display the sizing grid. By default, the grid is on.

SnapToGrid - Determines whether designers will snap objects and controls to the grid. In other words, the resizing and movement of elements on the designer are constrained to the GridSize increment when this feature is turned on. Having SnapToGrid turned on makes it easier to line up the various aspects of the user interface precisely, but limits the freedom with which one can place controls. By default, SnapToGrid is turned on.

Correcting Violations

Specify Windows Forms Designer settings for the project.

Configurable Properties for the Rule

  • GridWidth - Set the default grid width on designers;
  • GridHeight - Set the default grid height on designers;
  • ShowGrid - Sets if designers should display sizing grid by default;
  • SnapToGrid - Sets if designers should snap to grid by default.

Rule Instances

Instances of this rule in the built-in profile:
  • Set all Windows Forms Designer settings correctly.

Related Rules

Enforce Option Compare

Enforce Option Explicit

Enforce Option Strict


Source file name should be pascal cased

Rule ID: GE00008

Problem

The name of source file is not pascal cased.

Rule Description

This rule is created to ensure that the name of the file is cased correctly.
According to the coding guidelines names of source files should be Pascal Cased and named after the main type they contain.

Correcting Violations

The rule provides the following auto-correct options:
  • Rename file to the specified name.

Configurable Properties

  • FileNameCase - Set desired value of the case to check. Possible values: Camel, Pascal (set by default), Upper.

Rule Instances

Instances of this rule in the built-in profile:
  • Source file name should be pascal cased.

Related Rules

Source file name should match public type name

Source file should contain only one public type

Source file should have a header


Source file name should match public type name

Rule ID: GE00007

Problem

Source file contains public type and the name of the file does not match the name of the type.

Rule Description

This rule is created to ensure that the name of the file is the same as the name of the public type declared in this file.
According to the coding guidelines names of source files should be Pascal Cased and named after the main type they contain.

Correcting Violations

The rule provides the following auto-correct options:
  • Rename file to the specified name.
  • Rename type and its references to the specified name.

Rule Instances

Instances of this rule in the built-in profile:
  • Source file name should match public type name.

Related Rules

Source file name should be pascal cased

Source file should contain only one public type

Source file should have a header


Source file should contain only one public type

Rule ID: GE00006

Problem

Source file contains more than one public type.

Rule Description

According to the coding guidelines each source file should contain one public type definition only. This rule is created to ensure that.

Correcting Violations

The rule provides the following auto-correct options:
  • Move another public type to the separate souce file.

Rule Instances

Instances of this rule in the built-in profile:
  • Source file should contain only one public type.

Related Rules

Source file name should be pascal cased

Source file name should match public type name

Source file should have a header


Source file should have a header

Rule ID: GE00011

Problem

Source file does not have a header.

Rule Description

This rule is created to ensure that each source file has a header.
Headers are based on the T4 (Text Template Transformation Toolkit) templates. You can create your own T4 template or modify existing one.

Correcting Violations

The rule provides the following auto-correct options:
  • Add header to the file.

Configurable Properties

  • Template - T4 template for the file header.

Rule Instances

Instances of this rule in the built-in profile:
  • Source file should have a header.

Related Rules

Source file name should be pascal cased

Source file name should match public type name

Source file should contain only one public type


Globalization Rules

This section will guide you through the set of Globalization Rules.

Click on any of the links below to go directly to the corresponding rule.

Specify CultureInfo

Specify StringComparison


Specify CultureInfo

Rule ID: GL00001

Problem

There is an overload of the method with System.Globalization.CultureInfo or System.IFormatProvider parameter exists, but not called.

Rule Description

According to Microsoft .NET Framework guidelines, the culture-specific information should be explicitly specified if it is possible.

If System.Globalization.CultureInfo or System.IFormatProvider parameter is not specified explicitly, then methods of .NET Framework classes use default culture and formatting and, therefore, may produce results that will be incorrect for your scenarios.

The following methods are ignored by the rule:
  • System.Activator.CreateInstance
  • System.Resources.ResourceManager.GetObject
  • System.Resources.ResourceManager.GetString
This rule is similar to the following FxCop rules:
  • 'Specify CultureInfo', CheckId CA1304
  • 'Specify IFormatProvider', CheckId CA1305

Correcting Violations

The rule provides the following auto-correct options:
  • Call appropriate overload of a method and pass System.Globalization.CultureInfo.CurrentCulture as an argument.
  • Call appropriate overload of a method and pass System.Globalization.CultureInfo.InvariantCulture as an argument.

Configurable Properties

  • TypeName - System.Globalization.CultureInfo or System.IFormatProvider.

Rule Instances

Instances of this rule in the built-in profile:
  • Specify CultureInfo.
  • Specify IFormatProvider.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

  Imports System

  Public Class GlobalizationTest

    Public Sub ProcessInformation(number As Double, stringDate As String)

      Dim processDate As Date = Date.Parse(stringDate).AddDays(36)
      number += 123.45

      Console.WriteLine("Number: {0}", number.ToString())
      Console.WriteLine("Date: {0}", processDate.ToString())

    End Sub

  End Class

' This is the correct implementation

  Imports System
  Imports System.Globalization

  Public Class GlobalizationTest

    Public Sub ProcessInformation(number As Double, stringDate As String)

      Dim processDate As Date = Date.Parse(stringDate, CultureInfo.CurrentCulture).AddDays(36)
      number += 123.45

      Console.WriteLine("Number: {0}", number.ToString(CultureInfo.CurrentCulture))
      Console.WriteLine("Date: {0}", processDate.ToString(CultureInfo.CurrentCulture))

    End Sub

  End Class

[C#]

// This code will trigger the rule violation

  using System;

  public class GlobalizationTest
  {
    public void ProcessInformation(double number, string date)
    {
      DateTime processDate = DateTime.Parse(date).AddDays(36);
      number += 123.45;

      Console.WriteLine("Number: {0}", number.ToString());
      Console.WriteLine("Date: {0}", processDate.ToString());
    }
  }

// This is the correct implementation

  using System;
  using System.Globalization;

  public class GlobalizationTest
  {
    public void ProcessInformation(double number, string date)
    {
      DateTime processDate = DateTime.Parse(date, CultureInfo.CurrentCulture).AddDays(36);
      number += 123.45;

      Console.WriteLine("Number: {0}", number.ToString(CultureInfo.CurrentCulture));
      Console.WriteLine("Date: {0}", processDate.ToString(CultureInfo.CurrentCulture));
    }
  }


Specify StringComparison

Rule ID: GL00002

Problem

There is an overload of a method with System.StringComparison parameter exists, but it does not used.

Rule Description

According to Microsoft .NET Framework guidelines, System.StringComparison parameter should be explicitly specified if it is possible.

The following System.String methods provide an overload with a System.StringComparison parameter:
  • System.String.Compare
  • System.String.EndsWith
  • System.String.Equals
  • System.String.IndexOf
  • System.String.LastIndexOf
  • System.String.StartsWith
You should always use an overload that accepts a System.StringComparison enumeration value as a parameter, if you use one of thee methods.

This rule is similar to FxCop rule 'Specify StringComparison', CheckId CA1307

Correcting Violations

The rule provides the following auto-correct options:
  • Call appropriate overload of a method and pass System.StringComparison.CurrentCulture as an argument.
  • Call appropriate overload of a method and pass System.StringComparison.InvariantCulture as an argument.
  • Call appropriate overload of a method and pass System.StringComparison.Ordinal as an argument.

Rule Instances

Instances of this rule in the built-in profile:
  • Specify StringComparison.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

  Imports System

  Public Class GlobalizationTest

    Public Sub ProcessInformation(stringToCheck As String, correctEnding As String)

      If !stringToCheck.EndsWith(correctEnding) Then
        Console.WriteLine("Provided data is incorrect.")
      End If

    End Sub

  End Class

' This is the correct implementation

  Imports System

  Public Class GlobalizationTest

    Public Sub ProcessInformation(stringToCheck As String, correctEnding As String)

      If !stringToCheck.EndsWith(correctEnding, System.StringComparison.CurrentCulture) Then
        Console.WriteLine("Provided data is incorrect.")
      End If

    End Sub

  End Class

[C#]

// This code will trigger the rule violation

  using System;

  public class GlobalizationTest
  {
    public void ProcessInformation(string stringToCheck, string correctEnding)
    {
      if (!stringToCheck.EndsWith(correctEnding))
      {
        Console.WriteLine("Provided data is incorrect.");
      }
    }
  }

// This is the correct implementation

  using System;

  public class GlobalizationTest
  {
    public void ProcessInformation(string stringToCheck, string correctEnding)
    {
      if (!stringToCheck.EndsWith(correctEnding, System.StringComparison.CurrentCulture))
      {
        Console.WriteLine("Provided data is incorrect.");
      }
    }
  }


Interoperability Rules

This section will guide you through the set of Interoperability Rules.

Click on any of the links below to go directly to the corresponding rule.

Avoid Long type arguments for VB6 clients

Avoid non-public fields in ComVisible value types

Avoid static members in ComVisible types

Com visible types should be creatable

PInvokes should not be visible


Avoid Long type arguments for VB6 clients

Rule ID: IN00001

Problem

Type marked as COM visible and declares method that takes a System.Int64 argument.

Rule Description

According to Microsoft .NET Framework guidelines, .NET components that are meant to be exposed to COM clients shouldn't use features that COM-based clients can't see. Or they should provide alternative ways for COM clients to accesss these features.

The class shouldn't expose methods or properties that take or return System.Int64 values because they can't be handled by Visual Basic 6 clients.

This rule is similar to FxCop rule 'Avoid int64 arguments for VB6 clients', CheckId CA1406

Correcting Violations

The rule provides the following auto-correct options:
  • Change parameter return type on System.Int32
  • Change parameter return type on System.Decimal
  • Add System.Runtime.InteropServices.ComVisibleAttribute attribute to the method and set it to False

Rule Instances

Instances of this rule in the built-in profile:
  • Avoid Long type arguments for VB6 clients.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System
Imports System.Runtime.InteropServices

<Assembly: ComVisibleAttribute(False)>

Namespace MyInteropLibrary

   <ComVisibleAttribute(True)> _
   Public Class MyComClass

      Public Sub SomeMethod(Param1 As Long)
      End Sub

   End Class

End Namespace

' This is the correct implementation

Imports System
Imports System.Runtime.InteropServices

<Assembly: ComVisibleAttribute(False)>

Namespace MyInteropLibrary

   <ComVisibleAttribute(True)> _
   Public Class MyComClass

      <ComVisibleAttribute(False)> _
      Public Sub SomeMethod(Param1 As Long)
      End Sub

   End Class

End Namespace

- Or -

Imports System
Imports System.Runtime.InteropServices

<Assembly: ComVisibleAttribute(False)>

Namespace MyInteropLibrary

   <ComVisibleAttribute(True)> _
   Public Class MyComClass

      Public Sub SomeMethod(Param1 As System.Int32)
      End Sub

   End Class

End Namespace

[C#]

// This code will trigger the rule violation

using System;
using System.Runtime.InteropServices;

[assembly:ComVisibleAttribute(false)]

namespace MyInteropLibrary
{

   [ComVisibleAttribute(true)]
   public class MyComClass
   {

      public void SomeMethod(long param1)
      {
      }

   }

}

// This is the correct implementation

using System;
using System.Runtime.InteropServices;

[assembly:ComVisibleAttribute(false)]

namespace MyInteropLibrary
{

   [ComVisibleAttribute(true)]
   public class MyComClass
   {

      [ComVisibleAttribute(false)]
      public void SomeMethod(long param1)
      {
      }

   }

}

- Or -

using System;
using System.Runtime.InteropServices;

[assembly:ComVisibleAttribute(false)]

namespace MyInteropLibrary
{

   [ComVisibleAttribute(true)]
   public class MyComClass
   {

      public void SomeMethod(System.Int32 param1)
      {
      }

   }

}


Avoid non-public fields in ComVisible value types

Rule ID: IN00003

Problem

A Structure (struct in C#) that is specifically marked as visible to COM declares a non-public instance field.

Rule Description

A non-public instance field, which is declared in the COM visible Structure (struct in C#), is visible to COM clients. Such field may expose sensitive data and cause security risks.

This rule is similar to FxCop rule 'Avoid non-public fields in ComVisible value types', CheckId CA1413

Correcting Violations

The rule provides the following auto-correct options:
  • Change the System.Runtime.InteropServices.ComVisibleAttribute value of the struct to False

Rule Instances

Instances of this rule in the built-in profile:
  • Avoid non-public fields in ComVisible value types.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System
Imports System.Runtime.InteropServices

<Assembly: ComVisibleAttribute(False)>

Namespace EmployeesComLibrary

   <ComVisibleAttribute(True)> _
   Public Structure Employee

      Public FirstName As String
      Public LastName As String
      Friend Salary As Decimal ' Violates the rule

   End Structure

End Namespace

' This is the correct implementation

Imports System
Imports System.Runtime.InteropServices

<Assembly: ComVisibleAttribute(False)>

Namespace EmployeesComLibrary

   <ComVisibleAttribute(False)> _
   Public Structure Employee

      Public FirstName As String
      Public LastName As String
      Friend Salary As Decimal

   End Structure

End Namespace

[C#]

// This code will trigger the rule violation

using System;
using System.Runtime.InteropServices;

[assembly: ComVisibleAttribute(false)]
namespace EmployeesComLibrary
{

   [ComVisibleAttribute(true)]
   public struct Employee
   {

      public string FirstName;
      public string LastName;
      internal decimal Salary; // Violates the rule

   }

}

// This is the correct implementation

using System;
using System.Runtime.InteropServices;

[assembly: ComVisibleAttribute(false)]
namespace EmployeesComLibrary
{

   [ComVisibleAttribute(false)]
   public struct Employee
   {

      public string FirstName;
      public string LastName;
      internal decimal Salary;

   }

}


Avoid static members in ComVisible types

Rule ID: IN00004

Problem

Type that is specifically marked as visible to COM contains a public static method.

Rule Description

.NET components that are meant to be exposed to COM clients should not use features that COM-based clients cannot see.

COM does not support static methods. Therefore, such methods should not be exposed to COM clients.

This rule is similar to FxCop rule 'Avoid static members in ComVisible types', CheckId CA1407

Correcting Violations

The rule provides the following auto-correct options:
  • Change the System.Runtime.InteropServices.ComVisibleAttribute value of the method to False

Rule Instances

Instances of this rule in the built-in profile:
  • Avoid static members in ComVisible types.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System
Imports System.Runtime.InteropServices

<Assembly: ComVisibleAttribute(False)>

Namespace EmployeesComLibrary

   <ComVisibleAttribute(True)> _
   Public Class Employee

      Public FirstName As String
      Public LastName As String

      Public Shared Sub Print() ' Violates the rule

        ...

      End Sub

   End Class

End Namespace

' This is the correct implementation

Imports System
Imports System.Runtime.InteropServices

<Assembly: ComVisibleAttribute(False)>

Namespace EmployeesComLibrary

   <ComVisibleAttribute(True)> _
   Public Class Employee

     Public FirstName As String
     Public LastName As String

     <ComVisibleAttribute(False)> _
     Public Shared Sub Print()

       ...

     End Sub

   End Class

End Namespace

[C#]

// This code will trigger the rule violation

using System;
using System.Runtime.InteropServices;

[assembly: ComVisibleAttribute(false)]
namespace EmployeesComLibrary
{

   [ComVisibleAttribute(true)]
   public struct Employee
   {

     public string FirstName;
     public string LastName;

     public static void Print() // Violates the rule
     {

       ...

     }

   }

}

// This is the correct implementation

using System;
using System.Runtime.InteropServices;

[assembly: ComVisibleAttribute(false)]
namespace EmployeesComLibrary
{

   [ComVisibleAttribute(true)]
   public struct Employee
   {

     public string FirstName;
     public string LastName;

     [ComVisibleAttribute(false)]
     public static void Print() // Violates the rule
     {

       ...

     }

   }

}


Com visible types should be creatable

Rule ID: IN00002

Problem

Type marked as COM visible contains a public parameterized constructor but does not contain a public default (parameterless) constructor.

Rule Description

According to Microsoft .NET Framework guidelines, the class must expose an implicit and explicit parameter-less constructor because COM clients can't access constructors with parameters. (The class might expose a public Initialize method that COM clients can call immediately after instantiation to ensure that the objectis in a valid state before using it.)

This rule is similar to FxCop rule 'Com visible types should be creatable', CheckId CA1409

Correcting Violations

The rule provides the following auto-correct options:
  • Add a public default constructor

Rule Instances

Instances of this rule in the built-in profile:
  • Com visible types should be creatable.


PInvokes should not be visible

Rule ID: IN00004

Problem

Externally visible method in a public type has the System.Runtime.InteropServices.DllImportAttribute attribute.

- OR -

Externally visible method in a public type defined using the Declare keyword.

Rule Description

Methods defined using the Declare statement (or marked with the System.Runtime.InteropServices.DllImportAttribute attribute) use PInvoke (Platform Invocation Services) to call unmanaged functions that are implemented in a DLL. Therefore, if such method is externally visible, it maight be exploited and cause security vulnerability by allowing access to unmanaged API that could not be used otherwise.

This rule is similar to FxCop rule 'PInvokes should not be visible', CheckId CA1401

Correcting Violations

The rule provides the following auto-correct options:
  • Change method modifier to Private.
  • Change method modifier to Internal

Rule Instances

Instances of this rule in the built-in profile:
  • PInvokes should not be visible.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System
Imports System.Runtime.InteropServices

Namespace DiskManagementLibrary

  Public Class NativeDiskAccess

    ...

    ' Violates the rule
    Public Declare Function DeleteFile Lib "kernel32" _
      (ByVal lpFileName As String) As Boolean

  End Class

End Namespace

' This is the correct implementation

Imports System
Imports System.Runtime.InteropServices

Namespace DiskManagementLibrary

  Public Class NativeDiskAccess

    ...

    Private Declare Function DeleteFile Lib "kernel32" _
      (ByVal lpFileName As String) As Boolean

  End Class

End Namespace

[C#]

// This code will trigger the rule violation

using System;
using System.Runtime.InteropServices;

namespace DiskManagementLibrary
{

  public class NativeDiskAccess
  {

    ...

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool DeleteFile(string lpFileName); // Violates the rule

  }

}

// This is the correct implementation

using System;
using System.Runtime.InteropServices;

namespace DiskManagementLibrary
{

  public class NativeDiskAccess
  {

    ...

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool DeleteFile(string lpFileName);

  }

}


Maintainability Rules

This section will guide you through the set of Maintainability Rules.

Click on any of the links below to go directly to the corresponding rule.

Avoid excessive complexity

Avoid excessive inheritance


Avoid excessive complexity

Rule ID: MA00001

Problem

A method has excessive cyclomatic complexity.

Rule Description

Cyclomatic Complexity (CC) is a popular procedural software metric equal to the number of decisions that can be taken in a procedure. It is created by calculating the number of different code paths in the flow of the program such as if blocks, switch cases, and do, while, foreach and for loops then adding 1 to the total. Methods with CC 10-15 and higher are hard to understand and maintain - recommended to refactor. Methods with CC 25+ are extremely complex and must be split in smaller methods - Extract Method - with the exception perhaps for the auto-generated code when you have very little control.

Cyclomatic Complexity of a method should not exceed MaxCyclomaticComplexity value (25 by default).

This rule is similar to FxCop rule 'Avoid excessive complexity', CheckId CA1502

Correcting Violations

The rule provides the following auto-correct options:
  • Refactor the method to reduce its cyclomatic complexity.

Configurable Properties

  • MaxCyclomaticComplexity - Sets the maximum allowed cyclomatic complexity.

Rule Instances

Instances of this rule in the built-in profile:
  • Avoid excessive complexity.

Example

The following example show code with Cyclomatic Complexity 3.

[Visual Basic]

  Imports System

  Public Class TextProcessing

    Public Function IsNull(str1 As String) As Boolean

      If str1 = Null Then
        Return True
      Else
        Return False

    End Function

  End Class

[C#]

  using System;

  public class TextProcessing
  {
    public bool IsNull(string str1)
    {
      if (str1 == Null)
      {
        return true;
      }
      else
      {
        return false;
      }
    }
  }


Avoid excessive inheritance

Rule ID: MA00002

Problem

Type exceeds maximal inheritance level.

Rule Description

Depth of Inheritance (DI) - indicates the number of class definitions that extend to the root of the class hierarchy. The deeper the hierarchy the more difficult it might be to understand where particular methods and fields are defined or/and redefined. Depending on product type, technology and team accepted standards max DI value ranges between 4 and 6, types with higher DI would compromise encapsulation and increase complexity. However when deriving from BCL or other complex framework classes the accepted DI value may be higher since the base class DI is already high enough.

Depth of Inheritance of a class should not exceed MaxInheritanceLevel value (5 by default).

This rule is similar to FxCop rule 'Avoid excessive inheritance', CheckId CA1501

Correcting Violations

The rule provides the following auto-correct options (manual correct only):
  • Derive the type from a base type more shallow in the inheritance hierarchy or eliminate some of the intermediate base types.

Configurable Properties

  • MaxInheritanceLevel - Sets the maximum allowed level of inheritance.

Rule Instances

Instances of this rule in the built-in profile:
  • Avoid excessive inheritance.

Example

The following examples show code with Depth of Inheritance 3.

[Visual Basic]

  Imports System

  Public Class Root

  End Class

  Public Class FirstChild

    Inherits Root

  End Class

  Public Class SecondChild

    Inherits FirstChild

  End Class

  Public Class ThirdChild

    Inherits SecondChild

  End Class

[C#]

  using System;

  public class Root
  {
  }

  public class FirstChild: Root
  {
  }

  public class SecondChild: FirstChild
  {
  }

  public class ThirdChild: SecondChild
  {
  }


Naming Rules

This section will guide you through the set of Naming Rules.

Click on any of the links below to go directly to the corresponding rule.

Acronyms should be cased correctly

Avoid certain names for enum member

Avoid language specific type names in parameters

Avoid prefix enum values with type name

Avoid prefix for derived type

Avoid prefix for return type

Collection class name must have "Collection" suffix

Derived types should have correct suffix

Derived types should not have suffix

Enums should have plural names depending on Flag attribute

Identifiers should be cased correctly

Identifiers should differ by more than case

Identifiers should not contain specified characters

Identifiers should not match keywords

Parameter names should match base declaration

Property names should not match get methods

Parameter names should not match member names

Replace identifier prefix

Replace identifier suffix

Type names should not match namespaces

Use or Avoid Certain Prefixes

Use or Avoid Certain Suffixes

Use prefix for derived type

Use prefix for return type


Acronyms should be cased correctly

Rule ID: NA00001

Problem

The name of an identifier contains an acronym of three or more uppercase letters (long acronym) or a two-letter acronym and the second letter is lowercase (short acronym).

Rule Description

According to naming guidelines short acronyms (two-letter acronyms) should contain all uppercase letters, and long acronyms (three and more letters acronyms) should be Pascal cased.

This rule is similar to the following FxCop rules:
  • 'Long acronyms should be pascal-cased', CheckId CA1705
  • 'Short acronyms should be uppercase', CheckId CA1706

Correcting Violations

The rule provides the following auto-correct options:
  • Rename code element and its references to the specified name.

Configurable Properties

  • Acronym - Type of acronym used. Possible values: Short, Long;
  • ExceptionList - A comma-separated list of the acronyms excluded from analysis.

Rule Instances

Instances of this rule in the built-in profile:
  • Long Acronyms should be Pascal cased.
  • Short Acronyms should be Upper cased

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation
Imports System.IO
Imports System.Xml

Public Sub StartIo(ByVal IoStream As Stream)
End Sub

Public Sub ProcessHTMLTag(ByVal HTMLTag As String)
End Sub

' This is the correct implementation
Imports System.IO
Imports System.Xml

Public Sub StartIO(ByVal ioStream As Stream)
End Sub

Public Sub ProcessHtmlTag(ByVal htmlTag As String)
End Sub

[C#]

// This code will trigger the rule violation
using System.IO;
using System.Xml;

public void StartIo(Stream IoStream)
{
}

public void ProcessHTMLTag(string HTMLTag)
{
}

// This is the correct implementation
using System.IO;
using System.Xml;

public void StartIO(Stream ioStream)
{
}

public void ProcessHtmlTag(string htmlTag )
{
}

Related Rules

Identifiers should be cased correctly

Identifiers should differ by more than case


Avoid language specific type names in parameters

Rule ID: NA00003

Problem

According to the Microsoft naming guidelines for the .NET Framework types, the name of the parameter should not contain a language-specific type name.

Rule Description

Use names that reflect the meaning of the parameter and avoid prefixes and suffixes that indicate the type of a parameter.

This rule is similar to FxCop rule 'Avoid language specific type names in parameters', CheckId CA1718

Correcting Violations

The rule provides the following auto-correct options:
  • Rename parameter and its references to the specified name.

Rule Instances

Instances of this rule in the built-in profile:
  • Avoid language specific type names in parameters.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Public Class PersonInfo

Private _firstName As String
Private _lastName As String

Public ReadOnly Property FirstName() As String
    Get
        Return _firstName
    End Get
End Property

Public ReadOnly Property LastName() As String
    Get
        Return _lastName
    End Get
End Property

' Violation
Public Sub New(ByVal firstNameString As String, ByVal lastNameString As String)

  Me._firstName = firstNameString
  Me._lastName = lastNameString

End Sub

End Class

' This is the correct implementation

Public Class PersonInfo

Private _firstName As String
Private _lastName As String

Public ReadOnly Property FirstName() As String
    Get
        Return _firstName
    End Get
End Property

Public ReadOnly Property LastName() As String
    Get
        Return _lastName
    End Get
End Property

' Fixed names
Public Sub New(ByVal firstName As String, ByVal lastName As String)

    Me._firstName = firstName
    Me._lastName = lastName

End Sub

End Class

[C#]

// This code will trigger the rule violation

public class PersonInfo
{

  private string _firstName;
  private string _lastName;

  public string FirstName
  {
      get
      {
          return _firstName;
      }
  }

  public string LastName
  {
      get
      {
          return _lastName;
      }
  }

  // Violation
  public PersonInfo(string firstNameString, string lastNameString)
  {

    this._firstName = firstNameString;
    this._lastName = lastNameString;

  }

}

// This is the correct implementation

public class PersonInfo
{

  private string _firstName;
  private string _lastName;

  public string FirstName
  {
      get
      {
          return _firstName;
      }
  }

  public string LastName
  {
      get
      {
          return _lastName;
      }
  }

  // Violation
  public PersonInfo(string firstName, string lastName)
  {

    this._firstName = firstName;
    this._lastName = lastName;

  }

}

Related Rules

Collection class name must have "Collection" suffix

Use or avoid certain prefixes

Use or avoid certain suffixes


Avoid prefix enum values with type name

Rule ID: NA00004

Problem

An enumeration contains a member whose name begins with the type name of the enumeration.

Rule Description

Enumeration members names are not prefixed with the type name because type information is redundant.

This rule is similar to FxCop rule 'Do not prefix enum values with type name', CheckId CA1712

Correcting Violations

The rule provides the following auto-correct options:
  • Rename enumeration member and its references to the specified name.

Rule Instances

Instances of this rule in the built-in profile:
  • Avoid prefix enumeration values with type name.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Public Enum ImageMode

    ImageModeBitmap = 0
    ImageModeGrayscale = 1
    ImageModeIndexed = 2
    ImageModeRgb = 3

End Enum

' This is the correct implementation

Public Enum ImageMode

    Bitmap = 0
    Grayscale = 1
    Indexed = 2
    Rgb = 3

End Enum

[C#]

// This code will trigger the rule violation

public enum ImageMode
{

    ImageModeBitmap = 0,
    ImageModeGrayscale = 1,
    ImageModeIndexed = 2,
    ImageModeRgb = 3

}

// This is the correct implementation

public enum ImageMode
{

    Bitmap = 0,
    Grayscale = 1,
    Indexed = 2,
    Rgb = 3

}

Related Rules

Use or Avoid Certain Prefixes

Use or avoid certain suffixes


Avoid prefix for derived type

Rule ID: NA00024

Problem

The name of code element derived from specified type has incorrect prefix.

Rule Description

The rule was specially created to ensure that the class derived from some certain class or interface does not have specified prefix.

Correcting Violations

The rule provides the following auto-correct options:
  • Rename code element and its references to the specified name.

Rule Instances

Instances of this rule in the built-in profile:
  • Avoid prefix for derived type.

Configurable Properties

  • PrefixToCheck - Certain prefix to be checked.
  • NextCharCapitalizationStyle - Capitalization style of the next after prefix char.
  • MustImplement - Type should implement the specified type or interface.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

Assume that configurable properties have the following values after the rule customization:
  • PrefixToCheck = "T_"
  • NextCharCapitalizationStyle = "Upper"
  • MustImplement = "MyLibrary.Person"
This mean that classes derived from the MyLibrary.Person class should not have "T_" prefix.

[Visual Basic]

' This code will trigger the rule violation

Namespace MyLibrary

  Public Class Person

    Public FirstName As String
    Public LastName As String

  End Class

  Public Class T_Employee
      Inherits Person

    Public Position As String
    Public Salary As Decimal

  End Class

End Namespace

' This is the correct implementation

Namespace MyLibrary

  Public Class Person

    Public FirstName As String
    Public LastName As String

  End Class

  Public Class Employee
      Inherits Person

    Public Position As String
    Public Salary As Decimal

  End Class

End Namespace

[C#]

// This code will trigger the rule violation

namespace MyLibrary
{

  public class Person
  {

    public string FirstName;
    public string LastName;

  }

  public class T_Employee: Person
  {

    public string Position;
    public string Salary;

  }

}

// This is the correct implementation

namespace MyLibrary
{

  public class Person
  {

    public string FirstName;
    public string LastName;

  }

  public class Employee: Person
  {

    public string Position;
    public string Salary;

  }

}

Related Rules

Acronyms should be cased correctly

Avoid prefix for return type

Identifiers should be cased correctly

Identifiers should differ by more than case

Replace identifier prefix

Replace identifier suffix

Use or Avoid Certain Prefixes

Use prefix for derived type

Use prefix for return type


Avoid prefix for return type

Rule ID: NA00022

Problem

The name of code element (return type) has incorrect prefix.

Rule Description

The rule was specially created to ensure that the code element (field, property or variable) whis some certain return type does not have specified prefix.

Correcting Violations

The rule provides the following auto-correct options:
  • Rename code element and its references to the specified name.

Rule Instances

Instances of this rule in the built-in profile:
  • Avoid prefix for return type.

Configurable Properties

  • PrefixToCheck - Certain prefix to be checked.
  • NextCharCapitalizationStyle - Capitalization style of the next after prefix char. Possible values: None, Lower, Upper
  • TypeName - Type should be equal to the specified type or interface.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

Assume that configurable properties have the following values after the rule customization:
  • PrefixToCheck = "str"
  • NextCharCapitalizationStyle = "Upper"
  • TypeName = "System.String"
This mean that code elements with the System.String return type should not have "str" prefix.

[Visual Basic]

' This code will trigger the rule violation

Public Class PersonInfo

  Public strFirstName As String
  Public strLastName As String

End Class

' This is the correct implementation

Public Class PersonInfo

  Public FirstName As String
  Public LastName As String

End Class

[C#]

// This code will trigger the rule violation

public class PersonInfo
{

  public string strFirstName;
  public string strLastName;

}

// This is the correct implementation

public class PersonInfo
{

  public string FirstName;
  public string LastName;

}

Related Rules

Acronyms should be cased correctly

Avoid prefix for derived type

Identifiers should be cased correctly

Identifiers should differ by more than case

Replace identifier prefix

Replace identifier suffix

Use or Avoid Certain Prefixes

Use prefix for derived type

Use prefix for return type


Avoid name enum members with specified name

Rule ID: NA00005

Problem

The name of the member of enumeration includes the "Reserved" word.

Rule Description

Don't use the word "Reserved" in the name of an enumeration member. Defining such reserved values is a holdover from COM programming. A later version of a Microsoft .NET Framework class library can simply add new values as and when required, without breaking existing clients, provided that you don't change the numeric value of existing values.

This rule is similar to FxCop rule 'Do not name enum values Reserved', CheckId CA1700

Correcting Violations

The word "Reserved" should be removed from the name of the member of enumeration. Do not include "reserved for future use" values in an enum value.

The rule provides the following auto-correct options:
  • Rename enumeration member and its references to the specified name.

Configurable Properties

  • NameToAvoid - Name to be avoid in enum members.

Rule Instances

Instances of this rule in the built-in profile:
  • Avoid name enumeration values "Reserved".

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Enum SampleType

  Unknown = 0
  Known = 1
  SomeOtherReserved = 2

End Enum

' This is the correct implementation

Enum SampleType

  Unknown = 0
  Known = 1

End Enum

- Or -

Enum SampleType

  Unknown = 0
  Known = 1
  SomeOther = 2

End Enum

[C#]

// This code will trigger the rule violation

enum SampleType
{

  Unknown = 0,
  Known = 1,
  SomeOtherReserved = 2

}

// This is the correct implementation

enum SampleType
{

  Unknown = 0,
  Known = 1

}

- Or -

enum SampleType
{

  Unknown = 0,
  Known = 1,
  SomeOther = 2

}

Related Rules

Collection class name must have "Collection" suffix

Use or avoid certain prefixes

Use or avoid certain suffixes


Code region name should be pascal cased

Rule ID: NA00025

Problem

Code region name is not Pascal cased.

Rule Description

This rule is created to ensure that the name of the code region is Pascal cased. I.e. each word in the code region name starts from the upper case letter and contains at least one lower-case letter.

Correcting Violations

The rule provides the following auto-correct options:
  • Change code region name to corrected one

Rule Instances

Instances of this rule in the built-in profile:
  • Code region name should be pascal cased

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[C#]

' This code will trigger the rule violation

#region Code region name

  ...

#endregion

' This is the correct implementation

#region Code Region Name

  ...

#endregion

Related Rules

Acronyms should be cased correctly

Identifiers should be cased correctly


Collection class name must have "Collection" suffix

Rule ID: NA00015

Problem

The type implements System.Collections.ICollection or System.Collections.IEnumerable and its name does not have a Collection suffix.

Rule Description

Use the Collection suffix for the collection types that inherit from the System.Collections.CollectionBase or System.Collections.ReadOnlyCollectionBase, for types that implement System.Collections.IList interface, and, more generally, for types that behave like System.Collections.ArrayList and whose members can be indexed by their position.

This rule is similar to FxCop rule 'Identifiers should have correct suffix', CheckId CA1710

Correcting Violations

The rule provides the following auto-correct options:
  • Rename type and its references to the specified name.

Rule Instances

Instances of this rule in the built-in profile:
  • Collection class name must have "Collection" suffix.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

' The following Persons type implements System.Collections.ICollection interface

Imports System
Imports System.Collections

Public Class Persons
    Inherits CollectionBase

    Public Sub Add(ByVal value As PersonInfo)
        InnerList.Add(value)
    End Sub

    Public Sub AddRange(ByVal items As Persons)
        If Not items Is Nothing Then
            InnerList.AddRange(items)
        End If
    End Sub

    Public Sub AddRange(ByVal items() As PersonInfo)
        If Not items Is Nothing Then

            Dim item As CPersonInfo
            For Each item In items
                InnerList.Add(item)
            Next
        End If
    End Sub

End Class

' This is the correct implementation

Imports System
Imports System.Collections

Public Class PersonsCollection
    Inherits CollectionBase

    Public Sub Add(ByVal value As PersonInfo)
        InnerList.Add(value)
    End Sub

    Public Sub AddRange(ByVal items As PersonsCollection)
        If Not items Is Nothing Then
            InnerList.AddRange(items)
        End If
    End Sub

    Public Sub AddRange(ByVal items() As PersonInfo)
        If Not items Is Nothing Then

            Dim item As CPersonInfo
            For Each item In items
                InnerList.Add(item)
            Next
        End If
    End Sub

End Class

[C#]

// This code will trigger the rule violation

// The following Persons type implements System.Collections.ICollection interface

using System;
using System.Collections;

public class Persons: CollectionBase
{

    public void Add(PersonInfo value)
    {
        InnerList.Add(value);
    }

    public void AddRange(Persons items)
    {
        if (items != null)
        {
            InnerList.AddRange(items);
        }
    }

    public void AddRange(PersonInfo[] items)
    {
        if (items != null)
        {

            foreach (CPersonInfo item in items)
            {
                InnerList.Add(item);
            }

        }
    }

}

// This is the correct implementation

using System;
using System.Collections;

public class PersonsCollection: CollectionBase
{

    public void Add(PersonInfo value)
    {
        InnerList.Add(value);
    }

    public void AddRange(PersonsCollection items)
    {
        if (items != null)
        {
            InnerList.AddRange(items);
        }
    }

    public void AddRange(PersonInfo[] items)
    {
        if (items != null)
        {

            foreach (CPersonInfo item in items)
            {
                InnerList.Add(item);
            }

        }
    }

}

Related Rules

Avoid Language Specific Type Names in Parameters

Use or avoid certain prefixes

Use or avoid certain suffixes


Derived types should have correct suffix

Rule ID: NA00014

Problem

The name of the type or derived type does not have correct suffix.

Rule Description

According to the Microsoft naming guidelines for the .NET Framework types, the name of the type that extends certain base type, implement certain interface or derived from such types should end with one of specific reserved suffixes. These suffixes cannot be used in the name of other types.

The table below represents base types and interfaces with corresponding reserved suffixes that should be used in the names of derived types:
Name of base type or interface | Suffix
System.Attribute | Attribute
System.EventArgs | EventArgs
System.Exception | Exception
System.Collections.Generic.ICollection | Collection
System.Collections.Generic.IDictionary | Dictionary
System.Collections.ICollection | Collection
System.Collections.IDictionary | Dictionary
System.Collections.IEnumerable | Collection
System.Collections.Queue | Collection or Queue
System.Collections.Stack | Collection or Stack
System.Data.DataSet | Collection or DataSet
System.Data.DataTable | Collection or DataTable
System.IO.Stream | Stream
System.Security.IPermission | Permission
System.Security.Policy.IMembershipCondition | Condition
An event-handler delegate. | EventHandler

This rule is similar to FxCop rule 'Identifiers should have correct suffix', CheckId CA1710

Correcting Violations

Modify the name of the type so that it include correct suffix.

The rule provides the following auto-correct options:
  • Rename type and its references to the specified name.

Configurable Properties

  • MustImplement - Type should implement the specified type or interface;
  • SuffixToCheck - Certain Suffix to be checked.

Rule Instances

Instances of this rule in the built-in profile:
  • Dictionary class name must have "Dictionary" suffix.
  • Generic Dictionary class name must have "Dictionary" suffix.
  • Exception class name must have "Exception" suffix.
  • Attribute class name must have "Attribute" suffix.
  • Condition class name must have "Condition" suffix.
  • Queue class name must have "Queue" suffix.
  • Stack class name must have "Stack" suffix.
  • Stream class name must have "Stream" suffix.
  • Permission class name must have "Permission" suffix.
  • EventArgs class name must have "EventArgs" suffix.
  • DataSet class name must have "DataSet" suffix.
  • Derived types should have correct suffix.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Public Class MySample
    Implements IDictionary

    ...

End Class

' This is the correct implementation

Public Class MySampleDictionary
    Implements IDictionary

    ...

End Class

[C#]

// This code will trigger the rule violation

public class MySample: IDictionary
{

    ...

}

// This is the correct implementation

public class MySampleDictionary: IDictionary
{

    ...

}

Related Rules

Collection class name must have "Collection" suffix

Derived types should not have suffix

Use or avoid certain suffixes


Derived types should not have suffix

Rule ID: NA00002

Problem

The name of the type or derived type has incorrect suffix.

Rule Description

According to the Microsoft naming guidelines for the .NET Framework types, the name of the type or derived type should not end with one of specific reserved suffixes. These suffixes can be used only in the name of the type that extends certain base type, implement certain interface or derived from such types.

The table below represents base types and interfaces with corresponding reserved suffixes:
Suffix | Name of base type or interface
Attribute | System.Attribute
Collection | System.Collections.Generic.ICollection System.Collections.ICollection System.Collections.IEnumerable System.Collections.Queue System.Collections.Stack System.Data.DataSet System.Data.DataTable
Dictionary | System.Collections.Generic.IDictionary System.Collections.IDictionary
EventArgs | System.EventArgs
EventHandler | An event-handler delegate.
Exception | System.Exception
Permission | System.Security.IPermission
Queue | System.Collections.Queue
Stack | System.Collections.Stack
Stream | System.IO.Stream

The following suffixes are reserved as well: Delegate, Enum, Flags (for an enumeration) and Impl.

This rule is similar to FxCop rule 'Identifiers should not have incorrect suffix', CheckId CA1711

Correcting Violations

The rule provides the following auto-correct options:
  • Rename type and its references to the specified name.

Configurable Properties

  • MustImplement - Type should implement the specified type or interface;
  • SuffixToCheck - Certain Suffix to be checked.

Rule Instances

Instances of this rule in the built-in profile:
  • Only Collection class name must have "Collection" suffix.
  • Only Dictionary class name must have "Dictionary" suffix.
  • Only Exception class name must have "Exception" suffix
  • Only Attribute class name must have "Attribute" suffix
  • Only Condition class name must have "Condition" suffix
  • Only Queue class name must have "Queue" suffix
  • Only Stack class name must have "Stack" suffix
  • Only Stream class name must have "Stream" suffix
  • Only Permission class name must have "Permission" suffix
  • Only EventArgs class name must have "EventArgs" suffix

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' The following example shows incorrectly named types

Public Class MySampleDictionary

    ...

End Class

' This code will trigger the rule violation

Public Class MySample

    ...

End Class

- Or -

Public Class MySampleDictionary
    Implements IDictionary

    ...

End Class

[C#]

// The following example shows incorrectly named types

public class MySampleDictionary
{

    ...

}

// This code will trigger the rule violation

public class MySample
{

    ...

}

- Or -

public class MySampleDictionary: IDictionary
{

    ...

}

Related Rules

Collection class name must have "Collection" suffix

Derived types should have correct suffix

Use or avoid certain suffixes


Enums should have plural names depending on Flag attribute

Rule ID: NA00018

Problem

An externally visible enumeration has the System.FlagsAttribute attribute specified, but does not ends in a plural word.

Or

An externally visible enumeration ends in a plural word, but does not have the System.FlagsAttribute attribute specified.

Rule Description

The System.FlagsAttribute indicates that an enumeration can be treated as a bit field; that is, a set of flags. Bit fields are generally used for lists of elements that might occur in combination, whereas enumeration constants are generally used for lists of mutually exclusive elements.

Therefore, if only one value of an enumeration can be specified at a time, then the name of the enumeration should be a singular word and the enum should not be marked with the System.FlagsAttribute attribute.

If more than one value of the enumeration can be specified simultaneously, then the name of the enumeration should be a plural word and the enum should be marked with the System.FlagsAttribute attribute.

This rule is similar to the following FxCop rules:
  • 'Flags enums should have plural names', CheckId CA1714
  • 'Only FlagsAttribute enums should have plural names', CheckId CA1717

Correcting Violations

Rename externally visible enumeration according to the System.FlagsAttribute attribute.

The rule provides the following auto-correct options:
  • Rename enumeration and its references to the specified name.

Configurable Properties

  • CheckFlagEnum - Whether check Flag or Non-Flag enumeration.

Rule Instances

Instances of this rule in the built-in profile:
  • Enums should have plural names depending on Flag attribute.
  • Enums should have plural names depending on Flag attribute.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

<FlagsAttribute( )> _
Enum Color
  Red = 1
  Green = 2
  Blue = 4
End Enum

' This is the correct implementation

<FlagsAttribute( )> _
Enum Colors
  Red = 1
  Green = 2
  Blue = 4
End Enum

[C#]

// This code will trigger the rule violation

[FlagsAttribute( )]
enum Color
{
  Red = 1,
  Green = 2,
  Blue = 4
}

// This is the correct implementation

[FlagsAttribute( )]
enum Colors
{
  Red = 1,
  Green = 2,
  Blue = 4
}


Identifiers should be cased correctly

Rule ID: NA00006

Problem

The name of an identifier is not cased correctly.

Rule Description

According to the Microsoft naming guidelines for the .NET Framework types, the following capitalization rules should be used for the different types of identifiers:

Pascal case should be used for:
- Class
- Enum type
- Enum values
- Event
- Exception class
- Read-only Static field
- Interface
- Method
- Namespace
- Property
- Public instance field

Camel case should be used for:
- Parameter
- Protected instance field

This rule is similar to FxCop rule 'Identifiers should be cased correctly', CheckId CA1709

Correcting Violations

The rule provides the following auto-correct options:
  • Rename code element and its references to the specified name.

Configurable Properties

  • IdentifierCase - Name case notation to check. Possible values: Camel, Pascal, Upper

Rule Instances

Instances of this rule in the built-in profile:
  • Namespace/Type identifiers should be cased correctly.
  • Member identifiers should be cased correctly.
  • Field identifiers should be cased correctly.
  • Parameter identifiers should be cased correctly.
  • Local variable identifiers should be cased correctly.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Public Class sampleClass
    Protected InstanceField As String = String.Empty

    ...

End Class

' This is the correct implementation

Public Class SampleClass
    Protected instanceField As String = String.Empty

    ...

End Class

[C#]

// This code will trigger the rule violation

public class sampleClass
{
    protected string InstanceField = String.Empty;

    ...

}

' This is the correct implementation

public class SampleClass
{
    protected string instanceField = String.Empty;

    ...

}

Related Rules

Acronyms should be cased correctly

Identifiers should differ by more than case


Identifiers should differ by more than case

Rule ID: NA00007

Problem

The names of two types, members, parameters, or fully qualified namespaces are identical when converted to lower-case.

Rule Description

Identifiers for namespaces, types, members, and parameters cannot differ only by case because languages that target the common language runtime are not required to be case-sensitive. For example, Visual Basic is a widely used case-insensitive language.

This rule is similar to FxCop rule 'Identifiers should differ by more than case', CheckId CA1708

Correcting Violations

The rule provides the following auto-correct options:
  • Rename identifier and its references to the specified name.

Rule Instances

Instances of this rule in the built-in profile:
  • Member parameter names should differ by more than case.
  • Type member names should differ by more than case.
  • Identifiers should differ by more than case.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[C#]

' This code will trigger the rule violation
' Such class will not be usable in the case-insensitive language

class FileUtility
{

    public string GetFileContent(string fileName)
    {

    ...

    }

    public string GetFilecontent(string fileName)
    {

    ...

    }

}

' This is the correct implementation

class FileUtility
{

    public string GetFileContent(string fileName)
    {

    ...

    }

    public string GetFileContent1(string fileName)
    {

    ...

    }

}

Related Rules

Identifiers should be cased correctly

Acronyms should be cased correctly


Identifiers should not contain specified characters

Rule ID: NA00008

Problem

The name of an identifier contains the specified character.

Rule Description

The rule provides the following auto-correct options:
  • Remove the specified character from identifier's name and rename an identifier and its references.
  • Rename an identifier and its references to the specified name.
This rule is similar to FxCop rule 'Identifiers should not contain underscores', CheckId CA1707

Correcting Violations

The rule provides the following auto-correct options:
  • Rename code element and its references to the specified name.

Configurable Properties

  • ForbiddenChar - Should not contain a character.

Rule Instances

Instances of this rule in the built-in profile:
  • Namespace and type names should not contain underscores.
  • Public member names should not contain underscores.
  • Parameter names should not contain underscores.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

  Imports System
  Imports System.IO
  Imports System.Text

  Public Class _SampleFileReader

    ...

  End Class

' This is the correct implementation

  Imports System
  Imports System.IO
  Imports System.Text

  Public Class SampleFileReader

    ...

  End Class

[C#]

// This code will trigger the rule violation

  using System;
  using System.IO;
  using System.Text;

  public class _SampleFileReader
  {

    ...

  }

// This is the correct implementation

  using System;
  using System.IO;
  using System.Text;

  public class SampleFileReader
  {

    ...

  }

Related Rules

Identifiers should be cased correctly

Acronyms should be cased correctly


Identifiers should not match keywords

Rule ID: NA00009

Problem

A namespace name or a type name matches a reserved keyword in a case-insensitive comparison.

Rule Description

Identifiers for namespaces and types should not match keywords defined by languages that target the common language runtime. Depending on the language in use and the keyword, compiler errors and ambiguities can make the library difficult to use. This rule does not check all keywords in all .NET languages

This rule is similar to FxCop rule 'Identifiers should not match keywords', CheckId CA1716

Correcting Violations

The rule provides the following auto-correct options:
  • Rename an identifier and its references to the specified name.

Rule Instances

Instances of this rule in the built-in profile:
  • Namespace or Type names should not match keywords.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

  Public Class Operator

    ...

  End Class

' This is the correct implementation

  Public Class MyOperator

    ...

  End Class

[C#]

// This code will trigger the rule violation

  public class Delegate
  {

    ...

  }

// This is the correct implementation

  public class MyDelegate
  {

    ...

  }


Parameter names should match base declaration

Rule ID: NA00010

Problem

The name of the parameter in the derived method does not match the name of the parameter in the base declaration of that method.

Rule Description

The name of the parameter in the derived (overrided) method should match the name of the parameter in the base declaration of that method. Observance of that rule alows to avoid possible confusion and increases usability of derived methods.

This rule is similar to FxCop rule 'Parameter names should match base declaration', CheckId CA1725

Correcting Violations

The rule provides the following auto-correct options:
  • Rename parameter and its references to the base declaration parameter name.
  • Rename parameter and its references to the specified name.

Rule Instances

Instances of this rule in the built-in profile:
  • Parameter names should match base declaration.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' The base declaration of the System.ComponentModel.IBindingList.AddIndex method is:

Sub AddIndex (property As PropertyDescriptor)

' This code will trigger the rule violation

' The following Persons type implements System.ComponentModel.IBindingList interface.

Imports System.ComponentModel

Public Class Persons
    Implements IBindingList

    ...

    Public Sub AddIndex(propertyValue As PropertyDescriptor) Implements IBindingList.AddIndex

        ' method code

    End Sub

    ...

End Class

' This is the correct implementation

Imports System.ComponentModel

Public Class Persons
    Implements IBindingList

    ...

    Public Sub AddIndex([property] As PropertyDescriptor) Implements IBindingList.AddIndex

        ' method code

    End Sub

    ...

End Class

[C#]

// The base declaration of the System.ComponentModel.IBindingList.AddIndex method is:

void AddIndex(PropertyDescriptor property)

// This code will trigger the rule violation

// The following Persons type implements System.ComponentModel.IBindingList interface.

using System.ComponentModel;

public class Persons: IBindingList
{

    ...

    public void IBindingList.AddIndex(PropertyDescriptor propertyValue)
    {

        // method code

    }

    ...

}

// This is the correct implementation

using System.ComponentModel;

public class Persons: IBindingList
{

    ...

    public void IBindingList.AddIndex(PropertyDescriptor property)
    {

        // method code

    }

    ...

}


Parameter names should not match member names

Rule ID: NA00011

Problem

The name of one of parameters matches the name of the method in the case-insensetive comparison.

Rule Description

According to the Microsoft naming guidelines for the .NET Framework types, names of the parameters should be descriptive and reflect the meaning of the parameter. The same naming for the parameter and for the method is unintuitive.

This rule is similar to FxCop rule 'Parameter names should not match member names', CheckId CA1719

Correcting Violations

The rule provides the following auto-correct options:
  • Rename parameter and its references to the specified name.

Rule Instances

Instances of this rule in the built-in profile:
  • Parameter names should not match member names.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

    Public Sub AddRange(ByVal addRange As PersonsCollection)
        If Not addRange Is Nothing Then
            InnerList.AddRange(addRange)
        End If
    End Sub

' This is the correct implementation

    Public Sub AddRange(ByVal items As PersonsCollection)
        If Not items Is Nothing Then
            InnerList.AddRange(items)
        End If
    End Sub

[C#]

// This code will trigger the rule violation

    public void AddRange(PersonsCollection addRange)
    {
        if (addRange != null)
        {
            InnerList.AddRange(addRange);
        }
    }

// This is the correct implementation

    public void AddRange(PersonsCollection items)
    {
        if (items != null)
        {
            InnerList.AddRange(items);
        }
    }

Related Rules

Acronyms should be cased correctly

Avoid language specific type names in parameters

Identifiers should be cased correctly

Identifiers should differ by more than case

Identifiers should not contain specified characters


Property names should not match get methods

Rule ID: NA00012

Problem

The name of a public or protected member starts with "Get" and otherwise matches the name of a public or protected property.

Rule Description

Get methods and properties should have names that clearly distinguish their function.

This rule is similar to FxCop rule 'Property names should not match get methods', CheckId CA1721

Correcting Violations

The rule provides the following auto-correct options:
  • Rename property and its references to the specified name.

Rule Instances

Instances of this rule in the built-in profile:
  • Property names should not match get methods.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System.Drawing

Public Class Sample

    Public ReadOnly Property Color() As Color
        Get
            Return Color.Red
        End Get
    End Property

     ' This method violates rule: "Property names should not match get methods"
    Public Function GetColor() As Color
        Return Color.FromName("Red")
    End Function

End Class

' This is the correct implementation

Imports System.Drawing

Public Class Sample

    Public ReadOnly Property Color() As Color
        Get
            Return Color.Red
        End Get
    End Property

    Public Function GetDefaultColor() As Color
        Return Color.FromName("Red")
    End Function

End Class

[C#]

// This code will trigger the rule violation

using System.Drawing;

public class Sample
{

    public Color Color()
    {
        get
        {
            return Color.Red;
        }
    }

    // This method violates the rule
    public Color GetColor()
    {
        return Color.FromName("Red");
    }

}

// This is the correct implementation

using System.Drawing;

public class Sample
{

    public Color Color()
    {
        get
        {
            return Color.Red;
        }
    }

    public Color GetDefaultColor()
    {
        return Color.FromName("Red");
    }

}


Replace identifier prefix

Rule ID: NA00019

Problem

The name of an identifier is incorrect prefix and should be changed on specified.

Rule Description

The rule was specially created for conversion identifier names from Hungarian notation to Microsoft naming guidelines.

The name of an identifier is incorrect prefix and should be changed on specified.

Correcting Violations

The rule provides the following auto-correct options:
  • Replace identifier name prefix and rename code element and its references.
  • Rename code element and its references to the specified name.

Configurable Properties

  • PrefixToCheck - prefix to check in identifier name to replace;
  • PrefixToReplace - prefix to replace in identifier name.

Example

After customization when PrefixToCheck equals "m_" and PrefixToReplace equals "_" the following field violates "Replace identifier prefix" rule

[Visual Basic]

' This code will trigger the rule violation

Private m_fileName As String

' This is the correct implementation

Private _fileName As String

[C#]

// This code will trigger the rule violation

private string m_fileName;

// This is the correct implementation

private string _fileName;

Related Rules

Acronyms should be cased correctly

Avoid prefix for derived type

Avoid prefix for return type

Identifiers should be cased correctly

Identifiers should differ by more than case

Replace identifier suffix

Use or Avoid Certain Prefixes

Use prefix for derived type

Use prefix for return type


Replace identifier suffix

Rule ID: NA00020

Problem

The name of an identifier is incorrect suffix and should be changed on specified.

Rule Description

The rule was specially created for conversion identifier names from Hungarian notation to Microsoft naming guidelines.

The name of an identifier is incorrect suffix and should be changed on specified.

Correcting Violations

The rule provides the following auto-correct options:
  • Replace identifier name suffix and rename code element and its references.
  • Rename code element and its references to the specified name.

Configurable Properties

  • SuffixToCheck - suffix to check in identifier name to replace;
  • SuffixToReplace - suffix to replace in identifier name.

Example

After customization when SuffixToCheck equals "String" and SuffixToReplace equals "Text" the following field violates "Replace identifier suffix" rule

[Visual Basic]

' This code will trigger the rule violation

Private _fileNameString As String

' This is the correct implementation

Private _fileNameText As String

[C#]

// This code will trigger the rule violation

private string _fileNameString;

// This is the correct implementation

private string _fileNameText;

Related Rules

Acronyms should be cased correctly

Avoid prefix for derived type

Avoid prefix for return type

Identifiers should be cased correctly

Identifiers should differ by more than case

Replace identifier prefix

Use or Avoid Certain Prefixes

Use prefix for derived type

Use prefix for return type


Type names should not match namespaces

Rule ID: NA00013

Problem

The class name duplicates commonly used .NET Framework namespace.

Rule Description

Avoid using class names that duplicate commonly used .NET Framework namespaces in case-insensitive comparison. For example, the following names should not be used as a class name:
  • System;
  • Collections;
  • Forms;
  • UI;
  • etc.
This rule is similar to FxCop rule 'Type names should not match namespaces', CheckId CA1724

Correcting Violations

Rename class and choose new name that does not duplicate commonly used .NET Framework namespaces.

The rule provides the following auto-correct options:
  • Rename type and its references to the specified name.

Rule Instances

Instances of this rule in the built-in profile:
  • Type names should not match namespaces.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Namespace MyNamespace

    Public Class Forms

        ...

    End Class

End Namespace

' This is the correct implementation

Namespace MyNamespace

    Public Class MyForms

        ...

    End Class

End Namespace

[C#]

// This code will trigger the rule violation

namespace MyNamespace
{

    public class Forms
    {

        ...

    }

}

// This is the correct implementation

namespace MyNamespace
{

    public class MyForms
    {

        ...

    }

}


Use or Avoid Certain Prefixes

Rule ID: NA00016

Problem

Some programming elements have name that begins with incorrect prefix.

Rule Description

According to the Microsoft naming guidelines for the .NET Framework types, only certain programming elements should have names that begin with a specific prefix.

Class Naming: Do not use a type prefix, such as C for class, on a class name.

For example: CPersonInfo and TEmployee are incorrect type names; PersonInfo and Employee are correct type names.

Interface Naming: Prefix interface names with the letter I, to indicate that the type is an interface.

For example: Comparable or Disposable are incorrect interface names; IComparable or IDisposable are correct interface names.

Static Field Naming: Do not use a Hungarian notation prefix on static field names.

Parameter Naming: Do not prefix parameter names with Hungarian type notation.

Event Naming: Do not use a prefix on the event declaration on the type.

This rule is similar to the following FxCop rules:
  • 'Identifiers should have correct prefix', CheckId CA1715
  • 'Identifiers should not have incorrect prefix', CheckId CA1722
  • 'Events should not have before or after prefix', CheckId CA1713

Correcting Violations

The rule provides the following auto-correct options:
  • Rename code element and its references to the specified name.

Configurable Properties

  • PrefixUsage - Should prefix be used or avoided. Possible values: None, Avoid, Use;
  • PrefixToCheck - Certain prefix to be checked;
  • NextCharCapitalizationStyle - Capitalization style of the next after prefix char. Possible values: None, Lower, Upper.

Rule Instances

Instances of this rule in the built-in profile:
  • Use "I" prefix for Interface types.
  • Avoid to use "C" prefix for type names.
  • Only Interface types should have "I" prefix.
  • Event name must not have "Before" prefix.
  • Event name must not have "After" prefix.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

  Imports System
  Imports System.IO
  Imports System.Text

  Public Class CSampleFileReader

    ...

  End Class

' This is the correct implementation

  Imports System
  Imports System.IO
  Imports System.Text

  Public Class SampleFileReader

    ...

  End Class

[C#]

// This code will trigger the rule violation

  using System;
  using System.IO;
  using System.Text;

  public class CSampleFileReader
  {

    ...

  }

// This is the correct implementation

  using System;
  using System.IO;
  using System.Text;

  public class SampleFileReader
  {

    ...

  }

Related Rules

Avoid Language Specific Type Names in Parameters

Collection class name must have "Collection" suffix

Use or avoid certain suffixes


Use or Avoid Certain Suffixes

Rule ID: NA00017

Problem

The name of some type ends with incorrect suffix.

Rule Description

According to the Microsoft naming guidelines for the .NET Framework types, only the names of types that extend certain base types or that implement certain interfaces, or types derived from these types, should end with specific reserved suffixes.

Event Naming:
- Use an EventHandler suffix on event handler names.
- Name an event argument class with the EventArgs suffix.
- Do not use a suffix on the event declaration on the type.

Attribute Naming:
- You should always add the suffix Attribute to custom attribute classes.

Enumeration Type Naming:
- Do not use an Enum suffix on Enum type names.

This rule is similar to FxCop rule 'Identifiers should not have incorrect suffix', CheckId CA1711

Correcting Violations

The rule provides the following auto-correct options:
  • Rename code element and its references to the specified name.

Configurable Properties

  • SuffixUsage - Should suffix be used or avoided. Possible values: None, Avoid, Use;
  • SuffixToCheck - Certain Suffix to be checked.

Rule Instances

Instances of this rule in the built-in profile:
  • Avoid to use "Impl" suffix for type names.
  • Avoid to use "Enum" suffix for non enumeration types.
  • Avoid to use "Flags" suffix for non enumeration types.
  • Avoid to use "Delegate" suffix for non delegate types.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' The following example shows incorrectly named types

Public Class DictionaryImpl
    Implements IDictionary

    ...

End Class

' This code will trigger the rule violation

Public Class MyDictionary
    Implements IDictionary

    ...

End Class

[C#]

// The following example shows incorrectly named types

public class DictionaryImpl: IDictionary
{

    ...

}

// This code will trigger the rule violation

public class MyDictionary: IDictionary
{

    ...

}

Related Rules

Avoid language specific type names in parameters

Collection class name must have "Collection" suffix

Use or avoid certain prefixes


Use prefix for derived type

Rule ID: NA00023

Problem

The name of derived class does not have correct prefix.

Rule Description

The rule was specially created to ensure that the class derived from some certain class or interface has correct prefix.

Correcting Violations

The rule provides the following auto-correct options:
  • Rename code element and its references to the specified name.

Rule Instances

Instances of this rule in the built-in profile:
  • Use prefix for derived type.

Configurable Properties

  • PrefixToCheck - Certain prefix to be checked.
  • MustImplement - Type should implement the specified type or interface.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

Assume that configurable properties have the following values after the rule customization:
  • PrefixToCheck = "Txt_"
  • MustImplement = "System.Windows.Forms.TextBox"
This mean that each class derived from the System.Windows.Forms.TextBox class should have "Txt" prefix.

[Visual Basic]

' This code will trigger the rule violation

Imports System.Windows.Forms

Public Class CustomBox
  Inherits System.Windows.Forms.TextBox

  Private _custom As String

  Public Property CustomProperty(ByVal value As String) As String
    Get
      Return _custom
    End Get
    Set
      _custom = value
    End Set
  End Property

  ...

End Class

' This is the correct implementation

Imports System.Windows.Forms

Public Class Txt_CustomBox
  Inherits System.Windows.Forms.TextBox

  Private _custom As String

  Public Property CustomProperty(ByVal value As String) As String
    Get
      Return _custom
    End Get
    Set
      _custom = value
    End Set
  End Property

  ...

End Class

[C#]

// This code will trigger the rule violation

using System.Windows.Forms;

public class CustomBox: System.Windows.Forms.TextBox
{

  private string _custom;

  public string CustomProperty
  {
    get
    {
      return _custom;
    }
    set
    {
      _custom = value;
    }
  }

  ...

}

// This is the correct implementation

using System.Windows.Forms;

public class Txt_CustomBox: System.Windows.Forms.TextBox
{

  private string _custom;

  public string CustomProperty
  {
    get
    {
      return _custom;
    }
    set
    {
      _custom = value;
    }
  }

  ...

}

Related Rules

Acronyms should be cased correctly

Avoid prefix for derived type

Avoid prefix for return type

Identifiers should be cased correctly

Identifiers should differ by more than case

Replace identifier prefix

Replace identifier suffix

Use or Avoid Certain Prefixes

Use prefix for return type


Use prefix for return type

Rule ID: NA00021

Problem

The name of code element (return type) does not have correct prefix.

Rule Description

The rule was specially created to ensure that the code element (field, property or variable) whis some certain return type has correct prefix.

Correcting Violations

The rule provides the following auto-correct options:
  • Rename code element and its references to the specified name.

Rule Instances

Instances of this rule in the built-in profile:
  • Use prefix for derived type.

Configurable Properties

  • PrefixToCheck - Certain prefix to be checked.
  • TypeName - Type should be equal to the specified type or interface.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

Assume that configurable properties have the following values after the rule customization:
  • PrefixToCheck = "text"
  • TypeName = "System.Windows.Forms.TextBox"
This mean that each code element with the System.Windows.Forms.TextBox return type should have "text" prefix.

[Visual Basic]

' This code will trigger the rule violation

Imports System.Windows.Forms

Private Function CreateMyMultilineTextBox() As TextBox
    Dim box1 As New TextBox()

    box1.Multiline = True
    box1.ScrollBars = ScrollBars.Vertical
    box1.AcceptsReturn = True
    box1.AcceptsTab = True
    box1.WordWrap = True

    Return box1
End Sub

' This is the correct implementation

Private Function CreateMyMultilineTextBox() As TextBox
    Dim textBox1 As New TextBox()

    textBox1.Multiline = True
    textBox1.ScrollBars = ScrollBars.Vertical
    textBox1.AcceptsReturn = True
    textBox1.AcceptsTab = True
    textBox1.WordWrap = True

    Return textBox1
End Sub

[C#]

// This code will trigger the rule violation

using System.Windows.Forms;

private TextBox CreateMyMultilineTextBox()
{
    TextBox box1 = new TextBox();

    box1.Multiline = true;
    box1.ScrollBars = ScrollBars.Vertical;
    box1.AcceptsReturn = true;
    box1.AcceptsTab = true;
    box1.WordWrap = true;

    return box1;
}

// This is the correct implementation

using System.Windows.Forms;

private TextBox CreateMyMultilineTextBox()
{
    TextBox textBox1 = new TextBox();

    textBox1.Multiline = true;
    textBox1.ScrollBars = ScrollBars.Vertical;
    textBox1.AcceptsReturn = true;
    textBox1.AcceptsTab = true;
    textBox1.WordWrap = true;

    return textBox1;
}

Related Rules

Acronyms should be cased correctly

Avoid prefix for derived type

Avoid prefix for return type

Identifiers should be cased correctly

Identifiers should differ by more than case

Replace identifier prefix

Replace identifier suffix

Use or avoid certain prefixes

Use prefix for derived type


Performace Rules

This section will guide you through the set of Performace Rules.

Click on any of the links below to go directly to the corresponding rule.

Avoid unsealed attributes

Dispose methods should call SuppressFinalize

Do not check for empty strings using Equals

Do not initialize unnecessarily

Override equals and operator equals on value types

Properties should not return arrays

Remove empty finalizers

Remove unused private methods

Remove unused public classes

Remove unused internal classes

Remove unused locals

Use constants where appropriate


Avoid unsealed attributes

Rule ID: PE00007

Problem

A type inherits from System.Attribute, is not abstract, and is not sealed (NotInheritable in Visual Basic).

Rule Description

According to Microsoft .NET Framework guidelines, classes for custom attributes should be sealed (NotInheritable in Visual Basic), unless rare cases when you need to inherit from the custom attribute.

The .NET Framework methods for retrieving custom attributes, such as System.Attribute.GetCustomAttribute, search the attribute inheritance hierarchy, which can be a time consuming operation. Sealing the attribute class can improve performance, eliminating the search through the inheritance hierarchy.

This rule is similar to FxCop rule 'Avoid unsealed attributes', CheckId CA1813

Correcting Violations

The rule provides the following auto-correct options:
  • Change type modifier to sealed.
  • Change type modifier to abstract.

Rule Instances

Instances of this rule in the built-in profile:
  • Avoid unsealed attributes.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System

<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Struct)>  _
Public Class CustomUserAttribute ' class is not abstract and is not sealed
    Inherits Attribute

    Private m_Name As String

    Public Sub New(ByVal name As String)
        m_Name = name
    End Sub

    Public ReadOnly Property Name() As String
        Get
            Return m_Name
        End Get
    End Property

End Class

' This is the correct implementation

Imports System

<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Struct)>  _
Public NotInheritable Class CustomUserAttribute
    Inherits Attribute

    Private m_Name As String

    Public Sub New(ByVal name As String)
        m_Name = name
    End Sub

    Public ReadOnly Property Name() As String
        Get
            Return m_Name
        End Get
    End Property

End Class

[C#]

// This code will trigger the rule violation

using System;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class CustomUserAttribute: Attribute // class is not abstract and is not sealed
{

    private string m_Name;

    public CustomUserAttribute(string name)
    {
        m_Name = name;
    }

    public string Name()
    {
        get
        {
            return m_Name;
        }
    }

}

// This is the correct implementation

using System;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public static class CustomUserAttribute: Attribute // class is not abstract and is not sealed
{

    private string m_Name;

    public CustomUserAttribute(string name)
    {
        m_Name = name;
    }

    public string Name()
    {
        get
        {
            return m_Name;
        }
    }

}


Dispose methods should call SuppressFinalize

Rule ID: PE00001

Problem

A type implements System.IDisposable.Dispose, but does not prevent the Finalize method from running by calling the GC.SuppressFinalize method.

Rule Description

IDisposable.Dispose method performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. Because the Dispose method must be called explicitly, objects that implement IDisposable must also implement a finalizer to handle freeing resources when Dispose is not called. By default, the garbage collector will automatically call an object's finalizer prior to reclaiming its memory. However, once the Dispose method has been called, it is typically unnecessary for the garbage collector to call the disposed object's finalizer. To prevent automatic finalization, Dispose implementations can call the GC.SuppressFinalize method.

This rule is similar to FxCop rule 'Dispose methods should call SuppressFinalize', CheckId CA1816

Correcting Violations

The rule provides the following auto-correct options:
  • Find the Dispose method and insert call to GC.SuppressFinalize at the end of the method.

Rule Instances

Instances of this rule in the built-in profile:
  • Dispose methods should call SuppressFinalize.

Example

The following example shows the basic design pattern for implementing Dispose that satisfies the rule.

[Visual Basic]

Public Class Sample
  Implements IDisposable

  ' Implement IDisposable

  Public Overloads Sub Dispose() Implements IDisposable.Dispose
    Dispose(True)
    GC.SuppressFinalize(Me)
  End Sub

  Protected Overloads Overridable Sub Dispose(disposing As Boolean)
    If disposing Then
      ' Free other state (managed objects).
    End If
    ' Free your own state (unmanaged objects).
    ' Set large fields to null.
  End Sub

  Protected Overrides Sub Finalize()
    ' Simply call Dispose(False).
    Dispose (False)
  End Sub

End Class

[C#]

public class Sample: IDisposable
{

  // Implement IDisposable

  public void Dispose()
  {
    Dispose(true);
    GC.SuppressFinalize(this);
  }

  protected virtual void Dispose(bool disposing)
  {
    if (disposing)
    {
      // Free other state (managed objects).
    }
    // Free your own state (unmanaged objects).
    // Set large fields to null.
  }

  ~Sample()
  {
    Dispose(false);
  }

}


Do not check for empty strings using Equals

Rule ID: PE00011

Problem

A string should not be compared to an empty string using System.Object.Equals.

Rule Description

Length property of a string should be compared with zero, rather than comparing a string with "" or String.Empty.
This technique delivers better performance.

This rule is similar to FxCop rule 'Test for empty strings using string length', CheckId CA1820

Correcting Violations

The rule provides the following auto-correct options:
  • Change the comparison to use the IsNullOrEmpty(System.String) method and test for the null string.
  • Change the comparison to use the Length property and test for the null string.
  • Change the comparison to use the IsNullOrEmpty(System.String) method.

Rule Instances

Instances of this rule in the built-in profile:
  • Do not check for empty strings using Equals.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

  Public Function JoinWords(words() As String, delimeter As String) As String

    Dim s As String = String.Empty
    Dim result As String = String.Empty
    Dim i As Integer

    For i = 0 To words.Length - 1
      s = words(i)
      If s <> "" Then ' Violates the rule
        If result = String.Empty Then ' Violates the rule
          result = s
        Else
          result &= delimeter & s
        End If
      End If
    Next i

    Return result

  End Function

' This is the correct implementation

  Public Function JoinWords(words() As String, delimeter As String) As String

    Dim s As String = String.Empty
    Dim result As String = String.Empty
    Dim i As Integer

    For i = 0 To words.Length - 1
      s = words(i)
      If s.Length <> 0 Then
        If result.Length = 0 Then
          result = s
        Else
          result &= delimeter & s
        End If
      End If
    Next i

    Return result

  End Function

[C#]

// This code will trigger the rule violation

  public string JoinWords(string[] words, string delimeter)
  {
    string s = String.Empty;
    string result = String.Empty;
    for (int i = 0; i < words.Length; i++)
    {
      s = words[i];
      if (s != "") // Violates the rule
      {
        if (result == String.Empty) // Violates the rule
        {
          result = s;
        }
        else
        {
          result += delimeter + s;
        }
      }
    }
    return result;
  }

// This is the correct implementation

  public string JoinWords(string[] words, string delimeter)
  {
    string s = String.Empty;
    string result = String.Empty;
    for (int i = 0; i < words.Length; i++)
    {
      s = words[i];
      if (s.Length != 0)
      {
        if (result.Length == 0)
        {
          result = s;
        }
        else
        {
          result += delimeter + s;
        }
      }
    }
    return result;
  }


Do not initialize unnecessarily

Rule ID: PE00010

Problem

The field is initialized with its default value.

Rule Description

The fields, that is initialized with its default value in the constructor, increase the size of an assembly and degrade performance. Such initialization is redundant, because the CLR (Common Language Runtime) initializes all fields with their default values before running the constructor.

This rule is similar to FxCop rule 'Do not initialize unnecessarily', CheckId CA1805

Correcting Violations

The rule provides the following auto-correct options:
  • Remove the field initialization.

Rule Instances

Instances of this rule in the built-in profile:
  • Do not initialize unnecessarily.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System

Public Class MyClass

  Dim BoolField As Boolean
  Dim IntField As Integer
  Dim DoubleField As Double
  Dim StringField As String

  Sub New()

    ' The following initializations violate the rule
    BoolField = False
    IntField = 0
    DoubleField = 0
    StringField = Nothing

  End Sub

  ...

End Class

' This is the correct implementation

Imports System

Public Class MyClass

  Public BoolField As Boolean
  Public IntField As Integer
  Public DoubleField As Double
  Public StringField As String

  Sub New()

    ' Redundant initializations are removed

  End Sub

  ...

End Class

[C#]

// This code will trigger the rule violation

using System;

public class MyClass
{

  bool BoolField;
  int IntField;
  double DoubleField;
  string StringField;

  public MyClass()
  {

    // The following initializations violate the rule
    BoolField = false;
    IntField = 0;
    DoubleField = 0;
    StringField = null;

  }

  ...

}

// This is the correct implementation

using System;

public class MyClass
{

  bool BoolField;
  int IntField;
  double DoubleField;
  string StringField;

  public MyClass()
  {

    // Redundant initializations are removed

  }

  ...

}


Override equals and operator equals on value types

Rule ID: PE00002

Problem

Equality operator == does not implemented by the public value type.

Or

System.Object.Equals does not overrided by the public value type.

Rule Description

The inherited implementation of Equals for value types compares the contents of all fields using the Reflection library, which is computationally expensive.

The following guidelines should be considered for implementing a value type:
  • Consider overriding Equals to gain increased performance over that provided by the default implementation of Equals on ValueType.
  • If you override Equals and the language supports operator overloading, you must overload the equality operator for your value type.
This rule is similar to FxCop rule 'Override equals and operator equals on value types', CheckId CA1815

Correcting Violations

The rule provides the following auto-correct options:
  • Override System.Object.Equals method.
  • Implement the equality operator.

Rule Instances

Instances of this rule in the built-in profile:
  • Override equals and operator equals on value types.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

  Imports System

  Public Structure Point
    Private _x As Integer
    Private _y As Integer

    Public Sub New(ByVal x As Integer, ByVal y As Integer)
      _x = x
      _y = y
    End Sub

    Public ReadOnly Property X As Integer
      Get
        Return _x
      End Get
    End Property

    Public ReadOnly Property Y As Integer
      Get
        Return _y
      End Get
    End Property

  End Structure

' This is the correct implementation

  Imports System

  Public Structure Point
    Private _x As Integer
    Private _y As Integer

    Public Sub New(ByVal x As Integer, ByVal y As Integer)
      _x = x
      _y = y
    End Sub

    Public ReadOnly Property X As Integer
      Get
        Return _x
      End Get
    End Property

    Public ReadOnly Property Y As Integer
      Get
        Return _y
      End Get
    End Property

    Public Overloads Function GetHashCode() As Integer
      Return _x Xor _y
    End Function

    Public Overloads Function Equals(ByVal obj As Object) As Boolean
        If Not (TypeOf obj Is Point) Then
            Return False
        End If
        Return Equals(CType(obj, Point))
    End Function

    Public Overloads Function Equals(ByVal other As Point) As Boolean
        If _x <> other.X Then
            Return False
        End If
        Return _y = other.Y
    End Function

    Public Shared Operator ==(ByVal point1 As Point, ByVal point2 As Point) As Boolean
      Return point1.Equals(point2)
    End Operator

    Public Shared Operator <>(ByVal point1 As Point, ByVal point2 As Point) As Boolean
      Return Not point1.Equals(point2)
    End Operator

  End Structure

[C#]

// This code will trigger the rule violation

  using System;

  public struct Point
  {
    private int _x;
    private int _y;

    public Point(int x, int y)
    {
      _x = x;
      _y = y;
    }

    public int X
    {
      get
      {
        return _x;
      }
    }

    public int Y
    {
      get
      {
        return _y;
      }
    }

  }

// This is the correct implementation

  using System;

  public struct Point
  {
    private int _x;
    private int _y;

    public Point(int x, int y)
    {
      _x = x;
      _y = y;
    }

    public int X
    {
      get
      {
        return _x;
      }
    }

    public int Y
    {
      get
      {
        return _y;
      }
    }

    public override int GetHashCode()
    {
      return _x ^ _y;
    }

    public override bool Equals(object obj)
    {
        if (obj.GetType() != typeof(Point)
        {
            return false;
        }
        return Equals((Point)obj);
    }

    public override bool Equals(Point other)
    {
        if (_x != other.X)
        {
            return false;
        }
        return _y == other.Y;
    }

    public static bool operator==(Point point1, Point point2)
    {
      return point1.Equals(point2);
    }

    public static operator!=(Point point1, Point point2)
    {
      return !point1.Equals(point2);
    }

  }


Properties should not return arrays

Rule ID: PE00005

Problem

A public or protected property in a public type returns an array.

Rule Description

The property must return a copy of the array, to keep the array tamper-proof, because of arrays returned by properties are not write-protected. Calling of such property affects performance negatively. According to Microsoft .NET Framework guidelines, a method should be used when returning array.

This rule is similar to FxCop rule 'Properties should not return arrays', CheckId CA1819

Correcting Violations

The rule provides the following auto-correct options:
  • Convert property to getter and/or setter method.

Rule Instances

Instances of this rule in the built-in profile:
  • Properties should not return arrays.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System

Public Class Persons

    Private _names As String()

    Public Sub New(ByVal names As String())
        _names = names
    End Sub

    ' Violates the rule: the public property returns array
    Public ReadOnly Property Names() As String()
        Get
            Return CType(_names.Clone(), String())
        End Get
    End Property

End Class

' This is the correct implementation

Imports System

Public Class Persons

    Private _names As String()

    Public Sub New(ByVal names As String())
        _names = names
    End Sub

    ' Correct implementation: the property converted to method
    Public Function GetNames() As String()
        Return CType(_names.Clone(), String())
    End Function

End Class

[C#]

// This code will trigger the rule violation

using System;

public class Persons
{

    private string[] _names;

    public Persons(string[] names)
    {
        _names = names;
    }

    // Violates the rule: the public property returns array
    public string[] Names
    {
        get
        {
            return (string[])_names.Clone();
        }
    }

}

// This is the correct implementation

using System;

public class Persons
{

    private string[] _names;

    public Persons(string[] names)
    {
        _names = names;
    }

    // Correct implementation: the property converted to method
    public string[] GetNames()
    {
        return (string[])_names.Clone();
    }

}


Remove empty finalizers

Rule ID: PE00006

Problem

A type implements a finalizer that is empty or calls only the base type finalizer.

Rule Description

The protected Finalize method should only be implemented if the type must release one ore more unmanaged resources that it has directly allocated. Unnecessary Finalize method results in overhead at instantiation and suboptimal usage of memory.
The entire finalizer should be enclosed in #if DEBUG / #endif directives, if it is required for debugging.

This rule is similar to FxCop rule 'Remove empty finalizers', CheckId CA1821

Correcting Violations

The rule provides the following auto-correct options:
  • Comment out the empty finalizer.

Rule Instances

Instances of this rule in the built-in profile:
  • Remove empty finalizers.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Public Class TestClass1

    Private Message As String

    ' Rule violation: empty finalizer
    Protected Overrides Sub Finalize()
    End Sub

End Class

Public Class TestClass2

    Private Message As String

    ' Rule violation: if the DEBUG directive is not present, the finalizer will be empty
    Protected Overrides Sub Finalize()

        Debug.Print(Message)

    End Sub

End Class

' This is the correct implementation

Public Class TestClass2

    Private Message As String

    ' Correct implementation: the finalizer is not empty when the DEBUG directive is present
#if DEBUG
    Protected Overrides Sub Finalize()

        Debug.Print(Message)

    End Sub
#endif

End Class

[C#]

// This code will trigger the rule violation

public class TestClass1
{

    private string message;

    // Rule violation: empty finalizer
    ~TestClass1()
    {
    }

}

public class TestClass2
{

    private string message;

    // Rule violation: if the DEBUG directive is not present, the finalizer will be empty
    ~TestClass1()
    {

        Debug.Print(message);

    }

}

// This is the correct implementation

public class TestClass2
{

    private string message;

    // Correct implementation: the finalizer is not empty when the DEBUG directive is present
#if DEBUG
    ~TestClass1()
    {

        Debug.Print(message);

    }
#endif

}

Related Rules

Remove unused private methods

Remove unused internal classes

Remove unused locals


Remove unused internal classes

Rule ID: PE00008

Problem

The type is not externally visible and its instance is not created by code within the assembly.

Rule Description

Assembly-level (private or internal) types, that does not instantiated in the assembly, increase the size of an assembly and degrade performance.

This rule is similar to FxCop rule 'Avoid uninstantiated internal classes', CheckId CA1812

Correcting Violations

The rule provides the following auto-correct options:
  • Comment out the type.

Rule Instances

Instances of this rule in the built-in profile:
  • Remove unused internal classes.

Related Rules

Remove empty finalizers

Remove unused private methods

Remove unused locals


Remove unused locals

Rule ID: PE00003

Problem

A method declares a local variable, but does not use the variable except possibly as the recipient of an assignment statement.

Rule Description

Unused local variables and unnecessary assignments increase the size of an assembly and degrade performance.

This rule is similar to FxCop rule 'Remove unused locals', CheckId CA1804

Correcting Violations

The rule provides the following auto-correct options:
  • Comment out the declaration of the local variable.

Rule Instances

Instances of this rule in the built-in profile:
  • Remove unused locals.

Example

The following example show code that triggers the rule violation.

[Visual Basic]

' This code will trigger the rule violation

Imports System
Imports System.Windows.Forms

Public Class TestClass1

    ' Rule violation: local variables are not used in the method and therefore unnecessary
    Sub TestMethod()

         Dim i As Integer
         Dim s As String = "Test string"
         Dim textBox1 As New TextBox()
         Dim myIntArray() As Integer = {1, 2, 3, 4, 5}

    End Sub

End Class

[C#]

// This code will trigger the rule violation

using System;
using System.Windows.Forms;

public class TestClass1
{

    // Rule violation: local variables are not used in the method and therefore unnecessary
    public void TestMethod()
    {

         int i;
         string s = "Test string";
         TextBox textBox1 = new TextBox();
         int[] myIntArray = new int[5] {1, 2, 3, 4, 5};

    }

}

Related Rules

Remove empty finalizers

Remove unused private methods

Remove unused internal classes


Remove unused private methods

Rule ID: PE00004

Problem

A method does not have callers in the assembly.

Rule Description

Assembly-level (private or internal) methods, that does not have callers in the assembly, and is not invoked by a delegate or by the CLR, increase the size of an assembly and degrade performance.

This rule is similar to FxCop rule 'Avoid uncalled private code', CheckId CA1811

Correcting Violations

The rule provides the following auto-correct options:
  • Comment out the uncalled method.

Rule Instances

Instances of this rule in the built-in profile:
  • Remove unused private methods.

Related Rules

Remove empty finalizers

Remove unused internal classes

Remove unused locals


Remove unused public classes

Rule ID: PE00012

Problem

The type is externally visible and its instance is not created by code within the assembly.

Rule Description

Public types, that does not instantiated in the assembly, increase the size of an assembly and degrade performance.

This rule is similar to FxCop rule 'Avoid uninstantiated internal classes', CheckId CA1812

Correcting Violations

The rule provides the following auto-correct options:
  • Comment out the type.

Rule Instances

Instances of this rule in the built-in profile:
  • Remove unused public classes.

Related Rules

Remove unused internal classes

Remove empty finalizers

Remove unused private methods

Remove unused locals


Use constants where appropriate

Rule ID: PE00009

Problem

The field is declared as static and readonly (Shared and ReadOnly in Visual Basic), but is initialized with a constant value.

Rule Description

The value of a static readonly (Shared ReadOnly in Visual Basic) field is computed at runtime when the static constructor is called. If a static constructor is not declared explicitly, the compiler emits it to initialize the field.

The value of the const (Const in Visual Basic) field is computed in the compile time and stored in the metadata. That increases runtime performance. Therefore, const (Const in Visual Basic) field should be used instead of static readonly (Shared ReadOnly in Visual Basic) field if the value of the field is computable in the compile time.

This rule is similar to FxCop rule 'Use literals where appropriate', CheckId CA1802

Correcting Violations

The rule provides the following auto-correct options:
  • Replace static readonly (Shared ReadOnly in Visual Basic) modifiers with the const (Const in Visual Basic) modifier.

Rule Instances

Instances of this rule in the built-in profile:
  • Use constants where appropriate.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System

Public Class MyClass

  Shared ReadOnly IntField As Integer = 2
  Shared ReadOnly DoubleField As Double = IntField * 3.14
  Shared ReadOnly StringField As String = "string"

  ...

End Class

' This is the correct implementation

Imports System

Public Class MyClass

  Const IntField As Integer = 2
  Const DoubleField As Double = IntField * 3.14
  Const StringField As String = "string"

  ...

End Class

[C#]

// This code will trigger the rule violation

using System;

public class MyClass
{

  static readonly int IntField = 2;
  static readonly double DoubleField = IntField * 3.14;
  static readonly string StringField = "string";

  ...

}

// This is the correct implementation

using System;

public class MyClass
{

  const int IntField = 2;
  const double DoubleField = IntField * 3.14;
  const string StringField = "string";

  ...

}


Security Rules

This section will guide you through the set of Security Rules.

Click on any of the links below to go directly to the corresponding rule.

Aptca methods should only call aptca methods

Aptca types should only extend aptca base types

Array fields should not be read only

Assemblies should declare minimum security

Do not declare read only mutable reference types

Do not indirectly expose methods with link demands

Method security should be a superset of type

Override link demands should be identical to base

Pointers should not be visible

Review declarative security on value types

Review deny and permit only usage

Review suppress unmanaged code security usage

Review visible event handlers

Seal methods that satisfy private interfaces

Secure asserts

Secured types should not expose fields

Secure GetObjectData overrides

Secure serialization constructors

Security transparent code should not assert

Type link demands require inheritance demands

Wrap vulnerable finally clauses in outer try


Aptca methods should only call aptca methods

Rule ID: SE00020

Problem

Method in an assembly with the System.Security.AllowPartiallyTrustedCallersAttribute attribute calls method in assembly that does not have the attribute.

Rule Description

According to Microsoft .NET Framework guidelines, methods in assemblies marked with the System.Security.AllowPartiallyTrustedCallersAttribute attribute should call methods in another assembly only if the other assembly is also marked with the System.Security.AllowPartiallyTrustedCallersAttribute attribute. This guideline ensures that untrusted assemblies cannot use the assembly marked with System.Security.AllowPartiallyTrustedCallersAttribute attribute to call into an assembly that isn't supposed to be available to untruted callers.

Methods in assemblies marked with the System.Security.AllowPartiallyTrustedCallersAttribute attribute should always demand one or more permissions from callers; exceptions to this rule are sometimes necessary but you should carefully review your code to ensure that untrusted assemblies cannot use your public methods to perform dangerous actions.

This rule is similar to FxCop rule 'Aptca methods should only call aptca methods', CheckId CA2116

Correcting Violations

The rule provides the following auto-correct options:
  • Add System.Security.AllowPartiallyTrustedCallersAttribute attribute to the assembly
  • Remove System.Security.AllowPartiallyTrustedCallersAttribute from the assembly

Rule Instances

Instances of this rule in the built-in profile:
  • Aptca methods should only call aptca methods.

Related Rules

Aptca types should only extend aptca base types


Aptca types should only extend aptca base types

Rule ID: SE00002

Problem

Type in the assembly derives from the type declared in another assembly that does not have System.Security.AllowPartiallyTrustedCallersAttribute attribute.

Rule Description

According to Microsoft .NET Framework guidelines, types in assemblies marked with the System.Security.AllowPartiallyTrustedCallersAttribute attribute shouldn't derive from types defined in assemblies that aren't marked with the System.Security.AllowPartiallyTrustedCallersAttribute attribute. (By default, public and protected types in strong-named assemblies are protected with an InheritanceDemand, but the System.Security.AllowPartiallyTrustedCallersAttribute attribute disables this protection.)

System.Security.AllowPartiallyTrustedCallersAttribute attribute can be applied only to strong-named assemblies that are meant to be called from partially trusted assemblies. (By default, strong-named assemblies can be called only by fully trusted assemblies.)

The security issue occurs when a type in an assembly marked with the System.Security.AllowPartiallyTrustedCallersAttribute attribute inherits from a type in another assembly that isn't marked with this attribute and that is supposed to contain private data. In that case, untrusted caller gain access to information that should be available to fully trusted types only.

This rule is similar to FxCop rule 'Aptca types should only extend aptca base types', CheckId CA2117

Correcting Violations

The rule provides the following auto-correct options:
  • Add System.Security.AllowPartiallyTrustedCallersAttribute attribute to the assembly
  • Remove System.Security.AllowPartiallyTrustedCallersAttribute attribute from the assembly

Rule Instances

Instances of this rule in the built-in profile:
  • Aptca types should only extend aptca base types.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This type contains private data in an assembly
' that is NOT marked with System.Security.AllowPartiallyTrustedCallersAttribute
Public Class LoginData
    Public ReadOnly Name As String = "John Smith"
    Public ReadOnly Password As String = "pass"
End Class

' This code will trigger the rule violation

' This type is placed in an assembly
' marked with System.Security.AllowPartiallyTrustedCallersAttribute

<Assembly: AllowPartiallyTrustedCallers()>

Public Class PersonalData
    Inherits LoginData

    Public Overrides Function ToString() As String
        Return Me.Name & ", " & Me.Password
    End Function

End Class

' The main assembly isn't fully trusted but can read private data.
Sub Main()
    Dim data As New PersonalData
    Console.WriteLine(data) ' Displays "John Smith, pass"
End Sub

' This is the correct implementation

' Mark the first assembly with the
' System.Security.AllowPartiallyTrustedCallersAttribute attribute,
' if it is possible

<Assembly: AllowPartiallyTrustedCallers()>

Public Class LoginData
    Public ReadOnly Name As String = "John Smith"
    Public ReadOnly Password As String = "pass"
End Class

<Assembly: AllowPartiallyTrustedCallers()>

Public Class PersonalData
    Inherits LoginData

    Public Overrides Function ToString() As String
        Return Me.Name & ", " & Me.Password
    End Function

End Class

' Alternatively, the System.Security.AllowPartiallyTrustedCallersAttribute attribute
' should be removed from the second assembly

[C#]

// This type contains private data in an assembly
// that is NOT marked with System.Security.AllowPartiallyTrustedCallersAttribute
public class LoginData
{
    public readonly string Name = "John Smith";
    Public readonly string Password = "pass";
}

// This code will trigger the rule violation

// This type is placed in an assembly
// marked with System.Security.AllowPartiallyTrustedCallersAttribute

[assembly:AllowPartiallyTrustedCallers()]

public class PersonalData: LoginData
{

    public override string ToString()
    {
        return this.Name + ", " + this.Password;
    }

}

// The main assembly isn't fully trusted but can read private data.
static void Main()
{
    PersonalData data = new PersonalData();
    Console.WriteLine(data); // Displays "John Smith, pass"
}

// This is the correct implementation

// Mark the first assembly with the
// System.Security.AllowPartiallyTrustedCallersAttribute attribute,
// if it is possible

[Assembly: AllowPartiallyTrustedCallers()]

public class LoginData
{
    public readonly string Name = "John Smith";
    Public readonly string Password = "pass";
}

[assembly:AllowPartiallyTrustedCallers()]

public class PersonalData: LoginData
{

    public override string ToString()
    {
        return this.Name + ", " + this.Password;
    }

}

// Alternatively, the System.Security.AllowPartiallyTrustedCallersAttribute attribute
// should be removed from the second assembly

Related Rules

Aptca methods should only call aptca methods


Array fields should not be read only

Rule ID: SE00019

Problem

An externally visible field that holds an array is declared read-only.

Rule Description

According to Microsoft .NET Framework guidelines, a field should be marked with the ReadOnly (Visual Basic) or readonly (C#) keyword if the value of the field must not change after instantiation. If a read-only field contains an array, the reference to the array cannot be changed. However, the elements of such array can be changed. Therefore, an externally visible read-only field that holds an array maight be exploited and cause security vulnerability.

This rule is similar to FxCop rule 'Array fields should not be read only', CheckId CA2105

Correcting Violations

The rule provides the following auto-correct options:
  • Change field modifier and create a method that returns a clone of an array.
  • Manually replace the array with a strongly typed collection that cannot be changed.

Rule Instances

Instances of this rule in the built-in profile:
  • Array fields should not be read only.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Namespace SecureData

  Public Class AccountManager

    Public ReadOnly AccountValues As Decimal() = {10000, 20000, 30000}

    ...

  End Class

End Namespace

' This class can use and modify secure data in the read-only field
Public Class AccountsProcessor

  Public Sub ProcessAccounts()

    Dim Accounts As AccountManager = New AccountManager()

    Dim values As Decimal() = Accounts.AccountValues

    ' the element of the read-only array was modified
    values(1) = 100000

  End Sub

End Class

' This is the correct implementation

Namespace SecureData

  Public Class AccountManager

    ' Field visibility changed from Public to Private
    Private AccountValues As Decimal() = {10000, 20000, 30000}

    ' New method returns a clone of an array
    Public Function GetAccountValues() As Decimal()

      Return CType(AccountValues.Clone(), Decimal())

    End Function

    ...

  End Class

End Namespace

' This class can use and secure data, but cannot modify
Public Class AccountsProcessor

  Public Sub ProcessAccounts()

    Dim Accounts As AccountManager = New AccountManager()

    Dim values As Decimal() = Accounts.GetAccountValues()

    ' Local copy of data was modified.
    values(1) = 100000
    ' Secure data in the AccountManager class stays unchanged.

  End Sub

End Class

' Alternatively, the AccountValues array can be replaced
' with a strongly typed collection that cannot be changed

[C#]

// This code will trigger the rule violation

namespace SecureData
{

  public class AccountManager
  {

    public readonly decimal[] AccountValues = new decimal[3]{10000, 20000, 30000};

    ...

  }

}

// This class can use and modify secure data in the read-only field
public class AccountsProcessor
{

  public void ProcessAccounts()
  {

    AccountManager Accounts = new AccountManager();

    decimal[] values = Accounts.AccountValues;

    // the element of the read-only array was modified
    values[1] = 100000;

  }

}

// This is the correct implementation

namespace SecureData
{

  public class AccountManager
  {

    // Field visibility changed from Public to Private
    private decimal[] AccountValues = new decimal[3] {10000, 20000, 30000};

    // New method returns a clone of an array
    public decimal[] GetAccountValues()
    {

      return (decimal[])AccountValues.Clone();

    }

    ...

  }

}

// This class can use and secure data, but cannot modify
public class AccountsProcessor
{

  public void ProcessAccounts()
  {

    AccountManager Accounts = new AccountManager();

    decimal[] values = Accounts.GetAccountValues();

    // Local copy of data was modified.
    values[1] = 100000;
    // Secure data in the AccountManager class stays unchanged.

  }

}

// Alternatively, the AccountValues array can be replaced
// with a strongly typed collection that cannot be changed


Assemblies should declare minimum security

Rule ID: SE00006

Problem

Assembly does not have attributes specifying its minimum, optional, or refused security permissions.

Rule Description

Assemblies should be marked with permission attributes specifying suitable RequestMinimum, RequestOptional, and RequestRefuse actions.

This rule ensures that the assembly has only the permissions that it strictly needs for its chores. By reducing the prmission set assigned to the assembly, you make it harder for malicious code to exploit your assembly to access protected resources.

The RequestMinimum action specifies the permissions that are necessary for the assembly to work correctly; if the .NET runtime can't grant these permissions, the assembly won't be loaded and a System.Security.Policy.PolicyException is thrown. The RequestOptional action specifies the permissions that the assembly would like to use but that aren't crucial for its operations; if one of these permissions isn't granted, the assembly loads all the same, but its user interfaceshould disable or hide all commands that would perform a prohibited action. The RequestRefuse action specifies permissionsthat the .NET runtime should never grant to the assembly.

The permission set granted to the assembly consists of all the permissions marked with the RequestMinimum action, plus all the permissions marked with the RequestOptional action, minus all the permissions marked with the RequestRefuse action. In all cases, however, an assembly won't be given permissions that aren't granted by the policy level and the code group the assembly belongs to.

This rule is similar to FxCop rule 'Assemblies should declare minimum security', CheckId CA2209

Correcting Violations

The rule provides the following auto-correct options:
  • Add suitable attribute to the assembly.

Rule Instances

Instances of this rule in the built-in profile:
  • Assemblies should declare minimum security.

Example

The following example shows the attributes that can be applied to an assembly that requires permission to create user interface elements and access files by means of common file dialogs, that wants to be granted permission to use performance counters (but that can run without them), and that explicitly refuses to receive the permission to call unmanaged code:

[Visual Basic]

Imports System
Imports System.Security
Imports System.Security.Permissions

<Assembly: UIPermission(SecurityAction.RequestMinimum, Unrestricted:=True)>
<Assembly: FileDialogPermission(SecurityAction.RequestMinimum, Unrestricted:=True)>
<Assembly: PerformanceCounterPermission(SecurityAction.RequestOptional, Unrestricted:=True)>
<Assembly: SecurityPermission(SecurityAction.RequestRefuse, UnmanagedCode:=True)>

Namespace UserLibrary

    ...

End Namespace

[C#]

using System;
using System.Security;
using System.Security.Permissions;

[assembly:UIPermission(SecurityAction.RequestMinimum, Unrestricted=true)]
[assembly:FileDialogPermission(SecurityAction.RequestMinimum, Unrestricted=true)]
[assembly:PerformanceCounterPermission(SecurityAction.RequestOptional, Unrestricted=true)]
[assembly:SecurityPermission(SecurityAction.RequestRefuse, UnmanagedCode=true)]

namespace UserLibrary
{

    ...

}


Do not declare read only mutable reference types

Rule ID: SE00003

Problem

Externally visible read-only field has a return type that is mutable. A mutabe type is a type whose instance data can be modified.

Rule Description

A mutabe type is a type whose instance data can be modified. Mutable type can change the value of an instance of the class. In the opposite, an immutable type cannot change its value once it is instantiated.

The System.Text.StringBuilder class, which contains members that can change the value of its instance, is an example of a mutable reference type. The System.String class, which can never change its value once it is instantiated, is an example of an immutable reference type.

The ReadOnly modifier (readonly in C#) on a reference type field prevents the field from being replaced by another instance of the reference type. But in the same time the field's instance data can be modified through the reference type.

This rule is similar to FxCop rule 'Do not declare read only mutable reference types', CheckId CA2104

Correcting Violations

The rule provides the following auto-correct options:
  • Remove ReadOnly modifier from the field (readonly in C#).

Rule Instances

Instances of this rule in the built-in profile:
  • Do not declare read only mutable reference types.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System.Text

Public Class SampleBufferedReader

    ' read-only field has a return type that is mutable
    Shared Protected ReadOnly Buffer As StringBuilder

    Shared Sub New()
        Buffer = New StringBuilder()
    End Sub

    ...

End Class

' This is the correct implementation

Imports System.Text

Public Class SampleBufferedReader

    // ReadOnly modifier is removed
    Shared Protected Buffer As StringBuilder

    Shared Sub New()
        Buffer = New StringBuilder()
    End Sub

    ...

End Class

[C#]

// This code will trigger the rule violation

using System.Text;

public class SampleBufferedReader
{

    // read-only field has a return type that is mutable
    protected static readonly StringBuilder Buffer;

    static SampleBufferedReader()
    {
        Buffer = new StringBuilder();
    }

    ...

}

// This is the correct implementation

using System.Text;

public class SampleBufferedReader
{

    // readonly modifier is removed
    protected static StringBuilder Buffer;

    static SampleBufferedReader()
    {
        Buffer = new StringBuilder();
    }

    ...

}


Do not indirectly expose methods with link demands

Rule ID: SE00009

Problem

The member has a link demand and is called by the member that does not perform any security checks.

Rule Description

According to Microsoft .NET Framework guidelines, you should not access members protected with a SecurityAction.LinkDemand security action, from members that are not protected with similar SecurityAction.LinkDemand security action.

Unlike the SecurityAction.Demand security action, which checks the permissions of all the callers in the stack, the SecurityAction.LinkDemand action check only the permissions of the immediate caller and does it only when the method is JIT-compiled (rather then at each method call). The behavior can improve performance but opens up a few security risks. A malicious client might wait until a trusted assembly invokes (and indirectly JIT-compiles) the protected method and then instantiate an object that derives from the secured type but overrides the virtual member.

This rule is similar to FxCop rule 'Do not indirectly expose methods with link demands', CheckId CA2122

Correcting Violations

The rule provides the following auto-correct options:
  • Add necessary attribute to the member

Rule Instances

Instances of this rule in the built-in profile:
  • Do not indirectly expose methods with link demands.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System
Imports System.Security
Imports System.Security.Permissions

Namespace DocumentsProcessing

  Public Class Document

    <FileIOPermission(SecurityAction.LinkDemand, Unrestricted := True)> _
    Public Function GetDocumentText() As String

      ...

    End Function

    ' Violates the rule: the method does not protected with similar LinkDemand security action
    Public Function IndirectlyExposeDocumentText() As String

      Return this.GetDocumentText()

    End Function

  End Class

End Namespace

' This is the correct implementation

Imports System
Imports System.Security
Imports System.Security.Permissions

Namespace DocumentsProcessing

  Public Class Document

    <FileIOPermission(SecurityAction.LinkDemand, Unrestricted := True)> _
    Public Function GetDocumentText() As String

      ...

    End Function

    <FileIOPermission(SecurityAction.LinkDemand, Unrestricted := True)> _
    Public Function IndirectlyExposeDocumentText() As String

      Return this.GetDocumentText()

    End Function

  End Class

End Namespace

[C#]

// This code will trigger the rule violation

using System;
using System.Security;
using System.Security.Permissions;

namespace DocumentsProcessing
{

  public class Document
  {

    [FileIOPermission(SecurityAction.LinkDemand, Unrestricted = true)]
    public string GetDocumentText()
    {

      ...

    }

    // Violates the rule: the method does not protected with similar LinkDemand security action
    public string IndirectlyExposeDocumentText()
    {

      return this.GetDocumentText();

    }

  }

}

// This is the correct implementation

using System;
using System.Security;
using System.Security.Permissions;

namespace DocumentsProcessing
{

  public class Document
  {

    [FileIOPermission(SecurityAction.LinkDemand, Unrestricted = true)]
    public string GetDocumentText()
    {

      ...

    }

    [FileIOPermission(SecurityAction.LinkDemand, Unrestricted = true)]
    public string IndirectlyExposeDocumentText()
    {

      return this.GetDocumentText();

    }

  }

}

Related Rules

Override link demands should be identical to base

Review suppress unmanaged code security usage


Method security should be a superset of type

Rule ID: SE00018

Problem

Type has declarative security and its method has declarative security for the same security action, and the security action is not LinkDemand or InheritanceDemand, and the permissions checked by the type are not a subset of the permissions checked by the method.

Rule Description

If the same declarative security action is applied to both a type and one of its methods, the permission checked at the method level should be more restrictive than the permission checked at the type level. (This gudeline doesn't apply to LinkDemand actions.)

If you mark both a type and one of its methods for the same security action but for a different range of permissions, the two permissions are not combined together. Instead, the type-level permission is ignored and only the method-level permission is applied.

If this guideline is ignored, malicious code might bypass the more restrictive type-level permissions by obtaining an istance of the type by some other means - for example, using a factory method exposed by a trusted assembly - and then invoke the method without any security exception.

This rule is similar to FxCop rule 'Method security should be a superset of type', CheckId CA2114

Correcting Violations

The rule provides the following auto-correct options:
  • Add required attribute(s) to the method.
  • Remove required attribute(s) from the type.
  • Remove required attribute(s) from the method.

Rule Instances

Instances of this rule in the built-in profile:
  • Method security should be a superset of type.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

<FileIOPermission(SecurityAction.Demand, Unresticted:=True)> _
Public Class FileProcessing

  <FileIOPermission(SecurityAction.Demand, Read:="C:\Text")> _
  Public Function GetFile(ByVal fileName As String) As String

    ...

  End Function

  ...

End Class

' This is the correct implementation

<FileIOPermission(SecurityAction.Demand, Unresticted:=True)> _
Public Class FileProcessing

  Public Function GetFile(ByVal fileName As String) As String

    ...

  End Function

  ...

End Class

[C#]

// This code will trigger the rule violation

[FileIOPermission(SecurityAction.Demand, Unresticted = true)]
public class FileProcessing
{

  [FileIOPermission(SecurityAction.Demand, Read = "C:\Text")]
  public string GetFile(string fileName)
  {

    ...

  }

  ...

}

// This is the correct implementation

[FileIOPermission(SecurityAction.Demand, Unresticted = true)]
public class FileProcessing
{

  public string GetFile(string fileName)
  {

    ...

  }

  ...

}


Override link demands should be identical to base

Rule ID: SE00007

Problem

Method in a public type implements an interface or overrides a method, and does not marked with the same SecurityAction.LinkDemand security action as the interface method or virtual method.

Rule Description

According to Microsoft .NET Framework guidelines, if you override a method marked with a SecurityAction.LinkDemand security action, the method in the derived type should be marked with the same SecurityAction.LinkDemand security action.

Unlike the SecurityAction.Demand security action, which checks the permissions of all the callers in the stack, the SecurityAction.LinkDemand action check only the permissions of the immediate caller and does it only when the method is JIT-compiled (rather then at each method call). The behavior can improve performance but opens up a few security risks. A malicious client might wait until a trusted assembly invokes (and indirectly JIT-compiles) the protected method and then instantiate an object that derives from the secured type but overrides the virtual member.

This rule is similar to FxCop rule 'Override link demands should be identical to base', CheckId CA2123

Correcting Violations

The rule provides the following auto-correct options:
  • Add necessary attribute to the method

Rule Instances

Instances of this rule in the built-in profile:
  • Override link demands should be identical to base.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System
Imports System.Security
Imports System.Security.Permissions

Namespace DocumentsProcessing

  Public Class Document

    <FileIOPermission(SecurityAction.LinkDemand, Unrestricted := True)> _
    Public Overridable Function GetDocumentText() As String

      ...

    End Function

  End Class

  Public Class SecureDocument
    Inherits Document

    ' Violation: The method does not marked with LinkDemand security action,
    ' but the base class version does.
    Public Overrides Function GetDocumentText() As String

      ...

    End Function

  End Class

End Namespace

' This is the correct implementation

Imports System
Imports System.Security
Imports System.Security.Permissions

Namespace DocumentsProcessing

  Public Class Document

    <FileIOPermission(SecurityAction.LinkDemand, Unrestricted := True)> _
    Public Overridable Function GetDocumentText() As String

      ...

    End Function

  End Class

  Public Class SecureDocument
    Inherits Document

    <FileIOPermission(SecurityAction.LinkDemand, Unrestricted := True)> _
    Public Overrides Function GetDocumentText() As String

      ...

    End Function

  End Class

End Namespace

[C#]

// This code will trigger the rule violation

using System;
using System.Security;
using System.Security.Permissions;

namespace DocumentsProcessing
{

  public class Document
  {

    [FileIOPermission(SecurityAction.LinkDemand, Unrestricted = true)]
    public virtual string GetDocumentText()
    {

      ...

    }

  }

  public class SecureDocument: Document
  {

    // Violation: The method does not marked with LinkDemand security action,
    // but the base class version does.
    public override string GetDocumentText()
    {

      ...

    }

  }

}

' This is the correct implementation

using System;
using System.Security;
using System.Security.Permissions;

namespace DocumentsProcessing
{

  public class Document
  {

    [FileIOPermission(SecurityAction.LinkDemand, Unrestricted = true)]
    public virtual string GetDocumentText()
    {

      ...

    }

  }

  public class SecureDocument: Document
  {

    [FileIOPermission(SecurityAction.LinkDemand, Unrestricted = true)]
    public override string GetDocumentText()
    {

      ...

    }

  }

}

Related Rules

Do not indirectly expose methods with link demands

Review suppress unmanaged code security usage


Pointers should not be visible

Rule ID: SE00001

Problem

Externally visible field that has System.IntPtr or System.UIntPtr return type is not read-only.

Rule Description

System.IntPtr and System.UIntPtr are platform-specific types that are used to represent a pointer or a handle for accessing unmanaged memory. Malicious code can change the value of the pointer, if a pointer is not read-only, private, or internal. That can potentially cause application or system failures or allow access to arbitrary locations in memory.

This rule is similar to FxCop rule 'Pointers should not be visible', CheckId CA2111

Correcting Violations

The rule provides the following auto-correct options:
  • Make field read-only.
  • Change field modifier to internal (Friend in Visual Basic).
  • Change field modifier to private.

Rule Instances

Instances of this rule in the built-in profile:
  • Pointers should not be visible.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System

Namespace SecurityTestLibrary

   Public Class ExposedPointers

        Public exposedPointer1 As IntPtr
        Public exposedPointer2 As UIntPtr
        Protected exposedPointer3 As IntPtr

   End Class

End Namespace

' This is the correct implementation

Imports System

Namespace SecurityTestLibrary

   Public Class ProtectedPointers

        Friend  protectedPointer1 As IntPtr
        Private protectedPointer2 As IntPtr

        Public ReadOnly protectedPointer3 As IntPtr
        Protected ReadOnly protectedPointer4 As UIntPtr

   End Class

End Namespace

[C#]

// This code will trigger the rule violation

using System;

namespace SecurityTestLibrary
{

   public class ExposedPointers
   {

        public IntPtr exposedPointer1;
        public UIntPtr exposedPointer2;
        protected IntPtr exposedPointer3;

   }

}

' This is the correct implementation

using System;

namespace SecurityTestLibrary
{

   public class ProtectedPointers
   {

        internal IntPtr protectedPointer1;
        private IntPtr protectedPointer2;

        public readonly IntPtr protectedPointer3;
        protected readonly UIntPtr protectedPointer4;

   }

}


Review declarative security on value types

Rule ID: SE00017

Problem

An externally visible structure is secured by System.Security.Permissions.SecurityAction.Demand or System.Security.Permissions.SecurityAction.LinkDemand.

Rule Description

According to Microsoft .NET Framework guidelines, a value type or its default constructor should not be protected with an imperative System.Security.Permissions.SecurityAction.Demand or System.Security.Permissions.SecurityAction.LinkDemand security action.

The .NET Framework allocates and initializes value types by means of their default (parameterless) constructor, and then executes any constructor with parameters explicitly invoked by the caller. If such a constructor is protected with a System.Security.Permissions.SecurityAction.Demand or System.Security.Permissions.SecurityAction.LinkDemand security action and the caller doesn't pass the security check, the .NET Framework throws an exception, but the instance of the value type still exists (as initialized by the default constructor) and its members can be used freely.

This rule is similar to FxCop rule 'Review declarative security on value types', CheckId CA2108

Correcting Violations

The rule provides the following auto-correct options:
  • Remove attribute(s) from the structure.
  • Remove attribute(s) from the constructor.
  • Remove demand or link demand from the constructor manually.

Rule Instances

Instances of this rule in the built-in profile:
  • Review declarative security on value types.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System
Imports System.Security
Imports System.Security.Permissions

' Violation: structure should not be protected with System.Security.Permissions.SecurityAction.Demand
<System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name := "FullTrust")> _
Public Class Point

  Public X As Double
  Public Y As Double

  Sub New(ByVal x As Double, ByVal y As Double)
    Me.X = x
    Me.Y = y
  End Sub

End Class

' This is the correct implementation

Imports System

' Attribute has been removed
Public Class Point

  Public X As Double
  Public Y As Double

  Sub New(ByVal x As Double, ByVal y As Double)
    Me.X = x
    Me.Y = y
  End Sub

End Class

[C#]

// This code will trigger the rule violation

using System;
using System.Security;
using System.Security.Permissions;

// Violation: structure should not be protected with System.Security.Permissions.SecurityAction.Demand
[System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
public class Point
{

  public double X;
  public double Y;

  Point(double x, double y)
  {
    this.X = x;
    this.Y = y;
  }

}

// This is the correct implementation

using System;

// Attribute has been removed
public class Point
{

  public double X;
  public double Y;

  Point(double x, double y)
  {
    this.X = x;
    this.Y = y;
  }

}


Review deny and permit only usage

Rule ID: SE00016

Problem

A method contains a security check that specifies the System.Security.Permissions.SecurityAction.PermitOnly or System.Security.Permissions.SecurityAction.Deny security action.

Rule Description

The System.Security.Permissions.SecurityAction.PermitOnly action defines a white list containing only the permissions that should be granted, whereas the System.Security.Permissions.SecurityAction.Deny action defines a black list containing all the permissions that should not be granted. According to Microsoft .NET Framework guidelines, white lists are preferable to black lists, therefore System.Security.Permissions.SecurityAction.PermitOnly action is favorable over System.Security.Permissions.SecurityAction.Deny action. However, it is quite impactical to deny all the permissions that considered potentially dangerous and it is difficult to anticipate all the permissions that might be required.

Unreasoned using of System.Security.Permissions.SecurityAction.Deny and System.Security.Permissions.SecurityAction.PermitOnly security actions might alter the default behavior of the stack walk. Therefore, code that uses these security actions should be carefully evaluated by specialists in .NET Framework security.

This rule is similar to FxCop rule 'Review deny and permit only usage', CheckId CA2107

Correcting Violations

The rule provides the following auto-correct options:
  • Remove attribute(s) from the method.

Rule Instances

Instances of this rule in the built-in profile:
  • Review declarative security on value types.


Review suppress unmanaged code security usage

Rule ID: SE00008

Problem

A public or protected type or member is marked with the System.Security.SuppressUnmanagedCodeSecurity attribute.

Rule Description

According to Microsoft .NET Framework guidelines, you should avoid using the System.Security.SuppressUnmanagedCodeSecurity attribute at the type level in public or protected types as well as avoid applying the System.Security.SuppressUnmanagedCodeSecurity attribute to public and protected members.

By default, the .NET Framework makes a full Demand for methods that call unmanaged code through PInvoke or COM Interop services. If you mark the method (or its enclosing type) with the System.Security.SuppressUnmanagedCodeSecurity attribute, the .NET Framework makes a LinkDemand for the unmanaged code permission.

This rule is similar to FxCop rule 'Review suppress unmanaged code security usage', CheckId CA2118

Correcting Violations

The rule provides the following auto-correct options:
  • Remove System.Security.SuppressUnmanagedCodeSecurityAttribute attribute from a type or member

Rule Instances

Instances of this rule in the built-in profile:
  • Review suppress unmanaged code security usage.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System
Imports System.Security
Imports System.Security.Permissions

Namespace SystemLibrary

  Public Class SystemClass

    ' Violates the rule
    <SuppressUnmanagedCodeSecurityAttribute()> _
    Public Sub DoSomethingDangerous()

      ...

    End Sub

  End Class

End Namespace

' This is the correct implementation

Imports System
Imports System.Security
Imports System.Security.Permissions

Namespace SystemLibrary

  Public Class SystemClass

    ' Attribute has been removed
    Public Sub DoSomethingDangerous()

      ...

    End Sub

  End Class

End Namespace

[C#]

// This code will trigger the rule violation

using System;
using System.Security;
using System.Security.Permissions;

namespace SystemLibrary
{

  public class SystemClass
  {

    // Violates the rule
    [SuppressUnmanagedCodeSecurityAttribute()]
    public void DoSomethingDangerous()
    {

      ...

    }

  }

}

// This is the correct implementation

using System;
using System.Security;
using System.Security.Permissions;

namespace SystemLibrary
{

  public class SystemClass
  {

    // Attribute has been removed
    public void DoSomethingDangerous()
    {

      ...

    }

  }

}

Related Rules

Do not indirectly expose methods with link demands

Override link demands should be identical to base


Review visible event handlers

Rule ID: SE00015

Problem

An externally visible event-handling method was detected.

- OR -

An externally visible method was detected that is decorated with a security demand and exposing an EventArgs parameter.

Rule Description

According to Microsoft .NET Framework guidelines, private scope should be used for all event handlers.

The Demand security action checks whether an untrusted caller is in the call stack but cannot check whether the handler was added to the event source by untrusted code; also, the permission might be asserted at the time the event is raised. Therefore, malicious clients might attach your event handler to an event source so that your handler unknowingly executes dangerous code on behalf of the untrusted client.

This rule is similar to FxCop rule 'Review visible event handlers', CheckId CA2109

Correcting Violations

The rule provides the following auto-correct options:
  • Change method modifier to Private (private in C#).
  • Change method modifier to Friend (internal in C#).

Rule Instances

Instances of this rule in the built-in profile:
  • Review visible event handlers.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System

Public Class EventHandler

  ' Violation: event-handling method is public
  Public Sub HandleSomeEvent(sender As Object, e As EventArgs)

  ...

  End Sub

  ...

End Class

' This is the correct implementation

Imports System

Public Class EventHandler

  ' Correct implementation
  Private Sub HandleSomeEvent(sender As Object, e As EventArgs)

  ...

  End Sub

  ...

End Class

[C#]

// This code will trigger the rule violation

using System;

public class EventHandler
{

  // Violation: event-handling method is public
  public void HandleSomeEvent(object sender, EventArgs e)
  {

  ...

  }

  ...

}

' This is the correct implementation

using System;

public class EventHandler
{

  private void HandleSomeEvent(object sender, EventArgs e)
  {

  ...

  }

  ...

}


Seal methods that satisfy private interfaces

Rule ID: SE00004

Problem

Inheritable public type provides overridable method implementation of a Friend (internal in C#) interface.

Rule Description

A public type that implements a method of an internal interface using the Overridable (virtual in C#) modifier allows the method to be overridden by a derived type that is outside the assembly. Such scenario can create the following security vulnerability: If a second type in the defining assembly calls the method and expects an internal-only contract, behavior might be compromised when, instead, the overridden method in the outside assembly is executed.

This rule is similar to FxCop rule 'Seal methods that satisfy private interfaces', CheckId CA2119

Correcting Violations

The rule provides the following auto-correct options:
  • Change type modifier to NotInheritable (sealed in C#).
  • Change type modifier to Friend (internal in C#).
  • Implement the method without Overridable modifier (virtual in C#).

Rule Instances

Instances of this rule in the built-in profile:
  • Seal methods that satisfy private interfaces.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System

Namespace SecurityAccessLibrary

   Interface IValidateUser
      Function IsValidated() As Boolean
   End Interface

   Public Class BaseValidator
      Implements IValidateUser

      Overridable Function IsValidated() As Boolean _
         Implements IValidateUser.IsValidated
         Return False
      End Function

   End Class

   Public Class SecureDataProvider

      Private UserAccountInfo As SecureData

      Public Function GetSecureData(validator As BaseValidator) As SecureData

         If validator.IsValidated() = True Then
            Return UserAccountInfo
         Else
            Return Nothing
         End If

      End Sub

      ...

   End Class

End Namespace

' How the violator can exploit security vulnerability from the example above:

' external code
Imports System

Namespace SecurityAccessLibrary

   Public Class SecurityViolator
      Inherits BaseValidator

      Overrides Function IsValidated() As Boolean
         Return True
      End Function

      Shared Sub Main()
         Dim dataProvider As New SecureDataProvider()
         Console.WriteLine(dataProvider.GetSecureData(New SecurityViolator()))
      End Sub

   End Class

End Namespace

' This is the correct implementation

Imports System

Namespace SecurityAccessLibrary

   Interface IValidateUser
      Function IsValidated() As Boolean
   End Interface

   Public NotInheritable Class BaseValidator
      Implements IValidateUser

      Function IsValidated() As Boolean _
         Implements IValidateUser.IsValidated
         Return False
      End Function

   End Class

   Public Class SecureDataProvider

      Private UserAccountInfo As SecureData

      Public Function GetSecureData(validator As BaseValidator) As SecureData

         If validator.IsValidated() = True Then
            Return UserAccountInfo
         Else
            Return Nothing
         End If

      End Sub

      ...

   End Class

End Namespace

[C#]

// This code will trigger the rule violation

using System;

namespace SecurityAccessLibrary
{

   interface IValidateUser
   {
      bool IsValidated();
   }

   public class BaseValidator: IValidateUser
   {

      virtual bool IValidateUser.IsValidated()
      {
         return false;
      }

   }

   public class SecureDataProvider
   {

      private SecureData serAccountInfo;

      public SecureData GetSecureData(BaseValidator validator)
      {

         if (validator.IsValidated() == true)
         {
            return UserAccountInfo;
         }
         else
         {
            return null;
         }

      }

      ...

   }

}

// How the violator can exploit security vulnerability from the example above:

// external code
using System;

namespace SecurityAccessLibrary
{

   public class SecurityViolator: BaseValidator
   {

      override bool IsValidated()
      {
         return true;
      }

      static void Main()
      {
         SecureDataProvider dataProvider = new SecureDataProvider();
         Console.WriteLine(dataProvider.GetSecureData(new SecurityViolator()));
      }

   }

}

' This is the correct implementation

using System;

namespace SecurityAccessLibrary
{

   interface IValidateUser
   {
      bool IsValidated();
   }

   public sealed class BaseValidator: IValidateUser
   {

      virtual bool IValidateUser.IsValidated()
      {
         return false;
      }

   }

   public class SecureDataProvider
   {

      private SecureData serAccountInfo;

      public SecureData GetSecureData(BaseValidator validator)
      {

         if (validator.IsValidated() == true)
         {
            return UserAccountInfo;
         }
         else
         {
            return null;
         }

      }

      ...

   }

}


Secure asserts

Rule ID: SE00011

Problem

The method asserts a permission and no security checks are performed on the caller member.

Rule Description

Because calling Assert removes the requirement that all code in the call chain must be granted permission to access the specified resource, it can open up security issues if used incorrectly or inappropriately. If you assert a permission without performing any checks on the caller, the caller might be able to indirectly execute code using your permissions.

This rule is similar to FxCop rule 'Secure asserts', CheckId CA2106

Correcting Violations

The rule provides the following auto-correct options:
  • Add a security demand (System.Security.PermissionSet(SecurityAction.LinkDemand)) to the method or type.

Rule Instances

Instances of this rule in the built-in profile:
  • Secure asserts.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System
Imports System.Security
Imports System.Security.Permissions

Namespace SystemLibrary

  Public Class SystemClass

    Private DataFiles() As String

    ...

    <System.Security.SecurityCritical()> _
    Public Sub ProcessDataFile(fileName As String)
      Dim filePermission As New FileIOPermission(PermissionState.Unrestricted)
      filePermission.Assert()

      ...

    End Sub

    ' Violates the rule: no security checks are performed
    Public Sub ProcessAllDataFiles()

      For i = 0 To DataFiles.Length - 1

        ProcessDataFile(DataFiles(i))

      Next i

    End Sub

  End Class

End Namespace

' This is the correct implementation

Imports System
Imports System.Security
Imports System.Security.Permissions

Namespace SystemLibrary

  Public Class SystemClass

    Private DataFiles() As String

    ...

    <System.Security.SecurityCritical()> _
    Public Sub ProcessDataFile(fileName As String)
      Dim filePermission As New FileIOPermission(PermissionState.Unrestricted)
      filePermission.Assert()

      ...

    End Sub

    <System.Security.PermissionSet(SecurityAction.LinkDemand, Unrestricted := True)> _
    Public Sub ProcessAllDataFiles()

      For i = 0 To DataFiles.Length - 1

        ProcessDataFile(DataFiles(i))

      Next i

    End Sub

  End Class

End Namespace

[C#]

// This code will trigger the rule violation

using System;
using System.Security;
using System.Security.Permissions;

namespace SystemLibrary
{

  public class SystemClass
  {

    private string[] DataFiles;

    ...

    [System.Security.SecurityCritical()]
    public void ProcessDataFile(string fileName)
    {
      FileIOPermission filePermission = new FileIOPermission(PermissionState.Unrestricted);
      filePermission.Assert();

      ...

    }

    // Violates the rule: no security checks are performed
    public void ProcessAllDataFiles()
    {

      for (int i = 0; i < DataFiles.Length; i++)
      {

        ProcessDataFile(DataFiles[i]);

      }

    }

  }

}

' This is the correct implementation

using System;
using System.Security;
using System.Security.Permissions;

namespace SystemLibrary
{

  public class SystemClass
  {

    private string[] DataFiles;

    ...

    [System.Security.SecurityCritical()]
    public void ProcessDataFile(string fileName)
    {
      FileIOPermission filePermission = new FileIOPermission(PermissionState.Unrestricted);
      filePermission.Assert();

      ...

    }

    [System.Security.PermissionSet(SecurityAction.LinkDemand, Unrestricted = true)]
    public void ProcessAllDataFiles()
    {

      for (int i = 0; i < DataFiles.Length; i++)
      {

        ProcessDataFile(DataFiles[i]);

      }

    }

  }

}

Related Rules

Security transparent code should not assert


Secured types should not expose fields

Rule ID: SE00013

Problem

Externally visible type is protected with a System.Security.Permissions.SecurityAction.LinkDemand, has public field.

Rule Description

According to Microsoft .NET Framework guidelines, types protected with System.Security.Permissions.SecurityAction.LinkDemand security action should not expose public fields because this action protects only properties and methods. If an assembly without all necessary permissions can grab a reference to an instance of a type protected with a System.Security.Permissions.SecurityAction.LinkDemand security action, the assembly can freely access all the public fields.

This rule is similar to FxCop rule 'Secured types should not expose fields', CheckId CA2112

Correcting Violations

The rule provides the following auto-correct options:
  • Change field modifier to Private (private in C#).
  • Create public property from the field.

Rule Instances

Instances of this rule in the built-in profile:
  • Secured types should not expose fields.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System
Imports System.Security
Imports System.Security.Permissions

Namespace AccountsManagement

  <System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Name := "FullTrust")> _
  Public Class Account

    ' Violation: fields are not secured
    Public AccountNumber As String
    Public AccountValue As Decimal

    Sub New(ByVal accountNumber As String, ByVal accountValue As Decimal)
      Me.AccountNumber = accountNumber
      Me.AccountValue = accountValue
    End Sub

  End Class

End Namespace

' This is the correct implementation

Imports System
Imports System.Security
Imports System.Security.Permissions

Namespace AccountsManagement

  <System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Name := "FullTrust")> _
  Public Class Account

    Private _accountNumber As String
    Private _accountValue As Decimal

    Sub New(ByVal accountNumber As String, ByVal accountValue As Decimal)
      Me._accountNumber = accountNumber
      Me._accountValue = accountValue
    End Sub

    Public Property AccountNumber() As String
      Get

        Return _accountNumber

      End Get

      Set(ByVal value As String)

        _accountNumber = value

      End Set
    End Property

    Public Property AccountValue() As Decimal
      Get

        Return _accountValue

      End Get

      Set(ByVal value As Decimal)

        _accountValue = value

      End Set
    End Property

  End Class

End Namespace

[C#]

// This code will trigger the rule violation

using System;
using System.Security;
using System.Security.Permissions;

namespace AccountsManagement
{

  [System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Name = "FullTrust")]
  public class Account
  {

    // Violation: fields are not secured
    public string AccountNumber;
    public decimal AccountValue;

    Account(string accountNumber, decimal accountValue)
    {
      this.AccountNumber = accountNumber;
      this.AccountValue = accountValue;
    }

  }

}

// This is the correct implementation

using System;
using System.Security;
using System.Security.Permissions;

namespace AccountsManagement
{

  [System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Name = "FullTrust")]
  public class Account
  {

    private string _accountNumber;
    private decimal _accountValue;

    Account(string accountNumber, decimal accountValue)
    {
      this._accountNumber = accountNumber;
      this._accountValue = accountValue;
    }

    public string AccountNumber
    {
      get
      {

        return _accountNumber;

      }

      set
      {

        _accountNumber = value;

      }
    }

    public decimal AccountValue
    {
      get
      {

        return _accountValue;

      }

      set
      {

        _accountValue = value;

      }
    }

  }

}


Secure GetObjectData overrides

Rule ID: SE00005

Problem

Method GetObjectData declared in the type that implements the System.Runtime.Serialization.ISerializable interface is not protected by security permission System.Security.Permissions.SecurityPermissionAttribute.SerializationFormatter.

Rule Description

The GetObjectData method should be protected by demanding System.Security.Permissions.SecurityPermissionAttribute.SerializationFormatter permissions.

If the GetObjectData method is not protected by a security check for SerializationFormatter, it might result in a security risk because a malicious caller might serialize an instance obtained through a factory method exposed by a trusted assembly and then create a copy of it at a later time, or it might manufacture a stream of data containing arbitrary values and use it to create an invalid instance of the type.

This rule is similar to FxCop rule 'Secure GetObjectData overrides', CheckId CA2110

Correcting Violations

The rule provides the following auto-correct options:
  • Add attribute SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter=true) to GetObjectData method.

Rule Instances

Instances of this rule in the built-in profile:
  • Secure GetObjectData overrides.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System.Runtime.Serialization

Public Class PersonalData
    Implements ISerializable

    <SecurityPermission(SecurityAction.Demand, ControlPrincipal:=True)> _
    Sub New (ByVal name As String)
      ...
    End Sub

    ...

    ' Might result in a security risk!
    Public Sub GetObjectData(ByVal info As SerializationInfo, _
        ByVal context As StreamingContext) _
        Implements ISerializable.GetObjectData

        ...

    End Sub

End Class

' This is the correct implementation

Imports System.Runtime.Serialization

Public Class PersonalData
    Implements ISerializable

    <SecurityPermission(SecurityAction.Demand, ControlPrincipal:=True)> _
    Sub New (ByVal name As String)
        ...
    End Sub

    ...

    <SecurityPermission(SecurityAction.Demand, SerializationFormatter:=True)> _
    Public Sub GetObjectData(ByVal info As SerializationInfo, _
        ByVal context As StreamingContext) _
        Implements ISerializable.GetObjectData

          ...

    End Sub

End Class

[C#]

// This code will trigger the rule violation

using System.Runtime.Serialization;

public class PersonalData: ISerializable
{

    [SecurityPermission(SecurityAction.Demand, ControlPrincipal = true)]
    PersonalData (string name)
    {
      ...
    }

    ...

    // Might result in a security risk!
    public void ISerializable.GetObjectData(SerializationInfo info,
        StreamingContext context)
    {

        ...

    }

}

// This is the correct implementation

using System.Runtime.Serialization;

public class PersonalData: ISerializable
{

    [SecurityPermission(SecurityAction.Demand, ControlPrincipal = true)]
    PersonalData (string name)
    {
      ...
    }

    ...

    [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
    public void ISerializable.GetObjectData(SerializationInfo info,
        StreamingContext context)
    {

        ...

    }

}


Secure serialization constructors

Rule ID: SE00014

Problem

Type implements the System.Runtime.Serialization.ISerializable interface, has a serialization constructor with the System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext parameter signature. This constructor is not secured by a security check, but one or more of the regular constructors in the type is secured.

Rule Description

According to Microsoft .NET Framework guidelines, the constructor implied by the System.Runtime.Serialization.ISerializable interface should be protected with the same security actions used to protect other constructors.

Ignoring this guideline might result in a security risk because a malicious caller might serialize an instance obtained through a factory method exposed by a trusted assembly and then create a copy of it at a later time.

This rule is similar to FxCop rule 'Secure serialization constructors', CheckId CA2120

Correcting Violations

The rule provides the following auto-correct options:
  • Add required attribute(s) to the serialization constructor.

Rule Instances

Instances of this rule in the built-in profile:
  • Secure serialization constructors.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System
Imports System.Security
Imports System.Security.Permissions
Imports System.Runtime.Serialization

<Assembly: AllowPartiallyTrustedCallersAttribute()>

<Serializable()> _
Public Class Person
    Implements ISerializable

    Private _firstName As String
    Private _lastName As String

    Public ReadOnly Property FirstName() As String
        Get
            Return _firstName
        End Get
    End Property

    Public ReadOnly Property LastName() As String
        Get
            Return _lastName
        End Get
    End Property

    <SecurityPermission(SecurityAction.Demand, ControlPrincipal:=True)> _
    Public Sub New(ByVal firstName As String, ByVal lastName As String)
        Me._firstName = firstName
        Me._lastName = lastName
    End Sub

    ' Violation: Serialization constructor does not protected
    ' with the same security action as regular constructor
    Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
        _firstName = CType(info.GetValue("_firstName", GetType(String)), String)
        _lastName = CType(info.GetValue("_lastName", GetType(String)), String)
    End Sub

    Public Overridable Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext) _
        Implements ISerializable.GetObjectData

        info.AddValue("_firstName", _firstName)
        info.AddValue("_lastName", _lastName)
    End Sub

End Class

' This is the correct implementation

Imports System
Imports System.Security
Imports System.Security.Permissions
Imports System.Runtime.Serialization

<Assembly: AllowPartiallyTrustedCallersAttribute()>

<Serializable()> _
Public Class Person
    Implements ISerializable

    Private _firstName As String
    Private _lastName As String

    Public ReadOnly Property FirstName() As String
        Get
            Return _firstName
        End Get
    End Property

    Public ReadOnly Property LastName() As String
        Get
            Return _lastName
        End Get
    End Property

    <SecurityPermission(SecurityAction.Demand, ControlPrincipal:=True)> _
    Public Sub New(ByVal firstName As String, ByVal lastName As String)
        Me._firstName = firstName
        Me._lastName = lastName
    End Sub

    ' Serialization constructor demands same permissions as regular constructor
    <SecurityPermission(SecurityAction.Demand, ControlPrincipal:=True)> _
    Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
        _firstName = CType(info.GetValue("_firstName", GetType(String)), String)
        _lastName = CType(info.GetValue("_lastName", GetType(String)), String)
    End Sub

    Public Overridable Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext) _
        Implements ISerializable.GetObjectData

        info.AddValue("_firstName", _firstName)
        info.AddValue("_lastName", _lastName)
    End Sub

End Class

[C#]

// This code will trigger the rule violation

using System;
using System.Security;
using System.Security.Permissions;
using System.Runtime.Serialization;

[assembly:AllowPartiallyTrustedCallersAttribute()]

[Serializable()]
public class Person: ISerializable
{

    private string _firstName;
    private string _lastName;

    public string FirstName()
    {
        get
        {
            return _firstName;
        }
    }

    public string LastName()
    {
        get
        {
            return _lastName;
        }
    }

    [SecurityPermission(SecurityAction.Demand, ControlPrincipal = true)]
    public Person(string firstName, string lastName)
    {
        this._firstName = firstName;
        this._lastName = lastName;
    }

    // Violation: Serialization constructor does not protected
    // with the same security action as regular constructor
    protected Person(SerializationInfo info, StreamingContext context)
    {
        _firstName = (string)info.GetValue("_firstName", string.GetType());
        _lastName = (string)info.GetValue("_lastName", string.GetType());
    }

    public virtual void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
    {

        info.AddValue("_firstName", _firstName);
        info.AddValue("_lastName", _lastName);
    }

}

// This is the correct implementation

using System;
using System.Security;
using System.Security.Permissions;
using System.Runtime.Serialization;

[assembly:AllowPartiallyTrustedCallersAttribute()]

[Serializable()]
public class Person: ISerializable
{

    private string _firstName;
    private string _lastName;

    public string FirstName()
    {
        get
        {
            return _firstName;
        }
    }

    public string LastName()
    {
        get
        {
            return _lastName;
        }
    }

    [SecurityPermission(SecurityAction.Demand, ControlPrincipal = true)]
    public Person(string firstName, string lastName)
    {
        this._firstName = firstName;
        this._lastName = lastName;
    }

    ' Serialization constructor demands same permissions as regular constructor
    [SecurityPermission(SecurityAction.Demand, ControlPrincipal = true)]
    protected Person(SerializationInfo info, StreamingContext context)
    {
        _firstName = (string)info.GetValue("_firstName", string.GetType());
        _lastName = (string)info.GetValue("_lastName", string.GetType());
    }

    public virtual void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
    {

        info.AddValue("_firstName", _firstName);
        info.AddValue("_lastName", _lastName);
    }

}


Security transparent code should not assert

Rule ID: SE00010

Problem

Type or member is marked as SecurityTransparent or mixed transparent/critical is not granted sufficient permissions to assert permissions.

Rule Description

Any call to CodeAccessPermission.Assert from transparent code will cause a System.Security.SecurityException to be thrown at run time. Each transparent or mixed transparent/critical member which calls CodeAccessPermission.Assert should be marked with System.Security.SecurityCriticalAttribute attribute to avoid this issue.

This rule is similar to FxCop rule 'Security transparent code should not assert', CheckId CA2128

Correcting Violations

The rule provides the following auto-correct options:
  • Add System.Security.SecurityCriticalAttribute to the member

Rule Instances

Instances of this rule in the built-in profile:
  • Security transparent code should not assert.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System
Imports System.Security
Imports System.Security.Permissions

Namespace SystemLibrary

  Public Class SystemClass

    ' Violates the rule: code is security transparent, but calls assert
    Public Sub ProcessDataFiles()
      Dim filePermission As New FileIOPermission(PermissionState.Unrestricted)
      filePermission.Demand()
      filePermission.Assert()

      ...

    End Sub

  End Class

End Namespace

' This is the correct implementation

Imports System
Imports System.Security
Imports System.Security.Permissions

Namespace SystemLibrary

  Public Class SystemClass

    <System.Security.SecurityCritical()> _
    Public Sub ProcessDataFiles()
      Dim filePermission As New FileIOPermission(PermissionState.Unrestricted)
      filePermission.Demand()
      filePermission.Assert()

      ...

    End Sub

  End Class

End Namespace

[C#]

// This code will trigger the rule violation

using System;
using System.Security;
using System.Security.Permissions;

namespace SystemLibrary
{

  public class SystemClass
  {

    // Violates the rule: code is security transparent, but calls assert
    public void ProcessDataFiles()
    {
      FileIOPermission filePermission = new FileIOPermission(PermissionState.Unrestricted);
      filePermission.Demand();
      filePermission.Assert();

      ...

    }

  }

}

' This is the correct implementation

using System;
using System.Security;
using System.Security.Permissions;

namespace SystemLibrary
{

  public class SystemClass
  {

    [System.Security.SecurityCritical()]
    public void ProcessDataFiles()
    {
      FileIOPermission filePermission = new FileIOPermission(PermissionState.Unrestricted);
      filePermission.Demand();
      filePermission.Assert();

      ...

    }

  }

}

Related Rules

Secure asserts


Type link demands require inheritance demands

Rule ID: SE00012

Problem

Externally visible unsealed type is protected with a link demand, has an overridable method, and neither the type nor the method is protected with an inheritance demand.

Rule Description

According to Microsoft .NET Framework guidelines, a type level SecurityAction.InheritanceDemand action should be used for any nonsealed type that is marked with a SecurityAction.LinkDemand action if the type has one or more Overridable (virtual in C#) methods. Alternatively, SecurityAction.InheritanceDemand action should be used for each virtual method. (The SecurityAction.InheritanceDemand action has no effect on nonvirtual members.)

Protecting an overridable member with a SecurityAction.LinkDemand action isn't sufficient if the type isn't sealed because malicious code might wait until a trusted assembly invokes (and indirectly JIT-compiles) the protected method and then instantiate an object that derives from the secured type but overrides the virtual member.

This rule is similar to FxCop rule 'Type link demands require inheritance demands', CheckId CA2126

Correcting Violations

The rule provides the following auto-correct options:
  • Apply inheritance demands for the same permission as the type link demand to the type.
  • Apply inheritance demands for the same permission as the type link demand to the method.
  • Apply inheritance demands for the same permission as the method link demand to the type.
  • Apply inheritance demands for the same permission as the method link demand to the method.

Rule Instances

Instances of this rule in the built-in profile:
  • Type link demands require inheritance demands.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System
Imports System.Security
Imports System.Security.Permissions

Namespace DocumentsProcessing

  <FileIOPermission(SecurityAction.LinkDemand, Unrestricted := True)> _
  Public Class Document

    ' Violation: the method is not secured with an inheritance demand
    Public Overridable Function GetDocumentText() As String

      ...

    End Function

  End Class

End Namespace

' This is the correct implementation

Imports System
Imports System.Security
Imports System.Security.Permissions

Namespace DocumentsProcessing

  <FileIOPermission(SecurityAction.LinkDemand, Unrestricted := True)> _
  Public Class Document

    <FileIOPermission(SecurityAction.InheritanceDemand, Unrestricted := True)> _
    Public Overridable Function GetDocumentText() As String

      ...

    End Function

  End Class

End Namespace

[C#]

// This code will trigger the rule violation

using System;
using System.Security;
using System.Security.Permissions;

namespace DocumentsProcessing
{

  [FileIOPermission(SecurityAction.LinkDemand, Unrestricted = true)]
  public class Document
  {

    // Violation: the method is not secured with an inheritance demand
    public virtual string GetDocumentText()
    {

      ...

    }

  }

}

// This is the correct implementation

using System;
using System.Security;
using System.Security.Permissions;

namespace DocumentsProcessing
{

  [FileIOPermission(SecurityAction.LinkDemand, Unrestricted = true)]
  public class Document
  {

    [FileIOPermission(SecurityAction.InheritanceDemand, Unrestricted = true)]
    public virtual string GetDocumentText()
    {

      ...

    }

  }

}


Wrap vulnerable finally clauses in outer try

Rule ID: SE00021

Problem

An externally visible method contains a try-finally block. The finally block appears to reset security state and is not enclosed in a finally block.

Rule Description

According to Microsoft .NET Framework guidelines, always should be added a Catch (catch in C#) clause that traps all exceptions if the code in the Try (try in C#) block modifies any property of the current thread in a way that might be exploited by malicious code, for example, by impersonating a user with higher privileges.

A malicious exception filters presented in the call stack might execute before the Finally (finally in C#) block. An exception filter is a When clause implemented in Visual Basic.

This rule is similar to FxCop rule 'Wrap vulnerable finally clauses in outer try', CheckId CA2124

Correcting Violations

The rule provides the following auto-correct options:
  • Wrap the finally clause in an outer try block with an associated catch that simply rethrows.

Rule Instances

Instances of this rule in the built-in profile:
  • Wrap vulnerable finally clauses in outer try.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Public Class ServerTasks

  ' Violation: Try/Finally block is not wrapped.
  Public Shared Sub PerformTask()
    Try
      ' Impersonate a different, more privileged user here.
      Dim WindowsImpersonationContext impersonationContext = WindowsIdentity.Impersonate(privilegedUserToken)

      ...

    Finally
      ' Revert to original user.
      impersonationContext.Undo()

      ...

    End Try
  End Sub
End Class

' This is the correct implementation

Public Class ServerTasks

  Public Shared Sub PerformTask()
    Try
      Try
        ' Impersonate a different, more privileged user here.
        Dim WindowsImpersonationContext impersonationContext = WindowsIdentity.Impersonate(privilegedUserToken)

        ...

      Finally
        ' Revert to original user.
        impersonationContext.Undo()

        ...

      End Try
    Catch
      Throw
    End Try
  End Sub
End Class

[C#]

// This code will trigger the rule violation

public class ServerTasks
{

  // Violation: Try/Finally block is not wrapped.
  public static void PerformTask()
  {
    try
    {
      // Impersonate a different, more privileged user here.
      WindowsImpersonationContext impersonationContext = WindowsIdentity.Impersonate(privilegedUserToken);

      ...

    }
    finally
    {
      // Revert to original user.
      impersonationContext.Undo();
    }
  }
}

' This is the correct implementation

public class ServerTasks
{

  public static void PerformTask()
  {
    try
    {
      try
      {
        // Impersonate a different, more privileged user here.
        WindowsImpersonationContext impersonationContext = WindowsIdentity.Impersonate(privilegedUserToken);

        ...

      }
      finally
      {
        // Revert to original user.
        impersonationContext.Undo();

        ...

      }
    }
    catch
    {
      throw;
    }
  }
}


Spelling Rules

This section will guide you through the set of Spelling Rules.

Click on any of the links below to go directly to the corresponding rule.

Comments should be spelled correctly

Identifiers should be spelled correctly

XML comments should be spelled correctly


Comments should be spelled correctly

Rule ID: SP00002

Problem

Comment contains word, which is not recognized by the spelling checker library.

Rule Description

The rule was created to check spelling of comment strings. Spelling of each word in the comment is checked against the standard dictionary. If the word cannot be found in the standard dictionary the user has possibility to save it in the custom dictionary for further checks.

The English version of the spelling checker is only supported in present.

Correcting Violations

The rule provides the following auto-correct options:
  • Change unrecognized word to the word from dictionary.
  • Add unrecognized word to the custom dictionary.
  • Change unrecognized word in comment text to the specified text.

Rule Instances

Instances of this rule in the built-in profile:
  • Comments should be spelled correctly.


Identifiers should be spelled correctly

Rule ID: SP00001

Problem

Code element name contains word, which is not recognized by the spelling checker library.

Rule Description

The rule was created to check spelling of the identifiers. Each new word in the identifier starts from capital letter. Spelling of each word in the identifiers is checked against the standard dictionary. If the word cannot be found in the standard dictionary the user has possibility to save it in the custom dictionary for further checks.

The English version of the spelling checker is only supported in present.

Correcting Violations

The rule provides the following auto-correct options:
  • Rename code element and its references to correct word.
  • Add unrecognized word to the custom dictionary.
  • Rename code element and its references to the specified name.

Rule Instances

Instances of this rule in the built-in profile:
  • Identifiers should be spelled correctly.


XML comments should be spelled correctly

Rule ID: SP00003

Problem

XML comment contains word, which is not recognized by the spelling checker library.

Rule Description

The rule was created to check spelling of XML comment strings. Spelling of each word in the XML comment is checked against the standard dictionary. If the word cannot be found in the standard dictionary the user has possibility to save it in the custom dictionary for further checks.

The English version of the spelling checker is only supported in present.

Correcting Violations

The rule provides the following auto-correct options:
  • Change XML comment to the text with corrected words from dictionary.
  • Add unrecognized word to the custom dictionary.
  • Change unrecognized word in XML comment text to the specified text.

Rule Instances

Instances of this rule in the built-in profile:
  • XML comments should be spelled correctly.


Usage Rules

This section will guide you through the set of Usage Rules.

Click on any of the links below to go directly to the corresponding rule.

Always close SQL resources

Always close standard IO streams

Always provide names for threads

Avoid control statements with empty bodies

Avoid empty methods

Avoid System.Console 'Write()' or 'WriteLine()' statements

Avoid use of 'new' keyword for hiding methods

Call base class methods on ISerializable types

Close database connections in 'finally' block

Disposable fields should be disposed

Disposable types should declare finalizer

Dispose methods should call base class dispose

Do not explicitly call 'System.GC.Collect()' or 'System.GC.Collect(int)'

Do not mark serviced components with WebMethod

Do not prefix calls with 'base' ('MyBase' in Visual Basic) unless local implementation exists

Finalizers should be protected

Finalizers should call base class finalizer

Implement ISerializable correctly

Implement ISerializable for serializable classes that expose events

Implement Serialization Constructor

Implement serialization methods correctly

Include instance fields in the serialization/deserialization process

Lock both when either set or get is locked for a property

Mark all non-serializable fields with "NonSerialized" attribute

Mark derived types with specified attribute

Calls to local members should be prefixed with the 'this.' ('Me.' in Visual Basic)

Provide 'default:' for each 'switch' statement

Provide deserialization methods for optional fields

Remove unused parameters


Always close SQL resources

Rule ID: US00030

Problem

Method opens System.Data.SqlClient.SqlConnection but Close or Dispose is not called

- OR -

Method performs call to ExecuteReader of System.Data.SqlClient.SqlCommand class but Close or Dispose of returned System.Data.SqlClient.SqlDataReader is not called.

Rule Description

This rule detects situations when a resource leak is created by having a call to a method that opens an SqlConnection and not closing it with an appropriate method. The following is the list of methods considered for opening and closing the resources.

Resouce openers:
  • System.Data.SqlClient.SqlConnection.Open
  • System.Data.SqlClient.SqlCommand.ExecuteReader
Resource closers:
  • System.Data.SqlClient.SqlConnection.Close
  • System.Data.SqlClient.SqlConnection.Dispose
  • System.ComponentModel.Component.Dispose
  • System.Data.SqlClient.SqlDataReader.Close
  • System.Data.SqlClient.SqlDataReader.Dispose
  • System.IDisposable.Dispose

Correcting Violations

The rule provides the following auto-correct options:
  • Add method call that closes SQL resource.

Rule Instances

Instances of this rule in the built-in profile:
  • Always close SQL resources.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

    ' This code will trigger the rule violation
    Public Sub Foo0()
      ' Violates the rule
      Dim connection As New SqlConnection()
      connection.Open()
    End Sub

    Public Sub Foo1()
      ' Violates the rule
      Dim command As New SqlCommand()
      Dim reader As SqlDataReader = command.ExecuteReader()
    End Sub

    ' This is the correct implementation
    Public Class SomeClass
      Private _listConnections As List(Of SqlConnection)
      Private _listReader As List(Of SqlDataReader)

      Public Sub New()
        _listConnections = New List(Of SqlConnection)()
        _listReader = New List(Of SqlDataReader)()
      End Sub

      Public Sub Bar0()
        Using connection As New SqlConnection()
          connection.Open()
        End Using
      End Sub

      Public Sub Bar1()
        Dim connection As New SqlConnection()
        connection.Open()
        ' some code
        connection.Close()
      End Sub

      Public Sub Bar2()
        Dim command As New SqlCommand()
        Dim reader As SqlDataReader = command.ExecuteReader()
        reader.Dispose()
      End Sub

      Public Sub Bar3()
        Dim command As New SqlCommand()

        Using reader As SqlDataReader = command.ExecuteReader()
          ' some code
        End Using
      End Sub

      Public Sub Bar4()
      ' Enabled: Assume third-party methods could store resource references
        Dim connection As New SqlConnection()
        connection.Open()
        _lstCon.Add(connection)
        ' can be closed in other code
      End Sub

      Public Sub Bar5()
      ' Enabled: Assume third-party methods could store resource references
        Dim command As New SqlCommand()
        Dim reader As SqlDataReader = command.ExecuteReader()
        _lstReader.Add(reader)
        ' can be closed in other code
      End Sub
    End Class

[C#]

    // This code will trigger the rule violation
    public void Foo0()
    {
      // Violates the rule
      SqlConnection connection = new SqlConnection();
      connection.Open();
    }
    public void Foo1()
    {
      // Violates the rule
      SqlCommand command = new SqlCommand();
      SqlDataReader reader = command.ExecuteReader();
    }

    // This is the correct implementation
    public class SomeClass
    {
        private List _listConnections;
        private List _listReader;

        public SomeClass()
        {
          _listConnections = new List();
          _listReader = new List();
        }

        public void Bar0()
        {
          using (SqlConnection connection = new SqlConnection())
          {
            connection.Open();
          }
        }

        public void Bar1()
        {
          SqlConnection connection = new SqlConnection();
          connection.Open();
          // some code
          connection.Close();
        }

        public void Bar2()
        {
          SqlCommand command = new SqlCommand();
          SqlDataReader reader = command.ExecuteReader();
          reader.Dispose();
        }

        public void Bar3()
        {
          SqlCommand command = new SqlCommand();
          using (SqlDataReader reader = command.ExecuteReader())
          {
            // some code
          }
        }

        public void Bar4() // Enabled: Assume third-party methods could store resource references
        {
          SqlConnection connection = new SqlConnection();
          connection.Open();
          _lstCon.Add(connection); // can be closed in other code
        }

        public void Bar5() // Enabled: Assume third-party methods could store resource references
        {
          SqlCommand command = new SqlCommand();
          SqlDataReader reader = command.ExecuteReader();
          _lstReader.Add(reader); // can be closed in other code
        }
      }

Related Rules

Always close standard IO streams

Close data base connections in 'finally' block


Always close standard IO streams

Rule ID: US00029

Problem

Method opens standard IO Stream but not closes or disposes it.

- OR -

Method opens standard Reader but not closes or disposes it.

- OR -

Method opens standard Witer but not closes or disposes it.

- OR -

Method opens standard File but not closes or disposes it.

- OR -

Method opens standard Security.Cryptography.CryptoStream but not closes or disposes it.

Rule Description

This rule detects situations when a resource leak is created by having a call to a method that opens an I/O Stream and not closing it with an appropriate method. The following is the list of classes that this rule handles while detecting resources leaks.
  • System.CodeDom.Compiler.IndentedTextWriter
  • System.IO.BinaryReader
  • System.IO.BinaryWriter
  • System.IO.BufferedStream
  • System.IO.FileInfo (factory for producing wrappers)
  • System.IO.File (factory for producing wrappers)
  • System.IO.StreamReader
  • System.IO.StreamWriter
  • System.Resources.ResourceReader
  • System.Resources.ResourceSet
  • System.Resources.ResourceWriter
  • System.Resources.ResXResourceReader
  • System.Resources.ResXResourceWriter
  • System.Xml.XmlTextReader
  • System.Xml.XmlTextWriter
  • System.Xml.XmlValidatingReader
  • Security.Cryptography.CryptoStream
Each of these classes supports methods such as Create, Open, OpenRead, etc. which will be considered to open the resource. A corresponding call to a clsoing method such as Close or Dispose is expected to be present along every execution path before the variable that holds a reference to the opened resource goes out of scope.

Correcting Violations

The rule provides the following auto-correct options:
  • Add method call that closes IO stream.

Rule Instances

Instances of this rule in the built-in profile:
  • Always close standard IO streams.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

    ' This code will trigger the rule violation
    Public Sub Foo0()
      ' Violates the rule
      Dim sw As New StreamWriter()
      ' some code
    End Sub

    Public Sub Foo1()
      ' Violates the rule
      Dim file As New File()
      file.Open()
      ' some code
    End Sub

    ' This is the correct implementation

    Public Class SomeClass
      Private _listWriter As List(Of StreamWriter)

      Public Sub New()
        _listWriter = New List(Of StreamWriter)()
      End Sub

      Public Sub Bar0()
        Using sw As New StreamWriter()
          ' some code
        End Using
      End Sub

      Public Sub Bar1()
        Dim file As New File()
        file.Open()
        ' some code
        file.Close()
      End Sub

      Public Sub Bar2()
        Dim file As New File()
        ' file is not opened
      End Sub

      Public Sub Bar3()
      ' Enabled: Assume third-party methods could store resource references
        Dim sw As New StreamWriter()
        _swList.Add(sw)
        ' can be closed in other code
        ' some code
      End Sub
    End Class

[C#]

    // This code will trigger the rule violation
    public void Foo0()
    {
      // Violates the rule
      StreamWriter sw = new StreamWriter();
      // some code
    }
    public void Foo1()
    {
      // Violates the rule
      File file = new File();
      file.Open();
      // some code
    }

    // This is the correct implementation
    public class SomeClass
    {
        private List _listWriter;

        public SomeClass()
        {
          _listWriter = new List();
        }

        public void Bar0()
        {
          using(StreamWriter sw = new StreamWriter())
          {
            // some code
          }
        }

        public void Bar1()
        {
          File file = new File();
          file.Open();
          // some code
          file.Close();
        }

        public void Bar2()
        {
          File file = new File(); // file is not opened
        }

        public void Bar3() // Enabled: Assume third-party methods could store resource references
        {
          StreamWriter sw = new StreamWriter();
          _swList.Add(sw); // can be closed in other code
          // some code
        }
      }

Related Rules

Always close SQL resources

Close data base connections in 'finally' block


Always provide names for threads

Rule ID: US00027

Problem

It is very difficult to work with threads without names during debugging.

Rule Description

This reports a violation whenever the call to the constructor of Thread is not immediately followed by an assignment to the Name property of the threads.

Correcting Violations

The rule provides the following auto-correct options depending from detected violation:
  • Set a thread name in the method manually

Rule Instances

Instances of this rule in the built-in profile:
  • Always provide names for threads.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation
  Public Sub Foo0()
    ' Violation: no name is provided for the thread
    Dim th As New Thread()
    ' some code
  End Sub

  Public Sub Foo1()
    ' Violation: Name is provided but not immediately after the Thread constructor
    Dim th As New Thread()
    ' some code
    th.Name = "thread name"
  End Sub

' This is the correct implementation
  Public Sub Bar()
    Dim th As New Thread()
    th.Name = "Worker thread!"
  End Sub

[C#]

// This code will trigger the rule violation
  public void Foo0()
  {
    // Violation: no name is provided for the thread
    Thread th = new Thread();
    // some code
  }

  public void Foo1()
  {
    // Violation: Name is provided but not immediately after the Thread constructor
    Thread th = new Thread();
    // some code
    th.Name = "thread name";
  }

// This is the correct implementation
  public void Bar()
  {
    Thread th = new Thread();
    th.Name = "Worker thread!";
  }

Related Rules

© 2002-2019 SubMain. All rights reserved.
Designated trademarks and brands are the property of their respective owners.


Avoid control statements with empty bodies

Rule ID: US00025

Problem

A conditional statement that is immediately followed by a closing statement (e.g. a semicolon) is usually a typo.

- OR -

Missing out or improper handling important conditions that can even cause security holes.

Rule Description

This rule identifies if, for, while, do while, else and switch statements with empty bodies. An error is reported for each occurrence.

Correcting Violations

The rule provides the following auto-correct options:
  • Fill the empty body control statement manually.

Rule Instances

Instances of this rule in the built-in profile:
  • Avoid control statements with empty bodies.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

    ' This code will trigger the rule violation
    Public Class SomeClassWithViolations
      Public Sub Foo_If()
        Dim a As Integer = 0
        If a < 4 Then
        End If

        ' some code
      End Sub

      Public Sub Foo_If2()
        Dim a As Integer = 0
        If a > 4 Then
        End If

        ' some code
      End Sub

      Public Sub Foo_Switch()
        Dim a As Integer = 0
        Select Case a
        End Select

        ' some code
      End Sub

      Public Sub Foo_Else()
        Dim a As Integer = 0
        If a > 5 Then
          ' some code
        Else
        End If
      End Sub

      Public Sub Foo_For()
        For value As Integer = 0 To 5
        Next

        ' some code
      End Sub

      Public Sub Foo_While()
        Dim a As Integer = 0
        While a < 5
        End While

        ' some code
      End Sub

      Public Sub Foo_Do()
        Dim a As Integer = 0
        Do
        Loop While a < 5

        ' some code
      End Sub
    End Class

' This is the correct implementation
    Public Class SomeClass
      Public Sub Foo_If()
        Dim a As int = 0
        If a < 4 Then
          ' some code
        End If
      End Sub

      Public Sub Foo_Switch()
        Dim a As Integer = 0
        Select Case a
          Case 3
          ' some code
        End Select
      End Sub

      Public Sub Foo_Else()
        Dim a As Integer = 0
        If a > 5 Then
          ' some code
        Else
          ' some code
        End If
      End Sub

      Public Sub Foo_For()
        For value As Integer = 0 To 5
          ' some code
        Next
      End Sub

      Public Sub Foo_While()
        Dim a As Integer = 0
        While a < 5
          a += 1
        End While
      End Sub

      Public Sub Foo_Do()
        Dim a As Integer = 0
        Do
          a += 1
        Loop While a < 5
      End Sub
    End Class

[C#]

// This code will trigger the rule violation
    public class SomeClassWithViolations
    {
      public void Foo_If()
      {
        int a= 0;
        if (a < 4)
          ;
        // some code
      }

      public void Foo_If2()
      {
        int a = 0;
        if (a > 4)
        {
        }

        // some code
      }

      public void Foo_Switch()
      {
        int a = 0;
        switch (a)
        {
        }

        // some code
      }

      public void Foo_Else()
      {
        int a = 0;
        if (a > 5)
        {
          // some code
        }
        else
        {
        }
      }

      public void Foo_For()
      {
        for (; ; )
        {
        }

        // some code
      }

      public void Foo_While()
      {
        int a = 0;
        while (a < 5)
        {
        }

        // some code
      }

      public void Foo_Do()
      {
        int a = 0;
        do
        {
        }
        while (a < 5);

        // some code
      }
    }

// This is the correct implementation
    public class SomeClass
    {
      public void Foo_If()
      {
        int a = 0;
        if (a < 4)
        {
          // some code
        }
      }

      public void Foo_Switch()
      {
        int a = 0;
        switch (a)
        {
          case 3:
            {
              // some code
              break;
            }
        }
      }

      public void Foo_Else()
      {
        int a = 0;
        if (a > 5)
        {
          // some code
        }
        else
        {
          // some code
        }
      }

      public void Foo_For()
      {
        for (; ; )
        {
          // some code
        }
      }

      public void Foo_While()
      {
        int a = 0;
        while (a < 5)
        {
          a++;
        }
      }

      public void Foo_Do()
      {
        int a = 0;
        do
        {
          a++;
        }
        while (a < 5);
      }
    }

Related Rules

Avoid empty methods.

Provide 'default:' for each 'switch' statement.


Avoid empty methods

Rule ID: US00020

Problem

Placeholder empty methods are not filled with a code which can lead to bugs or errors in application behaviour.

Rule Description

This rule identifies code that declares a method with an empty body. An error is reported for each occurrence.

This rule does not apply for abstract, virtual, or override methods to reserve the use of polymorphism.

Prevents missing out implementation of important methods such as logging methods or methods that need to take important actions under abnormal cirucmstances, which are important for security.

During development empty methods often get introduced as place-holders for something to be implemented at a later time. For example, we could have a method that is supposed to log some error condition, but the developer decided to work on the normal cases first. These methods should get filled in before the product is released. To avoid oversights of this nature, it is best to ensure that there are no empty methods unless explicitly allowed (possibly via suppression of the violation).

Correcting Violations

The rule provides the following auto-correct options:
  • Comment out the empty method.
  • Remove the empty method.

Rule Instances

Instances of this rule in the built-in profile:
  • Avoid empty methods.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation
    Public Class SomeClass
      ' Violates the rule
      Public Sub EmptyMethod()
      End Sub
    End Class

' This is the correct implementation
    Public Class BaseClass
      ' Overridable method is an exception to the rule
      Public Overridable Sub VirtualMethod_NoError()
      End Sub
    End Class

    Public MustInherit Class Tests
      Inherits BaseTest
      Public Sub NotEmptyMethod()
        ' some code
      End Sub
      ' MustOverride method is an exception to the rule
      Public MustOverride Sub EmptyMethod_NoError()
    End Class

[C#]

// This code will trigger the rule violation
    public class SomeClass
    {
      // Violates the rule
      public void EmptyMethod()
      {
      }
    }

// This is the correct implementation
    public class BaseClass
    {
      // Virtual method is an exception to the rule
      public virtual void VirtualMethod_NoError()
      {
      }
    }

    public abstract class Tests: BaseTest
    {
      public void NotEmptyMethod()
      {
        // some code
      }

      // Abstract method is an exception to the rule
      public abstract void EmptyMethod_NoError();
    }

Related Rules

Avoid control statements with empty bodies


Avoid System.Console 'Write()' or 'WriteLine()' statements

Rule ID: US00021

Problem

Disallows the use of System.Console.WriteLine() or System.Console.Write() for debugging purposes.

Rule Description

All debugging statements should be cleaned up before the product is released.

Correcting Violations

The rule provides the following auto-correct options:
  • Comment out the method call.

Rule Instances

Instances of this rule in the built-in profile:
  • Avoid System.Console 'Write()' or 'WriteLine()' statements

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation
    Public Sub Foo0()
      ' Violates the rule
      Console.WriteLine("Some debug information")
    End Sub

' This is the correct implementation
    Public Sub Main()
    ' Main is an exception to the rule
      Console.WriteLine("Some debug information")
    End Sub

    Public Sub Foo0()
      ' Comment out the violation block
      ' Console.WriteLine("Some debug information");
    End Sub

[C#]

// This code will trigger the rule violation
    public void Foo0()
    {
      // Violates the rule
      Console.WriteLine("Some debug information");
    }

// This is the correct implementation
    public void Main()
    {
      // Main is an exception to the rule
      Console.WriteLine("Some debug information");
    }

    public void Foo0()
    {
      // Comment out the violation block
      // Console.WriteLine("Some debug information");
    }

Related Rules

© 2002-2019 SubMain. All rights reserved.
Designated trademarks and brands are the property of their respective owners.


Avoid use of new keyword for hiding methods

Rule ID: US00028

Problem

C# lets you redefine a method in the base class using the keyword new which can confuse the users of the class

Rule Description

This rule triggers on each use of the new key word when it is used to hide a method in the base class.

Correcting Violations

The rule provides the following auto-correct options:
  • Remove the new keyword from the method manually.

Rule Instances

Instances of this rule in the built-in profile:
  • Avoid use of new keyword for hiding methods

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation
    Public Class Parent
      Public Function foo() As Integer
        Return 100
      End Function
    End Class

    Public Class Child
      Inherits Parent
      ' Violates the rule
      Public Shadows Function foo() As Integer
        Return 200
      End Function
    End Class

' This is the correct implementation
    Public Class Parent
      Public Overridable Function foo() As Integer
        Return 100
      End Function
    End Class

    Public Class Child
      Inherits Parent
      Public Overrides Function foo() As Integer
        Return 200
      End Function
    End Class

[C#]

// This code will trigger the rule violation
    public class Parent
    {
      public int foo()
      {
        return 100;
      }
    }

    public class Child : Parent
    {
      // Violates the rule
      public new int foo()
      {
        return 200;
      }
    }

// This is the correct implementation
    public class Parent
    {
      public virtual int foo()
      {
        return 100;
      }
    }

    public class Child : Parent
    {
      public override int foo()
      {
        return 200;
      }
    }

Related Rules

© 2002-2019 SubMain. All rights reserved.
Designated trademarks and brands are the property of their respective owners.


Call base class methods on ISerializable types

Rule ID: US00001

Problem

Type derives from a type that implements the System.Runtime.Serialization.ISerializable interface, implements System.Runtime.Serialization.ISerializable.GetObjectData method but does not call the GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) method of the base type.

Or

Type derives from a type that implements the System.Runtime.Serialization.ISerializable interface, implements the serialization constructor with the (System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) parameter signature, but does not call the serialization constructor of the base type.

Rule Description

Implementing System.Runtime.Serialization.ISerializable involves implementing the GetObjectData method and a special constructor that is used when the object is deserialized. Derived classes should call the GetObjectData method and serialization constructor of the base object if the latter implements System.Runtime.Serialization.ISerializable. In opposite case, the type will not be serialized and de-serialized correctly. But if the derived type does not introduces any new fields, then the type does not need to implement the GetObjectData method and special serialization constructor. It does not need to call the base type equivalents as well.

This rule is similar to FxCop rule 'Call base class methods on ISerializable types', CheckId CA2236

Correcting Violations

The rule provides the following auto-correct options:
  • Find method System.Runtime.Serialization.ISerializable.GetObjectData and insert a GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) call at the beginning or at the end of the method.
  • Find constructor with the (System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) parameter signature and insert a call of the base type serialization constructor at the beginning of the constructor.

Rule Instances

Instances of this rule in the built-in profile:
  • Call base class methods on ISerializable types.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

Imports System.Runtime.Serialization

' The following base type implements ISerializable interface
<Serializable()> _
Public Class Person
    Implements ISerializable

    Private _firstName As String
    Private _lastName As String

    Public ReadOnly Property FirstName() As String
        Get
            Return _firstName
        End Get
    End Property

    Public ReadOnly Property LastName() As String
        Get
            Return _lastName
        End Get
    End Property

    Public Sub New(ByVal firstName As String, ByVal lastName As String)
        Me._firstName = firstName
        Me._lastName = lastName
    End Sub

    ' Special serialization constructor
    Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
        _firstName = CType(info.GetValue("_firstName", GetType(String)), String)
        _lastName = CType(info.GetValue("_lastName", GetType(String)), String)
    End Sub

    Public Overridable Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext) _
        Implements ISerializable.GetObjectData

        info.AddValue("_firstName", _firstName)
        info.AddValue("_lastName", _lastName)

    End Sub

End Class

' This code will trigger the rule violation

<Serializable> _
Public Class Employee
    Inherits Person

    Private _salary As Decimal

    Public ReadOnly Property Salary() As Decimal
        Get
            Return _salary
        End Get
    End Property

    Public Sub New(ByVal firstName As String, ByVal lastName As String, ByVal salary As Decimal)

        MyBase.New(firstName, lastName)
        Me._salary = salary

    End Sub

    Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
        _salary = CType(info.GetValue("_salary", GetType(Decimal)), Decimal)
    End Sub

    Public Overrides Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext)
        info.AddValue("_salary", _salary)
    End Sub

End Class

' This is the correct implementation

<Serializable> _
Public Class Employee
    Inherits Person

    Private _salary As Decimal

    Public ReadOnly Property Salary() As Decimal
        Get
            Return _salary
        End Get
    End Property

    Public Sub New(ByVal firstName As String, ByVal lastName As String, ByVal salary As Decimal)

        MyBase.New(firstName, lastName)
        Me._salary = salary

    End Sub

    Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
        MyBase.New(info, context)
        _salary = CType(info.GetValue("_salary", GetType(Decimal)), Decimal)
    End Sub

    Public Overrides Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext)
        MyBase.GetObjectData(info, context)
        info.AddValue("_salary", _salary)
    End Sub

End Class

[C#]

using System.Runtime.Serialization;

// The following base type implements ISerializable interface
[Serializable()]
public class Person: ISerializable
{

    private string _firstName;
    private string _lastName;

    public string FirstName
    {
        get
        {
            return _firstName;
        }
    }

    public string LastName
    {
        get
        {
            return _lastName;
        }
    }

    public Person(string firstName, string lastName)
    {
        this._firstName = firstName;
        this._lastName = lastName;
    }

    // Special serialization constructor
    protected Person(SerializationInfo info, StreamingContext context)
    {
        _firstName = (string)info.GetValue("_firstName", string.GetType());
        _lastName = (string)info.GetValue("_lastName", string.GetType());
    }

    public virtual void ISerializable.GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext)
    {

        info.AddValue("_firstName", _firstName);
        info.AddValue("_lastName", _lastName);

    }

}

// This code will trigger the rule violation

[Serializable]
public class Employee: Person
{

    private decimal _salary;

    public decimal Salary
    {
        get
        {
            return _salary;
        }
    }

    public Employee(string firstName, string lastName, decimal salary):
      base(firstName, lastName)
    {

        this._salary = salary;

    }

    protected Employee(SerializationInfo info, StreamingContext context)
    {
        _salary = (decimal)(info.GetValue("_salary", decimal.GetType());
    }

    public override void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("_salary", _salary);
    }

}

' This is the correct implementation

[Serializable]
public class Employee: Person
{

    private decimal _salary;

    public decimal Salary
    {
        get
        {
            return _salary;
        }
    }

    public Employee(string firstName, string lastName, decimal salary):
      base(firstName, lastName)
    {

        this._salary = salary;

    }

    protected Employee(SerializationInfo info, StreamingContext context):
      base(info, context)
    {
        _salary = (decimal)(info.GetValue("_salary", decimal.GetType());
    }

    public override void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        base.GetObjectData(info, context);
        info.AddValue("_salary", _salary);
    }

}

Related Rules

Implement ISerializable correctly

Implement ISerializable for serializable classes that expose events

Implement Serialization Constructor

Implement serialization methods correctly

Include instance fields in the serialization/deserialization process

Mark all non-serializable fields with "NonSerialized" attribute

Provide deserialization methods for optional fields


Calls to local members should be prefixed with the 'this.' ('Me.' in Visual Basic)

Rule ID: US00016

Problem

The call to the method does not begin with the this. (Me. in Visual Basic) prefix.

Rule Description

The call to the method must begin with the this. (Me. in Visual Basic) prefix to indicate that the item is a member of class. This rule makes the code clearer as it indicates the scope of the method.

Correcting Violations

The rule provides the following auto-correct options:
  • Add this. (Me. in Visual Basic) prefix to the method call.

Rule Instances

Instances of this rule in the built-in profile:
  • Calls to local members should be prefixed with the 'this.' ('Me.' in Visual Basic).

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Public Class SampleClass

  Private Sub DoSomething(ByVal param As Integer)

    ...

  End Sub

  Public Sub DoSomethingElse()

    ' Method call is not prefixed
    DoSomething(1)
    ...

  End Sub

End Class

' This is the correct implementation

Public Class SampleClass

  Private Sub DoSomething(ByVal param As Integer)

    ...

  End Sub

  Public Sub DoSomethingElse()

    Me.DoSomething(1)
    ...

  End Sub

End Class

[C#]

// This code will trigger the rule violation

public class SampleClass
{

  private void DoSomething(int param)
  {

    ...

  }

  public void DoSomethingElse()
  {

    // Violation: Method call is not prefixed
    DoSomething(1);
    ...

  }

}

// This is the correct implementation

public class SampleClass
{

  private void DoSomething(int param)
  {

    ...

  }

  public void DoSomethingElse()
  {

    this.DoSomething(1);
    ...

  }

}


Close data base connections in 'finally' block

Rule ID: US00024

Problem

Close and release database connection under all circumstances.

Rule Description

This rule triggers whenever a call to the closing method from given connection type is not present in a finally block. If the resource is used via a using statement the rule will not trigger.

Correcting Violations

The rule provides the following auto-correct options:
  • Add finally block and add the method call that closes database connection.

Rule Instances

Instances of this rule in the built-in profile:
  • Close data base connections in 'finally' block.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

    ' This code will trigger the rule violation
    Imports System.Data.SqlClient
    Namespace myApplication
      Class MyClientApplication
        Public Sub myMethod(connection As SqlConnection)
          Try
              ' do something
            connection.Open()
              ' handle error
          Catch exc As Exception
          End Try
          ' Violates the rule
          connection.Close()
        End Sub
      End Class
    End Namespace

    ' This is the correct implementation
    Imports System.Data.SqlClient
    Namespace myApplication
      Class MyClientApplication
        Public Sub myMethod(connection As SqlConnection)
          Try
              ' do something
            connection.Open()
              ' handle error
          Catch exc As Exception
          Finally
            connection.Close()  ' Fix
          End Try
        End Sub
      End Class
    End Namespace

[C#]

    // This code will trigger the rule violation
    using System.Data.SqlClient;
    namespace myApplication
    {
      class MyClientApplication
      {
        public void myMethod(SqlConnection connection)
        {
          try
          {
            connection.Open();
            // do something
          }
          catch(Exception exc)
          {
            // handle error
          }

          // Violates the rule
          connection.Close();
        }
      }
    }

    // This is the correct implementation
    using System.Data.SqlClient;
    namespace myApplication
    {
      class MyClientApplication
      {
        public void myMethod(SqlConnection connection)
        {
          try
          {
            connection.Open();
            // do something
          }
          catch(Exception exc)
          {
            // handle error
          }
          finally
          {
            connection.Close(); // Fix
          }
        }
      }
    }

Related Rules

Always close standard IO streams

Always close SQL resources


Disposable fields should be disposed

Rule ID: US00002

Problem

A type implements System.IDisposable interface and declares field, which is of type that implements System.IDisposable as well, but the Dispose method of the declaring type does not call the Dispose method of this field.

Rule Description

The Dispose method of the type, which implements System.IDisposable interface, should release all the resources that it owns. The Dispose method of the type should call the Dispose method for each field that hold a reference to a disposable object.

This rule is similar to FxCop rule 'Disposable fields should be disposed', CheckId CA2213

Correcting Violations

The rule provides the following auto-correct options:
  • Find method Dispose(disposing) and insert a Dispose() call at the end of the dispose snippet in the code path where disposing is True.

Rule Instances

Instances of this rule in the built-in profile:
  • Disposable fields should be disposed.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' The following code shows type
' that implements System.IDisposable interface
Public Class DisposableType
  Implements IDisposable

  Protected disposed As Boolean = False

  ' This method disposes the base object's resources.
  Protected Overridable Sub Dispose(ByVal disposing As Boolean)
    If Not Me.disposed Then
      If disposing Then

        ...

      End If

      Me.disposed = True

    End If
  End Sub

  Public Sub Dispose() Implements IDisposable.Dispose
    Dispose(True)
    GC.SuppressFinalize(Me)
  End Sub

  Protected Overrides Sub Finalize()
    Try
      Dispose(False)
    Catch

      ...

    Finally
      MyBase.Finalize()
    End Try

  End Sub

End Class

' This code will trigger the rule violation

Public Class AnotherDisposableType
  Implements IDisposable

  Private _disposableField As New DisposableType()

  Protected disposed As Boolean = False

  ' Violation: Disposable field _disposableField is not disposed
  Protected Overridable Sub Dispose(ByVal disposing As Boolean)
    If Not Me.disposed Then
      If disposing Then

        ...

      End If

      Me.disposed = True

    End If
  End Sub

  Public Sub Dispose() Implements IDisposable.Dispose
    Dispose(True)
    GC.SuppressFinalize(Me)
  End Sub

  Protected Overrides Sub Finalize()
    Try
      Dispose(False)
    Catch

      ...

    Finally
      MyBase.Finalize()
    End Try

  End Sub

End Class

' This is the correct implementation

Public Class AnotherDisposableType
  Implements IDisposable

  Private _disposableField As New DisposableType()

  Protected disposed As Boolean = False

  ' This method disposes the base object's resources.
  Protected Overridable Sub Dispose(ByVal disposing As Boolean)
    If Not Me.disposed Then
      If disposing Then

        ...

        _disposableField.Dispose(disposing)

      End If

      Me.disposed = True

    End If
  End Sub

  Public Sub Dispose() Implements IDisposable.Dispose
    Dispose(True)
    GC.SuppressFinalize(Me)
  End Sub

  Protected Overrides Sub Finalize()
    Try
      Dispose(False)
    Catch

      ...

    Finally
      MyBase.Finalize()
    End Try

  End Sub

End Class

[C#]

// The following code shows type
// that implements System.IDisposable interface
public class DisposableType: IDisposable
{

  protected bool disposed = false;

  // This method disposes the base object's resources.
  protected virtual void Dispose(bool disposing)
  {
    if (!this.disposed)
    {
      if (disposing)
      {

        ...

      }

      this.disposed = true;
    }
  }

  public void Dispose()
  {
    Dispose(true);
    GC.SuppressFinalize(this);
  }

  ~DisposableType()
  {
    Dispose(false);
  }

}

// This code will trigger the rule violation

public class AnotherDisposableType: IDisposable
{

  private DisposableType _disposableField = new DisposableType();

  protected bool disposed = false;

  // Violation: Disposable field _disposableField is not disposed
  protected virtual void Dispose(bool disposing)
  {
    if (!this.disposed)
    {
      if (disposing)
      {

        ...

      }

      this.disposed = true;
    }
  }

  public void Dispose()
  {
    Dispose(true);
    GC.SuppressFinalize(this);
  }

  ~DisposableType()
  {
    Dispose(false);
  }

}

' This is the correct implementation

public class AnotherDisposableType: IDisposable
{

  private DisposableType _disposableField = new DisposableType();

  protected bool disposed = false;

  protected virtual void Dispose(bool disposing)
  {
    if (!this.disposed)
    {
      if (disposing)
      {

        ...

        _disposableField.Dispose(disposing);
      }

      this.disposed = true;
    }
  }

  public void Dispose()
  {
    Dispose(true);
    GC.SuppressFinalize(this);
  }

  ~DisposableType()
  {
    Dispose(false);
  }

}

Related Rules

Disposable types should declare finalizer

Dispose methods should call base class dispose


Disposable types should declare finalizer

Rule ID: US00003

Problem

The type contains field of a type that suggest the use of unmanaged resource, but does not implement a finalizer as described by System.Object.Finalize.

Rule Description

According to Microsoft .NET Framework guidelines, if a type has System.IntPtr, System.UIntPtr, or System.Runtime.InteropServices.HandleRef fields, than it most likely stores pointers to unmanaged resources and therefore.

This rule is similar to FxCop rule 'Disposable types should declare finalizer', CheckId CA2216

Correcting Violations

The rule provides the following auto-correct options:
  • Implement finalizer (desctructor) that calls method Dispose(Boolean).

Rule Instances

Instances of this rule in the built-in profile:
  • Disposable types should declare finalizer.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

  Public Class SampleType
    Implements IDisposable

    Private _someUnmanagedResource As UIntPtr
    Protected disposed As Boolean = False

    Sub New()
      ' Allocate the unmanaged resource ...
      _someUnmanagedResource = ...
    End Sub

    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
      If Not Me.disposed Then
        If disposing Then

          ...

        End If

        ' Release unmanaged resources
        ...

        _someUnmanagedResource = IntPtr.Zero

        Me.disposed = True

      End If
    End Sub

    Public Sub Dispose() Implements IDisposable.Dispose
      Dispose(True)
      GC.SuppressFinalize(Me)
    End Sub

  End Class

' This is the correct implementation

  Public Class SampleType
    Implements IDisposable

    Private _someUnmanagedResource As UIntPtr
    Protected disposed As Boolean = False

    Sub New()
      ' Allocate the unmanaged resource ...
      _someUnmanagedResource = ...
    End Sub

    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
      If Not Me.disposed Then
        If disposing Then

          ...

        End If

        ' Release unmanaged resources
        ...

        _someUnmanagedResource = IntPtr.Zero

        Me.disposed = True

      End If
    End Sub

    Public Sub Dispose() Implements IDisposable.Dispose
      Dispose(True)
      GC.SuppressFinalize(Me)
    End Sub

    Protected Overrides Sub Finalize()
      Try
        Dispose(False)
      Catch
        ' Deal with errors or just ignore them
      Finally
        ' Invoke the base object's Finalize method
        MyBase.Finalize()
      End Try
    End Sub

  End Class

[C#]

// This code will trigger the rule violation

  public class SampleType: IDisposable
  {

    private UIntPtr _someUnmanagedResource;
    protected bool disposed = false;

    SampleType()
    {
      // Allocate the unmanaged resource ...
      _someUnmanagedResource = ...
    }

    protected virtual void Dispose(bool disposing)
    {
      if (!this.disposed)
      {
        if (disposing)
        {

          ...

        }

        // Release unmanaged resources
        ...

        _someUnmanagedResource = IntPtr.Zero;

        this.disposed = true;
      }
    }

    public void Dispose()
    {
      Dispose(true);
      GC.SuppressFinalize(this);
    }

  }

// This is the correct implementation

  public class SampleType: IDisposable
  {

    private UIntPtr _someUnmanagedResource;
    protected bool disposed = false;

    SampleType()
    {
      // Allocate the unmanaged resource ...
      _someUnmanagedResource = ...
    }

    protected virtual void Dispose(bool disposing)
    {
      if (!this.disposed)
      {
        if (disposing)
        {

          ...

        }

        // Release unmanaged resources
        ...

        _someUnmanagedResource = IntPtr.Zero;

        this.disposed = true;
      }
    }

    public void Dispose()
    {
      Dispose(true);
      GC.SuppressFinalize(this);
    }

    ~DisposableType()
    {
      Dispose(false);
    }

  }

Related Rules

Disposable fields should be disposed

Dispose methods should call base class dispose


Dispose methods should call base class dispose

Rule ID: US00004

Problem

The type derives from a type that implements the System.IDisposable interface, implements Dispose method, but does not call the Dispose method of the base type.

Rule Description

According to Microsoft .NET Framework guidelines, if the type derives from a type that implements the System.IDisposable interface, it must call the Dispose method of the base type from within its own implemented Dispose method.

This rule is similar to FxCop rule 'Dispose methods should call base class dispose', CheckId CA2215

Correcting Violations

The rule provides the following auto-correct options:
  • Find method Dispose and insert Dispose() call at the end of the method.

Rule Instances

Instances of this rule in the built-in profile:
  • Dispose methods should call base class dispose.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' The following code shows type
' that implements System.IDisposable interface
Public Class BaseDisposableType
  Implements IDisposable

  Protected disposed As Boolean = False

  ' This method disposes the base object's resources.
  Protected Overridable Sub Dispose(ByVal disposing As Boolean)
    If Not Me.disposed Then
      If disposing Then

        ...

      End If

      Me.disposed = True

    End If
  End Sub

  Public Sub Dispose() Implements IDisposable.Dispose
    Dispose(True)
    GC.SuppressFinalize(Me)
  End Sub

  Protected Overrides Sub Finalize()
    Try
      Dispose(False)
    Catch

      ...

    Finally
      MyBase.Finalize()
    End Try

  End Sub

End Class

' This code will trigger the rule violation

Public Class DerivedDisposableType
  Inherits BaseDisposableType

  ' This method disposes the derived object's resources.
  Protected Overrides Sub Dispose(ByVal disposing As Boolean)
    If Not Me.disposed Then
      If disposing Then
        ' Release disposable objects used by this instance here.

        ...

      End If
      ' Release unmanaged resources here.

      ...

    End If

  End Sub

End Class

' This is the correct implementation

Public Class DerivedDisposableType
  Inherits BaseDisposableType

  ' This method disposes the derived object's resources.
  Protected Overrides Sub Dispose(ByVal disposing As Boolean)
    If Not Me.disposed Then
      If disposing Then
        ' Release disposable objects used by this instance here.

        ...

      End If
      ' Release unmanaged resources here.

      ...

      ' Call the base object's Dispose protected method.
      MyBase.Dispose(disposing)

    End If

  End Sub

End Class

[C#]

// The following code shows type
// that implements System.IDisposable interface
public class BaseDisposableType: IDisposable
{

  protected bool disposed = false;

  // This method disposes the base object's resources.
  protected virtual void Dispose(bool disposing)
  {
    if (!this.disposed)
    {
      if (disposing)
      {

        ...

      }

      this.disposed = true;
    }
  }

  public void Dispose()
  {
    Dispose(true);
    GC.SuppressFinalize(this);
  }

  ~DisposableType()
  {
    Dispose(false);
  }

}

// This code will trigger the rule violation

public class DerivedDisposableType: BaseDisposableType
{

  // This method disposes the derived object's resources.
  protected override void Dispose(bool disposing)
  {
    if (!this.disposed)
    {
      if (disposing)
      {
        // Release disposable objects used by this instance here.

        ...

      }
      // Release unmanaged resources here.

      ...

    }

  }

}

' This is the correct implementation

public class DerivedDisposableType: BaseDisposableType
{

  // This method disposes the derived object's resources.
  protected override void Dispose(bool disposing)
  {
    if (!this.disposed)
    {
      if (disposing)
      {
        // Release disposable objects used by this instance here.

        ...

      }
      // Release unmanaged resources here.

      ...

      // Call the base object's Dispose protected method.
      base.Dispose(disposing);

    }

  }

}

Related Rules

Disposable fields should be disposed

Disposable types should declare finalizer


Do not explicitly call 'System.GC.Collect()' or 'System.GC.Collect(int)'

Rule ID: US00022

Problem

Garbage collection could be very costly and should be avoided by all means - except in benchmarking code.

Rule Description

This rule identifies explicit calls of the System.GC.Collect method. An error is reported for each occurrence.

Correcting Violations

The rule provides the following auto-correct options:
  • Comment out System.GC.Collect method call.

Rule Instances

Instances of this rule in the built-in profile:
  • Do not explicitly call 'System.GC.Collect()' or 'System.GC.Collect(int)'.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation
    Namespace Examples.Rules.GC
      Public Class GC
        Private Sub Method()
            '..
          Try
          Finally
            '..
            ' Violates the rule
            System.GC.Collect()
          End Try
        End Sub
      End Class
    End Namespace

' This is the correct implementation
    Namespace Examples.Rules.GC
      Public Class GCFixed
        Private Sub Method()
            '..
          Try
            '..
            ' System.GC.Collect() ' Fixed by commenting out
          Finally
          End Try
        End Sub
      End Class
    End Namespace

[C#]

// This code will trigger the rule violation
    namespace Examples.Rules.GC
    {
      public class GC
      {
        void Method()
        {
          try
          {
            //..
          }
          finally
          {
            //..
            // Violates the rule
            System.GC.Collect();
          }
        }
      }
    }

// This is the correct implementation
    namespace Examples.Rules.GC
    {
      public class GCFixed
      {
        void Method()
        {
          try
          {
            //..
          }
          finally
          {
            //..
            // System.GC.Collect() // Fixed by commenting out
          }
        }
      }
    }

Related Rules

© 2002-2019 SubMain. All rights reserved.
Designated trademarks and brands are the property of their respective owners.


Do not mark serviced components with WebMethod

Rule ID: US00015

Problem

Method in a type that inherits from System.EnterpriseServices.ServicedComponent class is marked with System.Web.Services.WebMethodAttribute.

Rule Description

Never mark a public method of a serviced component with a WebMethod attribute to make it callable throught the Web service infrastructure.

Both serviced components and Web services offer remote clients the ability to call methods in a .NET component. However, these two remoting technologies might conflict with each other because of the way they enable the transaction and context flow from the client and the component; therefore, you should never mix the two techniques in the same component.

This rule is similar to FxCop rule 'Do not mark serviced components with WebMethod', CheckId CA2212

Correcting Violations

The rule provides the following auto-correct options:
  • Comment out the System.Web.Services.WebMethodAttribute in the method.

Rule Instances

Instances of this rule in the built-in profile:
  • Do not mark serviced components with WebMethod.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System.EnterpriseServices

Public Class UsefulComponent

    Inherits ServicedComponent

    ' Violation: method should not be marked with System.Web.Services.WebMethodAttribute
    <WebMethod(Description := "Deposit an account", _
            EnableSession := True)> _
    Public Sub MakeDeposit(ByVal accountID As String, ByVal amount As Decimal)

        ...

    End Sub

End Class

' This is the correct implementation

Imports System.EnterpriseServices

Public Class UsefulComponent

    Inherits ServicedComponent

    Public Sub MakeDeposit(ByVal accountID As String, ByVal amount As Decimal)

        ...

    End Sub

End Class

[C#]

// This code will trigger the rule violation

using System.EnterpriseServices;

public class UsefulComponent: ServicedComponent
{

    // Violation: method should not be marked with System.Web.Services.WebMethodAttribute
    [WebMethod(Description = "Deposit an account", EnableSession = true)]
    public void MakeDeposit(string accountID, decimal amount)
    {

        ...

    }

}

// This is the correct implementation

using System.EnterpriseServices;

public class UsefulComponent: ServicedComponent
{

    public void MakeDeposit(string accountID, decimal amount)
    {

        ...

    }

}


Do not prefix calls with 'base' ('MyBase' in Visual Basic) unless local implementation exists

Rule ID: US00017

Problem

The call to the method is unnecessarily prefixed with base (MyBase in Visual Basic) keyword.

Rule Description

The base (MyBase in Visual Basic) keyword is used to access members of the base class from within a derived class. The call to the method should only use the base keyword if the item is declared virtual (Overridable in Visual Basic) in the base class and an override is defined in the local class, i.e. if a method on the base class has been overridden by another method.

Correcting Violations

The rule provides the following auto-correct options:
  • Replace base (MyBase in Visual Basic) keyword with this (Me in Visual Basic) keyword on the method call.

Rule Instances

Instances of this rule in the built-in profile:
  • Do not prefix calls with 'base' ('MyBase' in Visual Basic) unless local implementation exists.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Public Class Person

  Public FirstName As String
  Public LastName As String

  Public Sub PrintInfo()

  ...

  End Sub

End Class

Public Class Employee
  Inherits Person

  Public Position As String
  Public Salary As Decimal

  Public Sub PrintReport()

    ' Violation
    MyBase.PrintInfo()

    ...

  End Sub

End Class

' This is the correct implementation

Public Class Person

  Public FirstName As String
  Public LastName As String

  Public Sub PrintInfo()

  ...

  End Sub

End Class

Public Class Employee
  Inherits Person

  Public Position As String
  Public Salary As Decimal

  Public Sub PrintReport()

    Me.PrintInfo()

    ...

  End Sub

End Class

- Or -

Public Class Person

  Public FirstName As String
  Public LastName As String

  Public Overridable Sub PrintInfo()

    ...

  End Sub

End Class

Public Class Employee
  Inherits Person

  Public Position As String
  Public Salary As Decimal

  Public Overrides Sub PrintInfo()

    ...

  End Sub

  Public Sub PrintReport()

    MyBase.PrintInfo()

    ...

  End Sub

End Class

[C#]

// This code will trigger the rule violation

public class Person
{

  public string FirstName;
  public string LastName;

  public void PrintInfo()
  {

    ...

  }

}

public class Employee: Person
{

  public string Position;
  public decimal Salary;

  public void PrintReport()
  {

    ' Violation
    base.PrintInfo();

    ...

  }

}

// This is the correct implementation

public class Person
{

  public string FirstName;
  public string LastName;

  public void PrintInfo()
  {

    ...

  }

}

public class Employee: Person
{

  public string Position;
  public decimal Salary;

  public void PrintReport()
  {

    this.PrintInfo();

    ...

  }

}

- Or -

public class Person
{

  public string FirstName;
  public string LastName;

  public virtual void PrintInfo()
  {

    ...

  }

}

public class Employee: Person
{

  public string Position;
  public decimal Salary;

  public override void PrintInfo()
  {

    ...

  }

  public void PrintReport()
  {

    base.PrintInfo();

    ...

  }

}


Finalizers should be protected

Rule ID: US00005

Problem

The type implements a finalizer that does not have protected modifier.

Rule Description

According to Microsoft .NET Framework guidelines, types that implement finalizer must use protected modifier. This rule is enforced by the C# and Visual Basic compilers.

This rule is similar to FxCop rule 'Finalizers should be protected', CheckId CA2221

Correcting Violations

The rule provides the following auto-correct options:
  • Find finalizer and change its modifier to protected.

Rule Instances

Instances of this rule in the built-in profile:
  • Finalizers should be protected.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

  Public Class SampleType
    Implements IDisposable

    Protected disposed As Boolean = False

    ...

    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
      If Not Me.disposed Then
        If disposing Then

          ...

        End If

        ' Release unmanaged resources
        ...

        Me.disposed = True

      End If
    End Sub

    Public Sub Dispose() Implements IDisposable.Dispose
      Dispose(True)
      GC.SuppressFinalize(Me)
    End Sub

    Overrides Sub Finalize()
      Try
        Dispose(False)
      Catch
        ' Deal with errors or just ignore them
      Finally
        ' Invoke the base object's Finalize method
        MyBase.Finalize()
      End Try
    End Sub

  End Class

' This is the correct implementation

  Public Class SampleType
    Implements IDisposable

    Protected disposed As Boolean = False

    ...

    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
      If Not Me.disposed Then
        If disposing Then

          ...

        End If

        ' Release unmanaged resources
        ...

        Me.disposed = True

      End If
    End Sub

    Public Sub Dispose() Implements IDisposable.Dispose
      Dispose(True)
      GC.SuppressFinalize(Me)
    End Sub

    Protected Overrides Sub Finalize()
      Try
        Dispose(False)
      Catch
        ' Deal with errors or just ignore them
      Finally
        ' Invoke the base object's Finalize method
        MyBase.Finalize()
      End Try
    End Sub

  End Class

Related Rules

Finalizers should call base class finalizer


Finalizers should call base class finalizer

Rule ID: US00006

Problem

The type overrides System.Object.Finalize method, but does not call the Finalize method of the base type.

Rule Description

According to Microsoft .NET Framework guidelines, finalization must be propagated through the inheritance hierarchy. Therefore, the type must call Finalize method of its base class from within its own implemnted Finalize method.

This rule is similar to FxCop rule 'Finalizers should call base class finalizer', CheckId CA2220

Correcting Violations

The rule provides the following auto-correct options:
  • Find finalizer and insert MyBase.Finalize() call at the end of the method.

Rule Instances

Instances of this rule in the built-in profile:
  • Finalizers should call base class finalizer.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

  Public Class SampleType
    Implements IDisposable

    Protected disposed As Boolean = False

    ...

    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
      If Not Me.disposed Then
        If disposing Then

          ...

        End If

        ' Release unmanaged resources
        ...

        Me.disposed = True

      End If
    End Sub

    Public Sub Dispose() Implements IDisposable.Dispose
      Dispose(True)
      GC.SuppressFinalize(Me)
    End Sub

    Protected Overrides Sub Finalize()
      Try
        Dispose(False)
      Catch
        ' Deal with errors or just ignore them
      Finally

        ...

      End Try
    End Sub

  End Class

' This is the correct implementation

  Public Class SampleType
    Implements IDisposable

    Protected disposed As Boolean = False

    ...

    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
      If Not Me.disposed Then
        If disposing Then

          ...

        End If

        ' Release unmanaged resources
        ...

        Me.disposed = True

      End If
    End Sub

    Public Sub Dispose() Implements IDisposable.Dispose
      Dispose(True)
      GC.SuppressFinalize(Me)
    End Sub

    Protected Overrides Sub Finalize()
      Try
        Dispose(False)
      Catch
        ' Deal with errors or just ignore them
      Finally

        ...

        ' Invoke the base object's Finalize method
        MyBase.Finalize()
      End Try
    End Sub

  End Class

Related Rules

Finalizers should be protected


Implement ISerializable correctly

Rule ID: US00007

Problem

The type implements the System.Runtime.Serialization.ISerializable interface and contains GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) method which is not externally visible.

- OR -

Non sealed type implements the System.Runtime.Serialization.ISerializable interface and contains GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) method which is not overridable.

- OR -

The type implements the System.Runtime.Serialization.ISerializable interface, but does not override the GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) method and the type declares instance fields that are not marked with the System.NonSerializedAttribute attribute.

Rule Description

If a type is derived from one that implements the System.Runtime.Serialization.ISerializable interface and it has instance fields that need to be serialized, the derived class must implement both the serialization constructor as well as the GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) method. Fields that are not to be serialized should be marked with the NonSerializedAttribute attribute, which explicitly excludes the target field from the serialization process.

Implementations of the GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) method should be externally visible, if the type is not sealed. That enable derived types to call and override the method.

This rule is similar to FxCop rule 'Implement ISerializable correctly', CheckId CA2240

Correcting Violations

The rule provides the following auto-correct options depending from detected violation:
  • Find method GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) and change its modifier.
  • Add method GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) and add instance fields to the serialization process.
  • Add empty method GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext).

Rule Instances

Instances of this rule in the built-in profile:
  • Implement ISerializable correctly.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' Parent type Person implements ISerializable interface,
' but derived Employee type does not override GetObjectData method and
' introduces new _salary property, which is not marked with NonSerializedAttribute attribute

Imports System.Runtime.Serialization

' The following parent type implements ISerializable interface
<Serializable()> _
Public Class Person
    Implements ISerializable

    Private _firstName As String
    Private _lastName As String

    Public ReadOnly Property FirstName() As String
        Get
            Return _firstName
        End Get
    End Property

    Public ReadOnly Property LastName() As String
        Get
            Return _lastName
        End Get
    End Property

    Public Sub New(ByVal firstName As String, ByVal lastName As String)
        Me._firstName = firstName
        Me._lastName = lastName
    End Sub

    ' Special serialization constructor
    Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
        _firstName = CType(info.GetValue("_firstName", GetType(String)), String)
        _lastName = CType(info.GetValue("_lastName", GetType(String)), String)
    End Sub

    Public Overridable Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext) _
        Implements ISerializable.GetObjectData

        info.AddValue("_firstName", _firstName)
        info.AddValue("_lastName", _lastName)

    End Sub

End Class

' This code will trigger the rule violation

' Violation: the GetObjectData method does not overrided to serialize new _salary property.
<Serializable> _
Public Class Employee
    Inherits Person

    Private _salary As Decimal

    Public ReadOnly Property Salary() As Decimal
        Get
            Return _salary
        End Get
    End Property

    Public Sub New(ByVal firstName As String, ByVal lastName As String, ByVal salary As Decimal)

        MyBase.New(firstName, lastName)

        Me._salary = salary

    End Sub

    Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)

        MyBase.New(info, context)

        _salary = CType(info.GetValue("_salary", GetType(Decimal)), Decimal)

    End Sub

End Class

' This is the correct implementation

<Serializable> _
Public Class Employee
    Inherits Person

    Private _salary As Decimal

    Public ReadOnly Property Salary() As Decimal
        Get
            Return _salary
        End Get
    End Property

    Public Sub New(ByVal firstName As String, ByVal lastName As String, ByVal salary As Decimal)

        MyBase.New(firstName, lastName)
        Me._salary = salary

    End Sub

    Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
        MyBase.New(info, context)
        _salary = CType(info.GetValue("_salary", GetType(Decimal)), Decimal)
    End Sub

    Public Overrides Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext)
        MyBase.GetObjectData(info, context)
        info.AddValue("_salary", _salary)
    End Sub

End Class

[C#]

// Parent type Person implements ISerializable interface,
// but derived Employee type does not override GetObjectData method and
// introduces new _salary property, which is not marked with NonSerializedAttribute attribute

using System.Runtime.Serialization;

// The following base type implements ISerializable interface
[Serializable()]
public class Person: ISerializable
{

    private string _firstName;
    private string _lastName;

    public string FirstName
    {
        get
        {
            return _firstName;
        }
    }

    public string LastName
    {
        get
        {
            return _lastName;
        }
    }

    public Person(string firstName, string lastName)
    {
        this._firstName = firstName;
        this._lastName = lastName;
    }

    // Special serialization constructor
    protected Person(SerializationInfo info, StreamingContext context)
    {
        _firstName = (string)info.GetValue("_firstName", string.GetType());
        _lastName = (string)info.GetValue("_lastName", string.GetType());
    }

    public virtual void ISerializable.GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext)
    {

        info.AddValue("_firstName", _firstName);
        info.AddValue("_lastName", _lastName);

    }

}

// This code will trigger the rule violation

// Violation: the GetObjectData method does not overrided to serialize new _salary property.
[Serializable]
public class Employee: Person
{

    private decimal _salary;

    public decimal Salary
    {
        get
        {
            return _salary;
        }
    }

    public Employee(string firstName, string lastName, decimal salary):
      base(firstName, lastName)
    {

        this._salary = salary;

    }

    protected Employee(SerializationInfo info, StreamingContext context):
      base(info, context)
    {
        _salary = (decimal)(info.GetValue("_salary", decimal.GetType());
    }

}

// This is the correct implementation

[Serializable]
public class Employee: Person
{

    private decimal _salary;

    public decimal Salary
    {
        get
        {
            return _salary;
        }
    }

    public Employee(string firstName, string lastName, decimal salary):
      base(firstName, lastName)
    {

        this._salary = salary;

    }

    protected Employee(SerializationInfo info, StreamingContext context):
      base(info, context)
    {
        _salary = (decimal)(info.GetValue("_salary", decimal.GetType());
    }

    public override void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        base.GetObjectData(info, context);
        info.AddValue("_salary", _salary);
    }

}

Related Rules

Call base class methods on ISerializable types

Implement ISerializable for serializable classes that expose events

Implement Serialization Constructor

Implement serialization methods correctly

Include instance fields in the serialization/deserialization process

Mark all non-serializable fields with "NonSerialized" attribute

Provide deserialization methods for optional fields


Implement ISerializable for serializable classes that expose events

Rule ID: US00008

Problem

Type which exposes events has System.SerializableAttribute attribute.

Rule Description

For each event, both the Visual Basic .NET and the C# compiler define a hidden delegate field; delegate types aren't serializable and any attempt to serialize an instance that contains non-null delegates will fail. By implementing custom serialization, you can skip these delegate fields in the serialization process.

Correcting Violations

The rule provides the following auto-correct options:
  • Implement interface System.Runtime.Serialization.ISerializable for the type

Rule Instances

Instances of this rule in the built-in profile:
  • Implement System.Runtime.Serialization.ISerializable for serializable classes that expose events.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

' Violation: type should implement ISerializable

<Serializable> _
Public Class Person

    Private _firstName As String
    Private _lastName As String

    ' Changed event type is not serializable
    Public Event Changed As EventHandler

    Public Property FirstName() As String
        Get
            Return _firstName
        End Get
        Set(ByVal newValue As String)
            _firstName = newValue
            RaiseEvent Changed(Me, EventArgs.Empty)
        End Set
    End Property

    Public Property LastName() As String
        Get
            Return _lastName
        End Get
        Set(ByVal newValue As String)
            _lastName = newValue
            RaiseEvent Changed(Me, EventArgs.Empty)
        End Set
    End Property

    Public Sub New(ByVal firstName As String, ByVal lastName As String)

        Me._firstName = firstName
        Me._lastName = lastName

    End Sub

End Class

' This is the correct implementation

Imports System.Runtime.Serialization

<Serializable> _
Public Class Person
    Implements ISerializable

    Private _firstName As String
    Private _lastName As String

    Public Event Changed As EventHandler

    Public Property FirstName() As String
        Get
            Return _firstName
        End Get
        Set(ByVal newValue As String)
            _firstName = newValue
            RaiseEvent Changed(Me, EventArgs.Empty)
        End Set
    End Property

    Public Property LastName() As String
        Get
            Return _lastName
        End Get
        Set(ByVal newValue As String)
            _lastName = newValue
            RaiseEvent Changed(Me, EventArgs.Empty)
        End Set
    End Property

    Public Sub New(ByVal firstName As String, ByVal lastName As String)

        Me._firstName = firstName
        Me._lastName = lastName

    End Sub

    Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)

        _firstName = CType(info.GetValue("_firstName", GetType(String)), String)
        _lastName = CType(info.GetValue("_lastName", GetType(String)), String)

    End Sub

    Public Overridable Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext) _
      Implements ISerializable.GetObjectData

        info.AddValue("_firstName", _firstName)
        info.AddValue("_lastName", _lastName)

    End Sub

End Class

[C#]

// This code will trigger the rule violation

// Violation: type should implement ISerializable

[Serializable()]
public class Person
{

    private string _firstName;
    private string _lastName;

    // Changed event type is not serializable
    public event EventHandler Changed;

    public string FirstName
    {
        get
        {
            return _firstName;
        }
        set
        {
            _firstName = value;
            Changed(this, EventArgs.Empty);
        }
    }

    public string LastName
    {
        get
        {
            return _lastName;
        }
        set
        {
            _lastName = value;
            Changed(this, EventArgs.Empty);
        }
    }

    public Person(string firstName, string lastName)
    {
        this._firstName = firstName;
        this._lastName = lastName;
    }

}

// This is the correct implementation

using System.Runtime.Serialization;

[Serializable()]
public class Person: ISerializable
{

    private string _firstName;
    private string _lastName;

    public event EventHandler Changed;

    public string FirstName
    {
        get
        {
            return _firstName;
        }
        set
        {
            _firstName = value;
            Changed(this, EventArgs.Empty);
        }
    }

    public string LastName
    {
        get
        {
            return _lastName;
        }
        set
        {
            _lastName = value;
            Changed(this, EventArgs.Empty);
        }
    }

    public Person(string firstName, string lastName)
    {
        this._firstName = firstName;
        this._lastName = lastName;
    }

    protected Person(SerializationInfo info, StreamingContext context)
    {
        _firstName = (string)info.GetValue("_firstName", string.GetType());
        _lastName = (string)info.GetValue("_lastName", string.GetType());
    }

    public virtual void ISerializable.GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext)
    {

        info.AddValue("_firstName", _firstName);
        info.AddValue("_lastName", _lastName);

    }

}

Related Rules

Call base class methods on ISerializable types

Implement ISerializable correctly

Implement Serialization Constructor

Implement serialization methods correctly

Include instance fields in the serialization/deserialization process

Mark all non-serializable fields with "NonSerialized" attribute

Provide deserialization methods for optional fields


Implement Serialization Constructor

Rule ID: US00009

Problem

The type implements the System.Runtime.Serialization.ISerializable interface, but does not have a constructor with the System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext parameter signature.

- OR -

The unsealed type implements the System.Runtime.Serialization.ISerializable interface and have a serialization constructor (with the System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext parameter signature) with non protected access modifier.

- OR -

The sealed type {0} implements the System.Runtime.Serialization.ISerializable interface and have a serialization constructor (with the System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext parameter signature) with non private modifier.

This rule is similar to FxCop rule 'Implement serialization constructors', CheckId CA2229

Rule Description

You can add the System.Runtime.Serialization.ISerializable interface to a type to customize the serialization process. Both GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) and the special serialization constructor must be implemented in that case. The serialization constructor is required when the object is deserialized. A System.Runtime.Serialization.SerializationException will be thrown when an attempt is made to deserialize a type without the constructor.

Correcting Violations

The rule provides the following auto-correct options depending from detected violation:
  • Add constructor with System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext parameter signature and add instance fields to the serialization process.
  • Add empty constructor with System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext parameter signature.
  • Find constructor with System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext parameter signature and change its modifier.

Rule Instances

Instances of this rule in the built-in profile:
  • Implement serialization constructor.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

' Violation: The type Person implements System.Runtime.Serialization.ISerializable interface,
' but it does not have special serialization constructor.

Imports System.Runtime.Serialization

<Serializable()> _
Public Class Person
    Implements ISerializable

    Private _firstName As String
    Private _lastName As String

    Public ReadOnly Property FirstName() As String
        Get
            Return _firstName
        End Get
    End Property

    Public ReadOnly Property LastName() As String
        Get
            Return _lastName
        End Get
    End Property

    Public Sub New(ByVal firstName As String, ByVal lastName As String)
        Me._firstName = firstName
        Me._lastName = lastName
    End Sub

    Public Overridable Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext) _
        Implements ISerializable.GetObjectData

        info.AddValue("_firstName", _firstName)
        info.AddValue("_lastName", _lastName)
    End Sub

End Class

' This is the correct implementation

' The special serialization constructor is implemented
' and marked with protected access modifier.

Imports System.Runtime.Serialization

<Serializable()> _
Public Class Person
    Implements ISerializable

    Private _firstName As String
    Private _lastName As String

    Public ReadOnly Property FirstName() As String
        Get
            Return _firstName
        End Get
    End Property

    Public ReadOnly Property LastName() As String
        Get
            Return _lastName
        End Get
    End Property

    Public Sub New(ByVal firstName As String, ByVal lastName As String)
        Me._firstName = firstName
        Me._lastName = lastName
    End Sub

    ' Special serialization constructor
    Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
        _firstName = CType(info.GetValue("_firstName", GetType(String)), String)
        _lastName = CType(info.GetValue("_lastName", GetType(String)), String)
    End Sub

    Public Overridable Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext) _
        Implements ISerializable.GetObjectData

        info.AddValue("_firstName", _firstName)
        info.AddValue("_lastName", _lastName)
    End Sub

End Class

[C#]

// This code will trigger the rule violation

// Violation: The type Person implements System.Runtime.Serialization.ISerializable interface,
// but it does not have special serialization constructor.

using System.Runtime.Serialization;

[Serializable()]
public class Person: ISerializable
{

    private string _firstName;
    private string _lastName;

    public string FirstName
    {
        get
        {
            return _firstName;
        }
    }

    public string LastName
    {
        get
        {
            return _lastName;
        }
    }

    public Person(string firstName, string lastName)
    {
        this._firstName = firstName;
        this._lastName = lastName;
    }

    public virtual void ISerializable.GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext)
    {

        info.AddValue("_firstName", _firstName);
        info.AddValue("_lastName", _lastName);

    }

}

// This is the correct implementation

// The special serialization constructor is implemented
// and marked with protected access modifier.

using System.Runtime.Serialization;

[Serializable()]
public class Person: ISerializable
{

    private string _firstName;
    private string _lastName;

    public string FirstName
    {
        get
        {
            return _firstName;
        }
    }

    public string LastName
    {
        get
        {
            return _lastName;
        }
    }

    public Person(string firstName, string lastName)
    {
        this._firstName = firstName;
        this._lastName = lastName;
    }

    // Special serialization constructor
    protected Person(SerializationInfo info, StreamingContext context)
    {
        _firstName = (string)info.GetValue("_firstName", string.GetType());
        _lastName = (string)info.GetValue("_lastName", string.GetType());
    }

    public virtual void ISerializable.GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext)
    {

        info.AddValue("_firstName", _firstName);
        info.AddValue("_lastName", _lastName);

    }

}

Related Rules

Call base class methods on ISerializable types

Implement ISerializable correctly

Implement ISerializable for serializable classes that expose events

Implement serialization methods correctly

Include instance fields in the serialization/deserialization process

Mark all non-serializable fields with "NonSerialized" attribute

Provide deserialization methods for optional fields


Implement serialization methods correctly

Rule ID: US00010

Problem

The type has System.SerializableAttribute attribute and has a method (with System.Runtime.Serialization.StreamingContext parameter signature) that handles a serialization event with incorrect visibility modifier.

- OR -

The type has System.SerializableAttribute attribute and has a method that handles a serialization event with incorrect parameter list.

- OR -

The type has System.SerializableAttribute attribute and has a method that handles a serialization event with incorrect parameter return type.

Rule Description

According to Microsoft .NET Framework guidelines, method that handles a serialization event should take a single parameter of type System.Runtime.Serialization.StreamingContext, return void, and have private visibility modifier.

This rule is similar to FxCop rule 'Implement serialization methods correctly', CheckId CA2238

Correcting Violations

The rule provides the following auto-correct options depending from detected violation:
  • Find method with System.Runtime.Serialization.StreamingContext parameter signature and change its visibility modifier to private.
  • Find method and change its parameter signature to System.Runtime.Serialization.StreamingContext.
  • Find method and change return type to void.

Rule Instances

Instances of this rule in the built-in profile:
  • Implement serialization methods correctly.

Example

The following example shows shows correctly declared serialization event handlers.

[Visual Basic]

' This is the correct implementation

Imports System.Runtime.Serialization

<SerializableAttribute> _
Public Class SampleTypeWithEventHandlers

  <OnSerializingAttribute> _
  Private Sub OnSerializing(context As StreamingContext)

    ...

  End Sub

  <OnSerializedAttribute> _
  Private Sub OnSerialized(context As StreamingContext)

    ...

  End Sub

  <OnDeserializingAttribute> _
  Private Sub OnDeserializing(context As StreamingContext)

    ...

  End Sub

  <OnDeserializedAttribute> _
  Private Sub OnDeserialized(context As StreamingContext)

    ...

  End Sub

End Class

[C#]

// This is the correct implementation

using System.Runtime.Serialization;

[SerializableAttribute]
public class SampleTypeWithEventHandlers
{

  [OnSerializingAttribute]
  private void OnSerializing(StreamingContext context)
  {

    ...

  }

  [OnSerializedAttribute]
  private void OnSerialized(StreamingContext context)
  {

    ...

  }

  [OnDeserializingAttribute]
  private void OnDeserializing(StreamingContext context)
  {

    ...

  }

  [OnDeserializedAttribute]
  private void OnDeserialized(StreamingContext context)
  {

    ...

  }

}

Related Rules

Call base class methods on ISerializable types

Implement ISerializable correctly

Implement ISerializable for serializable classes that expose events

Implement Serialization Constructor

Include instance fields in the serialization/deserialization process

Mark all non-serializable fields with "NonSerialized" attribute

Provide deserialization methods for optional fields


Include instance fields in the serialization/deserialization process.

Rule ID: US00011

Problem

The type implements the System.Runtime.Serialization.ISerializable interface, contains instance field that is not marked with the System.NonSerializedAttribute attribute.

- OR -

The field is not included in the serialization process in GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) method.

Rule Description

If a type implements the System.Runtime.Serialization.ISerializable interface, than all of its instance fields should be included in the serialization/deserialization process of expicitly marked with System.NonSerializedAttribute attribute.

To include the instance field in the serialization/deserialization process, the type must implement the GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) method and special serialization constructor.

This rule is similar to FxCop rule 'Implement ISerializable correctly', CheckId CA2240

Correcting Violations

The rule provides the following auto-correct options depending from detected violation:
  • Find method GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) and insert AddValue() call at the end of the method.
  • Add System.NonSerializedAttribute to the instance field.
  • Find serialization constructor and insert GetValue() call at the end of the constructor.

Rule Instances

Instances of this rule in the built-in profile:
  • Include instance fields in the serialization/deserialization process.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' Sample serializable type
<Serializable()>  _
Public Class MySerializableType
  Implements ISerializable

  Private _serializableField As Integer

  Public ReadOnly Property SerializableField() As Integer
    Get
      Return _serializableField
    End Get
  End Property

  Public Sub New(ByVal serializableField As Integer)
    _serializableField = serializableField
  End Sub

  Protected Sub New(ByVal info As SerializationInfo, _
  ByVal context As StreamingContext)
      _serializableField = info.GetInt32("serializableField")
  End Sub 'New

  Public Overridable Sub GetObjectData(ByVal info As _
    SerializationInfo, ByVal context As StreamingContext)
    info.AddValue("serializableField", _serializableField)
  End Sub
End Class

' Sample non-serializable type
Public Class MyNonSerializableType

  Private _nonSerializableField As Integer

  Public ReadOnly Property NonSerializableField() As Integer
    Get
      Return _nonSerializableField
    End Get
  End Property

  Public Sub New(ByVal nonSerializableField As Integer)
    _nonSerializableField = nonSerializableField
  End Sub

End Class

' This code will trigger the rule violation

<Serializable()> _
Public Class MyType

    Private _mySerializable As MySerializableType
    Private _myNonSerializable As MyNonSerializableType

    Public ReadOnly Property MySerializable() As MySerializableType
        Get
            Return _mySerializable
        End Get
    End Property

    Public ReadOnly Property MyNonSerializable() As MyNonSerializableType
        Get
            Return _myNonSerializable
        End Get
    End Property

    Public Sub New(ByVal mySerializable As MySerializableType, ByVal myNonSerializable As MyNonSerializableType)
        Me._mySerializable = mySerializable
        Me._myNonSerializable = myNonSerializable
    End Sub

End Class

' This is the correct implementation

<Serializable()> _
Public Class MyType
    Implements ISerializable

    Private _mySerializable As MySerializableType

    <NonSerialized()> _
    Private _myNonSerializable As MyNonSerializableType

    Public ReadOnly Property MySerializable() As MySerializableType
        Get
            Return _mySerializable
        End Get
    End Property

    Public ReadOnly Property MyNonSerializable() As MyNonSerializableType
        Get
            Return _myNonSerializable
        End Get
    End Property

    Public Sub New(ByVal mySerializable As MySerializableType, ByVal myNonSerializable As MyNonSerializableType)
        Me._mySerializable = mySerializable
        Me._myNonSerializable = myNonSerializable
    End Sub

    ' Special serialization constructor
    Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
        _mySerializable = CType(info.GetValue("mySerializable", GetType(MySerializableType)), MySerializableType)
    End Sub

    Public Overridable Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext) _
        Implements ISerializable.GetObjectData

        info.AddValue("mySerializable", _mySerializable)

    End Sub

End Class

[C#]

// Sample serializable type
[Serializable()]
public class MySerializableType: ISerializable
{

  private int _serializableField;

  public int SerializableField
  {
    get
    {
      return _serializableField;
    }
  }

  public MySerializableType(int serializableField)
  {
    _serializableField = serializableField;
  }

  protected MySerializableType(SerializationInfo info, StreamingContext context)
  {
    _serializableField = info.GetInt32("serializableField");
  }

  public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
  {
    info.AddValue("serializableField", _serializableField)
  }

}

// Sample non-serializable type
public class MyNonSerializableType
{

  private int _nonSerializableField;

  public int NonSerializableField
  {
    get
    {
      return _nonSerializableField;
    }
  }

  public MyNonSerializableType(int nonSerializableField)
  {
    _nonSerializableField = nonSerializableField;
  }

}

// This code will trigger the rule violation

[Serializable()]
public class MyType
{

    private MySerializableType _mySerializable;
    private MyNonSerializableType _myNonSerializable;

    public MySerializableType MySerializable
    {
        get
        {
            return _mySerializable;
        }
    }

    public MyNonSerializableType MyNonSerializable
    {
        get
        {
            return _myNonSerializable;
        }
    }

    public MyType(MySerializableType mySerializable, MyNonSerializableType myNonSerializable)
    {
        this._mySerializable = mySerializable;
        this._myNonSerializable = myNonSerializable;
    }

}

// This is the correct implementation

[Serializable()]
public class MyType: ISerializable
{

    private MySerializableType _mySerializable;

    [NonSerialized()]
    private MyNonSerializableType _myNonSerializable;

    public MySerializableType MySerializable
    {
        get
        {
            return _mySerializable;
        }
    }

    public MyNonSerializableType MyNonSerializable
    {
        get
        {
            return _myNonSerializable;
        }
    }

    public MyType(MySerializableType mySerializable, MyNonSerializableType myNonSerializable)
    {
        this._mySerializable = mySerializable;
        this._myNonSerializable = myNonSerializable;
    }

    // Special serialization constructor
    protected MyType(SerializationInfo info, StreamingContext context)
    {
        _mySerializable = (MySerializableType)info.GetValue("mySerializable", MySerializableType.GetType())
    }

    public virtual void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
    {

        info.AddValue("mySerializable", _mySerializable);

    }

}

Related Rules

Call base class methods on ISerializable types

Implement ISerializable correctly

Implement ISerializable for serializable classes that expose events

Implement Serialization Constructor

Implement serialization methods correctly

Mark all non-serializable fields with "NonSerialized" attribute

Provide deserialization methods for optional fields


Lock both when either set or get is locked for a property

Rule ID: US00023

Problem

Property has both get and set methods and only one of the methods uses a lock and the other does not

- OR -

Property has both get and set methods and both of them use lock, but lock on different objects

Rule Description

If one of the methods in a property requires a lock, then it is very likely that the other one also needs it. Not locking can lead to issues that are very hard to detect and debug since the issues are usually not easy to reproduce.

Correcting Violations

The rule provides the following auto-correct options:
  • Lock both get and set accessors on the same object for the property.

Rule Instances

Instances of this rule in the built-in profile:
  • Lock both when either set or get is locked for a property

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation
    Public Class SomeClass
      Private a As Object
      Private DeadBolt As New Object()
      ' Violates the rule.
      Public Property SomeObject() As Object
        Get
          SyncLock DeadBolt
            Return a
          End SyncLock
        End Get
        Set
          a = value
        End Set
      End Property
    End Class

' This is the correct implementation
    Public Class SomeClass
      Private a As Object
      Private DeadBolt As New Object()
      Public Property SomeObject() As Object
        Get
          SyncLock DeadBolt
            Return a
          End SyncLock
        End Get
        Set
          SyncLock DeadBolt
            a = value
          End SyncLock
        End Set
      End Property
    End Class

[C#]

// This code will trigger the rule violation
    public class SomeClass
    {
      private object a;
      private object DeadBolt = new object();
      // Violates the rule.
      public object SomeObject
      {
        get
        {
          lock (DeadBolt)
          {
            return a;
          }
        }
        set
        {
          a = value;
        }
      }
    }

// This is the correct implementation
    public class SomeClass
    {
      private object a;
      private object DeadBolt = new object();
      public object SomeObject
      {
        get
        {
          lock (DeadBolt)
          {
            return a;
          }
        }
        set
        {
          lock (DeadBolt)
          {
            a = value;
          }
        }
      }
    }

Related Rules

© 2002-2019 SubMain. All rights reserved.
Designated trademarks and brands are the property of their respective owners.


Mark all non-serializable fields with "NonSerialized" attribute

Rule ID: US00012

Problem

The type marked with System.SerializableAttribute attribute and has an instance field of a type that is not serializable.

Rule Description

When the type is serialized, a System.Runtime.Serialization.SerializationException exception is thrown if a type contains an instance field of a type that is not serializable.

This rule is similar to FxCop rule 'Mark all non-serializable fields', CheckId CA2235

Correcting Violations

The rule provides the following auto-correct options:
  • Find field and mark it with System.NonSerializedAttribute attribute.
  • Find type and mark it with System.SerializableAttribute attribute.

Rule Instances

Instances of this rule in the built-in profile:
  • Mark all non-serializable fields with "NonSerialized" attribute.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

Public Class ContactInformation

    Private _address As String
    Private _phone As String

    Public ReadOnly Property Address() As String
        Get
            Return _address
        End Get
    End Property

    Public ReadOnly Property Phone() As String
        Get
            Return _phone
        End Get
    End Property

    Public Sub New(ByVal address As String, ByVal phone As String)

        Me._address = address
        Me._phone = phone

    End Sub

End Class

' This code will trigger the rule violation

<Serializable> _
Public Class Person

    Private _firstName As String
    Private _lastName As String

    ' Violation: _contactInformation field should be marked with NonSerialized attribute
    ' or ContactInformation type should be marked with Serializable attribute
    Private _contactInformation As ContactInformation

    Public ReadOnly Property FirstName() As String
        Get
            Return _firstName
        End Get
    End Property

    Public ReadOnly Property LastName() As String
        Get
            Return _lastName
        End Get
    End Property

    Public ReadOnly Property ContactInfo() As ContactInformation
        Get
            Return _contactInformation
        End Get
    End Property

    Public Sub New(ByVal firstName As String, ByVal lastName As String, _
        ByVal contactInfo As ContactInformation)

        Me._firstName = firstName
        Me._lastName = lastName
        Me._contactInformation = contactInfo

    End Sub

End Class

' This is the correct implementation

'Mark _contactInformation field with NonSerialized attribute
<Serializable> _
Public Class Person

    Private _firstName As String
    Private _lastName As String

    <NonSerialized()> _
    Private _contactInformation As ContactInformation

    Public ReadOnly Property FirstName() As String
        Get
            Return _firstName
        End Get
    End Property

    Public ReadOnly Property LastName() As String
        Get
            Return _lastName
        End Get
    End Property

    Public ReadOnly Property ContactInfo() As ContactInformation
        Get
            Return _contactInformation
        End Get
     End Property

    Public Sub New(ByVal firstName As String, ByVal middleName As String, _
        ByVal lastName As String, ByVal email As String, _
        ByVal contactInfo As ContactInformation)

        Me._firstName = firstName
        Me._lastName = lastName
        Me._contactInformation = contactInfo

    End Sub

End Class

- OR -

' Mark ContactInformation type with Serializable attribute
<Serializable> _
Public Class ContactInformation

    Private _address As String
    Private _phone As String

    Public ReadOnly Property Address() As String
        Get
            Return _address
        End Get
    End Property

    Public ReadOnly Property Phone() As String
        Get
            Return _phone
        End Get
    End Property

    Public Sub New(ByVal address As String, ByVal phone As String)

        Me._address = address
        Me._phone = phone

    End Sub

End Class

[C#]

public class ContactInformation
{

    private string _address;
    private string _phone;

    public string Address
    {
        get
        {
            return _address;
        }
    }

    public string Phone
    {
        get
        {
            return _phone;
        }
    }

    public ContactInformation(string address, string phone)
    {

        this._address = address;
        this._phone = phone;

    }

}

// This code will trigger the rule violation

[Serializable()]
public class Person
{

    private string _firstName;
    private string _lastName;

    // Violation: _contactInformation field should be marked with NonSerialized attribute
    // or ContactInformation type should be marked with Serializable attribute
    private ContactInformation _contactInformation;

    public string FirstName
    {
        get
        {
            return _firstName;
        }
    }

    public string LastName
    {
        get
        {
            return _lastName;
        }
    }

    public ContactInformation ContactInfo
    {
        get
        {
            return _contactInformation;
        }
    }

    public Person(string firstName, string lastName, ContactInformation contactInfo)
    {

        this._firstName = firstName;
        this._lastName = lastName;
        this._contactInformation = contactInfo;

    }

}

// This is the correct implementation

//Mark _contactInformation field with NonSerialized attribute
[Serializable()]
public class Person
{

    private string _firstName;
    private string _lastName;

    [NonSerialized()]
    private ContactInformation _contactInformation;

    public string FirstName
    {
        get
        {
            return _firstName;
        }
    }

    public string LastName
    {
        get
        {
            return _lastName;
        }
    }

    public ContactInformation ContactInfo
    {
        get
        {
            return _contactInformation;
        }
    }

    public Person(string firstName, string lastName, ContactInformation contactInfo)
    {

        this._firstName = firstName;
        this._lastName = lastName;
        this._contactInformation = contactInfo;

    }

}

- OR -

// Mark ContactInformation type with Serializable attribute
[Serializable()]
public class ContactInformation
{

    private string _address;
    private string _phone;

    public string Address
    {
        get
        {
            return _address;
        }
    }

    public string Phone
    {
        get
        {
            return _phone;
        }
    }

    public ContactInformation(string address, string phone)
    {

        this._address = address;
        this._phone = phone;

    }

}

Related Rules

Call base class methods on ISerializable types

Implement ISerializable correctly

Implement ISerializable for serializable classes that expose events

Implement Serialization Constructor

Implement serialization methods correctly

Include instance fields in the serialization/deserialization process

Provide deserialization methods for optional fields


Mark derived types with specified attribute

Rule ID: US00013

Problem

The type implements certain interface, but is not marked with specific attribute.

Rule Description

If the type implements some certain interface, then it should be marked with specific attribute.

Types implementing System.Runtime.Serialization.ISerializable interface must be marked with SerializedAttribute attribute. A type that implements System.Runtime.Serialization.ISerializable interface but isn't marked with the SerializableAttribute attributemight not be serialized under all circumstances and might not be recognized as serializable by reflection code that only checks for the presence of the attribute.

This rule is similar to FxCop rule 'Mark ISerializable types with serializable', CheckId CA2237

Correcting Violations

The rule provides the following auto-correct options:
  • Mark the type with specific attribute.

Configurable Properties

  • AttributeToCheck - Certain Attribute to be checked;
  • MustImplement - Type should implement the specified type or interface.

Rule Instances

Instances of this rule in the built-in profile:
  • Mark ISerializable types with "Serializable" attribute.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

' Violation: type is not marked with Serializable attribute
Public Class MySerializableType
  Implements ISerializable

  Private _serializableField As Integer

  Public ReadOnly Property SerializableField() As Integer
    Get
      Return _serializableField
    End Get
  End Property

  Public Sub New(ByVal serializableField As Integer)
    _serializableField = serializableField
  End Sub

  Protected Sub New(ByVal info As SerializationInfo, _
  ByVal context As StreamingContext)
      _serializableField = info.GetInt32("serializableField")
  End Sub 'New

  Public Overridable Sub GetObjectData(ByVal info As _
    SerializationInfo, ByVal context As StreamingContext)
    info.AddValue("serializableField", _serializableField)
  End Sub
End Class

' This is the correct implementation

<Serializable()>  _
Public Class MySerializableType
  Implements ISerializable

  Private _serializableField As Integer

  Public ReadOnly Property SerializableField() As Integer
    Get
      Return _serializableField
    End Get
  End Property

  Public Sub New(ByVal serializableField As Integer)
    _serializableField = serializableField
  End Sub

  Protected Sub New(ByVal info As SerializationInfo, _
  ByVal context As StreamingContext)
      _serializableField = info.GetInt32("serializableField")
  End Sub 'New

  Public Overridable Sub GetObjectData(ByVal info As _
    SerializationInfo, ByVal context As StreamingContext)
    info.AddValue("serializableField", _serializableField)
  End Sub
End Class

[C#]

// This code will trigger the rule violation

// Violation: type is not marked with Serializable attribute
public class MySerializableType: ISerializable
{

  private int _serializableField;

  public int SerializableField
  {
    get
    {
      return _serializableField;
    }
  }

  public MySerializableType(int serializableField)
  {
    _serializableField = serializableField;
  }

  protected MySerializableType(SerializationInfo info, StreamingContext context)
  {
    _serializableField = info.GetInt32("serializableField");
  }

  public virtual void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
  {
    info.AddValue("serializableField", _serializableField);
  }
}

' This is the correct implementation

[Serializable()]
public class MySerializableType: ISerializable
{

  private int _serializableField;

  public int SerializableField
  {
    get
    {
      return _serializableField;
    }
  }

  public MySerializableType(int serializableField)
  {
    _serializableField = serializableField;
  }

  protected MySerializableType(SerializationInfo info, StreamingContext context)
  {
    _serializableField = info.GetInt32("serializableField");
  }

  public virtual void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
  {
    info.AddValue("serializableField", _serializableField);
  }
}

Related Rules

Call base class methods on ISerializable types

Implement ISerializable correctly

Implement ISerializable for serializable classes that expose events

Implement Serialization Constructor

Implement serialization methods correctly

Include instance fields in the serialization/deserialization process

Mark all non-serializable fields with "NonSerialized" attribute

Provide deserialization methods for optional fields


Provide 'default:' for each 'switch' statement

Rule ID: US00026

Problem

Switch statement does not have a default statement.

Rule Description

Often, the case statements in a switch are the only logical options, so a default statement should be added to catch any options that are outside the accepted range of inputs.

- OR -

Handle gracefully situations where some additional values are defined in an enum and the switch has case statements for only the earlier values of the enum.

Correcting Violations

The rule provides the following auto-correct options:
  • Add default statement.

Rule Instances

Instances of this rule in the built-in profile:
  • Provide 'default:' for each 'switch' statement.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[C#]

// This code will trigger the rule violation
      public class SomeClass
      {
        void method (int i)
        {
          switch (i) // Violates the rule
          {
            case 0:
              System.Console.WriteLine ("Zero");
              break;
          }
        }
      }

// This is the correct implementation
    public class SomeClass
    {
      void method (int i)
      {
        switch (i)
        {
          case 0:
            System.Console.WriteLine ("Zero");
            break;
          default: // Fixed
            break;
        }
      }
    }

Related Rules

Avoid empty methods.

Avoid control statements with empty bodies.


Provide deserialization methods for optional fields

Rule ID: US00014

Problem

Type marked with System.SerializableAttribute attribute, and has a field with System.Runtime.Serialization.OptionalFieldAttribute attribute but does not provide de-serialization event handling methods (with OnDeserializingAttribute and OnDeserializedAttribute attributes).

Rule Description

System.Runtime.Serialization.OptionalFieldAttribute specifies that a field can be missing from a serialization stream. This attribute allows to specify that new fields in a serializable type are ignored by the System.Runtime.Serialization.Formatters.Binary.BinaryFormatter or the System.Runtime.Serialization.Formatters.Soap.SoapFormatter. Field marked with System.Runtime.Serialization.OptionalFieldAttribute attribute is serialized, but it is ignored on de-serialization and retains the default value. De-serialization event handlers should be created to initialize the field with the value, which depends from other deserialized values.

This rule is similar to FxCop rule 'Provide deserialization methods for optional fields', CheckId CA2239

Correcting Violations

The rule provides the following auto-correct options depending from detected violation:
  • Add two deserialization event handling methods by applying System.Runtime.Serialization.OnDeserializedAttribute and System.Runtime.Serialization.OnDeserializingAttribute attributes.
  • Add deserialization event handling method by applying System.Runtime.Serialization.OnDeserializedAttribute attribute.
  • Add deserialization event handling method by applying System.Runtime.Serialization.OnDeserializingAttribute attribute.
  • Initialize field in the deserialization event handling method marked with System.Runtime.Serialization.OnDeserializedAttribute attribute.

Rule Instances

Instances of this rule in the built-in profile:
  • Provide deserialization methods for optional fields.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

[Visual Basic]

' This code will trigger the rule violation

Imports System
Imports System.Reflection
Imports System.Runtime.Serialization

<Assembly: AssemblyVersionAttribute("2.0.0.0")>
Namespace SampleLibrary

  ' Violation: Type SerializationEventsSample does not provide
  ' de-serialization event handling methods
  <SerializableAttribute> _
  Public Class SerializationEventsSample

    <OptionalFieldAttribute(VersionAdded := 2)> _
    Private _optionalField As String = "Default Value"

    Public ReadOnly Property OptionalField() As String
      Get
        Return _optionalField
      End Get
    End Property

  End Class

End Namespace

' This is the correct implementation

Imports System
Imports System.Reflection
Imports System.Runtime.Serialization

<Assembly: AssemblyVersionAttribute("2.0.0.0")>
Namespace SampleLibrary

  <SerializableAttribute> _
  Public Class SerializationEventsSample

    <OptionalFieldAttribute(VersionAdded := 2)> _
    Private _optionalField As String = "Default Value"

    Public ReadOnly Property OptionalField() As String
      Get
        Return _optionalField
      End Get
    End Property

    <OnDeserializingAttribute> _
    Private Sub OnDeserializing(context As StreamingContext)
      _optionalField = "Default Value"
    End Sub

    <OnDeserializedAttribute> _
    Private Sub OnDeserialized(context As StreamingContext)
      ' Initialize _optionalField with the value, which depends from
      ' other deserialized values.

      ...

    End Sub

  End Class

End Namespace

[C#]

// This code will trigger the rule violation

using System;
using System.Reflection;
using System.Runtime.Serialization;

[assembly:AssemblyVersionAttribute("2.0.0.0")]
namespace SampleLibrary
{

  // Violation: Type SerializationEventsSample does not provide
  // de-serialization event handling methods
  [SerializableAttribute()]
  public class SerializationEventsSample
  {

    [OptionalFieldAttribute(VersionAdded = 2)]
    private string _optionalField = "Default Value";

    public string OptionalField
    {
      get
      {
        return _optionalField;
      }
    }

  }

}

// This is the correct implementation

using System;
using System.Reflection;
using System.Runtime.Serialization;

[assembly:AssemblyVersionAttribute("2.0.0.0")]
namespace SampleLibrary
{

  [SerializableAttribute()]
  public class SerializationEventsSample
  {

    [OptionalFieldAttribute(VersionAdded = 2)]
    private string _optionalField = "Default Value";

    public string OptionalField
    {
      get
      {
        return _optionalField;
      }
    }

    [OnDeserializingAttribute()]
    private void OnDeserializing(StreamingContext context)
    {
      _optionalField = "Default Value";
    }

    [OnDeserializedAttribute]
    private void OnDeserialized(StreamingContext context)
    {
      // Initialize _optionalField with the value, which depends from
      // other deserialized values.

      ...

    }

  }

}

Related Rules

Call base class methods on ISerializable types

Implement ISerializable correctly

Implement ISerializable for serializable classes that expose events

Implement Serialization Constructor

Implement serialization methods correctly

Include instance fields in the serialization/deserialization process

Mark all non-serializable fields with "NonSerialized" attribute


Remove unused parameters

Rule ID: US00019

Problem

A method includes parameter, which is not used in the body of the method.

Rule Description

Don't reserve one or more parameters for future use. Define only the parameters that are actually currently used by the method. If additional parameters are required in future versions of the class, you can later define an overloaded method. Unused parameters may degrade performance.

This rule is similar to FxCop rule 'Review unused parameters', CheckId CA1801

Correcting Violations

The rule provides the following auto-correct options:
  • Comment out unused parameter.

Rule Instances

Instances of this rule in the built-in profile:
  • Remove unused parameters.


Asp.Net Rules

This section will guide you through the set of Xaml Rules.

Click on any of the links below to go directly to the corresponding rule.

Property should be set once

Xaml file should be well-formed

Xaml member should not be empty

Xaml object should contain specified member


Property should be set once

Rule ID: XA00005

Problem

Xaml file contains property which is set more than once.

Rule Description

Properties can only be set once in XAML. There are three different ways to set a property in XAML: setting it as an XML attribute, as a property element, or as content.

This rule is similar to FxCop rule 'Properties can only be set once', CheckId MSX1000

Correcting Violations

The rule provides the following auto-correct options:
  • Set the property only once.

Rule Instances

Instances of this rule in the built-in profile:
  • Property should be set once.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<Button Width="50">
    <Button.Width>50</Button.Width>
    Click
</Button>

<!-- This is the correct implementation -->

<Button>
    <Button.Width>50</Button.Width>
    Click
</Button>

- OR -

<Button Width="50">
    Click
</Button>


Xaml should be well-formed

Rule ID: XA00003

Problem

Xaml file is not well-formed.

Rule Description

All XAML documents must well-formed XML documents that use a defined set of element names. I.e. each property of a Document Information Item must be of correct type, and XAML must have tree structure.

This rule is similar to FxCop rules 'XAML validation problem', CheckId MSX1001

Correcting Violations

The rule provides the following auto-correct options:
  • Please check the resolution for the exact issue manually.

Rule Instances

Instances of this rule in the built-in profile:
  • Xaml should be well-formed.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<MyObject>
    <MyObject.FirstProperty>First Value
    <MyObject.SecondProperty>Second Value
    <MyObject.ThirdProperty>Third Value
</MyObject>

<!-- This is the correct implementation -->

<MyObject>
    <MyObject.FirstProperty>First Value</MyObject.FirstProperty>
    <MyObject.SecondProperty>Second Value</MyObject.SecondProperty>
    <MyObject.ThirdProperty>Third Value</MyObject.ThirdProperty>
</MyObject>


Xaml member should not be empty

Rule ID: XA00002

Problem

Xaml file contains object and its member is empty.

Rule Description

Xaml object should always define specified member.

This rule is similar to the following FxCop rules:
  • 'Sequence activity should have child activities', CheckId XWF1000
  • 'Delay duration has not been set', CheckId XWF1003
  • 'Parallel activity should have atleast one branch', CheckId XWF1004

Correcting Violations

The rule provides the following auto-correct options:
  • Specifiy value for member manually.
  • Remove empty member from object manually.

Rule Instances

Instances of this rule in the built-in profile:
  • ControlTemplate object should define TargetType member.
  • Delay object should define Duration member.
  • Parallel object should define Branches member.
  • Sequence object should define Activities member.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<Activity x:Class="Workflow1"
  xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Sequence>
    <WriteLine Text="Start Delay" />
    <Delay />
    <WriteLine Text="["Delay has completed at " + DateTime.Now.ToString()]" />
  </Sequence>
</Activity>

<!-- This is the correct implementation -->

<Activity x:Class="Workflow1"
  xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Sequence>
    <WriteLine Text="Start Delay" />
    <Delay Duration="[new TimeSpan(0, 0, 5)]" />
    <WriteLine Text="["Delay has completed at " + DateTime.Now.ToString()]" />
  </Sequence>
</Activity>


Xaml object should contain specified member

Rule ID: XA00001

Problem

Xaml file contains object without member specified.

Rule Description

This rule can be used to check if Xaml object has all required members specified.

This rule is similar to the following FxCop rules:
  • 'Assign activity does not have a To specified', CheckId XWF1001
  • 'Assign activity does not have a Value specified', CheckId XWF1002

Correcting Violations

The rule provides the following auto-correct options:
  • Specifiy member for object manually.

Rule Instances

Instances of this rule in the built-in profile:
  • Assign object should define To member.
  • Assign object should define Value member.

Example

The following example show code that triggers the rule violation.

<!-- This code will trigger the rule violation -->

<Activity
  x:TypeArguments="x:Int32"
  x:Class="Add"
  xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <x:Members>
    <x:Property Name="Operand1" Type="InArgument(x:Int32)" />
    <x:Property Name="Operand2" Type="InArgument(x:Int32)" />
  </x:Members>
  <Sequence>
    <WriteLine Text="[Operand1.ToString() + " + " + Operand2.ToString()]" />
    <Assign x:TypeArguments="x:Int32" Value="[Operand1 + Operand2]">
      <Assign.To></Assign.To>
    </Assign>
  </Sequence>
</Activity>

<!-- This is the correct implementation -->

<Activity
  x:TypeArguments="x:Int32"
  x:Class="Add"
  xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <x:Members>
    <x:Property Name="Operand1" Type="InArgument(x:Int32)" />
    <x:Property Name="Operand2" Type="InArgument(x:Int32)" />
  </x:Members>
  <Sequence>
    <WriteLine Text="[Operand1.ToString() + " + " + Operand2.ToString()]" />
    <Assign x:TypeArguments="x:Int32" Value="[Operand1 + Operand2]">
      <Assign.To>
        <OutArgument x:TypeArguments="x:Int32">
          <ArgumentReference x:TypeArguments="x:Int32" ArgumentName="Result" />
        </OutArgument>
      </Assign.To>
    </Assign>
  </Sequence>
</Activity>


EULA

EULA
For the latest version please see our online copy of the EULA.

END-USER LICENSE AGREEMENT FOR CodeIt.Right

This End-User License Agreement ("EULA") is a legal agreement between you and vbCity.com, LLC dba SubMain ("SubMain"). "You" as the terms is used herein, includes individuals as well as business entities, such as corporations, limited liability companies, and partnerships. If you do not agree to the terms of this EULA, do not install, copy, or use the SOFTWARE PRODUCT.

SOFTWARE PRODUCT LICENSE

The SOFTWARE PRODUCT is protected by copyright laws and international copyright treaties, as well as other intellectual property laws and treaties. The SOFTWARE PRODUCT is licensed, not sold, and is subject to the terms of this EULA. The SOFTWARE PRODUCT is licensed on per-user basis.

GRANT OF LICENSE

SubMain grants you the following rights provided that you comply with all terms and conditions of this EULA:

1. SubMain grants you a personal, nonexclusive, royalty-free license to install and use the SOFTWARE PRODUCT for design, development, and testing purposes. You may install and use the SOFTWARE PRODUCT on up to 3 computers so long as you are the only individual using the SOFTWARE PRODUCT. This does not include build servers - separate user license is required for build server.

2. You may not reverse- engineer, decompile, or disassemble the SOFTWARE PRODUCT, except and only to the extent that such activity is expressly permitted by applicable law notwithstanding this limitation.

3. You may not use the SOFTWARE PRODUCT in whole or any part of it as a library for your products and tools.

4. You may not rent or lease the SOFTWARE PRODUCT.

5. You may not redistribute this package.

6. You may not upload this package to any 3rd party web sites or services.

7. You may permanently transfer all of your rights under this EULA, provided you retain no copies, you transfer all of the SOFTWARE PRODUCT (including all component parts, the media and printed materials, any upgrades and this EULA), and the recipient agrees to the terms of this EULA. If the SOFTWARE PRODUCT is an upgrade, any transfer must include all prior versions of the SOFTWARE PRODUCT.

8. No rights are granted for use of illegal copies of the SOFTWARE PRODUCT, or for legal copies of the SOFTWARE PRODUCT obtained by unlawful means.

TRIAL LICENSE

If the SOFTWARE PRODUCT has been provided to you under a time-limited trial license for evaluation or other purposes, your right to use the SOFTWARE PRODUCT ends after the time period specified in the trial. After the trial period has elapsed, you must either stop using the SOFTWARE PRODUCT, or purchase a legal license and obtain your registration key. You must not change the system date or take other steps to circumvent time restrictions while using the trial version of the SOFTWARE PRODUCT. Such an attempt will cause the termination of the trial period, and your rights to use the SOFTWARE PRODUCT.

LIMITATION OF LIABILITY

NO LIABILITY FOR CONSEQUENTIAL DAMAGES. To the maximum extent permitted by applicable law, in no event shall SubMain or its suppliers be liable for any damages whatsoever (including, without limitation, damages for loss of business profit, business interruption, loss of business information, or any other pecuniary loss) arising out of the use of, or inability to use, this software product, even if SubMain has been advised of the possibility of such damages.

COPYRIGHT

Copyright © 2002-2019 SubMain. All rights reserved.

The spellchecker engine is based on modified version of NetSpell which is Copyright (c) 2003, Paul Welter All rights reserved.


Support Options

We are committed to providing our customers with the highest level of support possible. To that end, we have multiple support mechanisms in place.

If you are looking to retrieve the purchased product license codes or latest product version licenses (for the eligible users), please visit the MyAccount page.

1. Check the Tutorials and How To articles

2. Search our Knowledge Base

3. Post in our Support Community

4. Post a Support Ticket

To reach our support/sales staff fill in our Online Support Form or email us at customer-service@submain.com


Do not disable custom errors

Rule ID: AN00007

Problem

Mode attribute of the <customErrors> element in Web.config contains Off value.

Rule Description

Never use the Off value for the mode attribute of the <customErrors> element in Web.config.

Disabling custom errors also for remote users would let ASP.NET expose important details to the outside, including pieces of source code. The RemoteOnly default value should be used instead. The RemoteOnly value specifies that rich ASP.NET error information are shown to the local host, and that custom errors are shown only to the remote clients.

Correcting Violations

The rule provides the following auto-correct options:
  • Set mode attribute of the <customErrors> element in Web.config to RemoteOnly value.

Rule Instances

Instances of this rule in the built-in profile:
  • Do not disable custom errors.

Example

The following examples show code that triggers the rule violation as well as the correct implementation.

' This code in Web.config file will trigger the rule violation

  <customErrors mode="Off" />

' This is the correct implementation

  <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.aspx">
    <error statusCode="403" redirect="NoAccess.htm" />
    <error statusCode="404" redirect="FileNotFound.htm" />
    <error statusCode="500" redirect="InternalError.htm" />
  </customErrors>

Related Rules

Always define a global error handler


Purchasing PrettyCode.Print

PrettyCode.Print is distributed as Shareware. You can freely download and try it for 30 days. If you find it useful and decide to keep it over 30-day evaluation period, you should pay the registration fee. See also License agreement <-- link to the License Agreement article.

How To Order

Please visit our ordering web site:

http://www.prettycode.com/order

Note: If corporate policy requires you to purchase through a reseller and you have an existing relationship with one, please have the reseller contact sales@prettycode.com on your behalf. We will work with your reseller so you get the software you need.

Got Questions?

If you have questions about purchasing PrettyCode.Print or would like a volume licensing quote please send e-mail to sales@prettycode.com or talk to our Sales representative in Live!Help Chat

Licensing

PrettyCode.Print is licensed to use only on a single computer by one individual. If the individual alternately uses several computers (for example, a laptop and a desktop), you may install PrettyCode.Print on each of them as long as it is never used on more than one simultaneously or by more than one individual.

Upgrade policy

Minor upgrades which include bug fixes and minor improvements are free. Major upgrades may carry an upgrade fee.


Summary Report API Overview

Quick Start

Quick 1 minute CodeIt.Right walkthrough

Quick 1 minute CodeIt.Right walkthrough
Click to play

Presentation 1: Introduction to CodeIt.Right Features

Here is where we show main CodeIt.Right functions and options

Presentation 1: Introduction to CodeIt.Right Features
Click to play

Presentation 2: ISerializable Pattern - example

One of many scenarios when CodeIt.Right helps to diagnose issues early and implement coding patterns correctly.

Presentation 2: ISerializable Pattern - example
Click to play
© 2002-2017 SubMain. All rights reserved.