61

I'm using StyleCop and want to suppress some warning which does not suit my style. I prefer to have solution for

1) in-line code suppressing
2) global setting suppressing

I've searched the internet but still not sure how to do the suppressing.

For method 1), They said to add the lines:

[assembly: SuppressMessage("Microsoft.Design", "SA1202:All private methods must be placed after all public methods", Scope = "namespace", Target = "Consus.Client.ClientVaultModule.Services.OnlineDetection")]

But they do not say where and which namespace to be used.

For method 2), they said to use GlobalSuppress file but it seems not easy to search for a how-to do it at the moment.

Please help.

[Edited] In my case, I have the warning about SA1202: All private methods must be placed after all public methods which is bothering since I group my related codes into regions. I want to suppress those warning for just some certain methods.

sorak
  • 2,607
  • 2
  • 16
  • 24
Nam G VU
  • 33,193
  • 69
  • 233
  • 372
  • 6
    Ideally, right-click, 'suppress' (or right-click, 'fix'). But StyleCop was written by masochists, so you have to tediously fix all its problems by hand. If ever there were work designed to be done by a machine, this is it. What a waste. – Colonel Panic Apr 02 '15 at 09:49

12 Answers12

50

Here's what you need:

[SuppressMessage("Microsoft.StyleCop.CSharp.OrderingRules", "SA1202:ElementsMustBeOrderedByAccess")]
Colonel Panic
  • 132,665
  • 89
  • 401
  • 465
Jason Allor
  • 501
  • 3
  • 2
  • 12
    How did you deduce those two magic strings? All OP posted was the code 'SA1202'. I have a similar problem (code 'SP0100') and I can't deduce the corresponding strings. – Colonel Panic Jan 07 '13 at 14:40
  • @Colonel Panic: You can get the first string from the StyleCop warning message when you run it. E.g. "SA1202: CSharp.OrderingRules: blahblah". Then open the StyleCop settings file with the editor and search with the SA code to find the actual rule and it's short name. – Hirvox Feb 20 '13 at 09:54
  • 6
    if you go to http://www.stylecop.com/docs/SA1202.html (or similar page urls for the other warnings) you can find very clear details of the suppress message syntax. – Seph Sep 24 '13 at 10:16
  • @Seph Alas, doesn't work for my Style Cop albatross 'SP0100'. The web page at http://www.stylecop.com/docs/SP0100.html is 404 not found. – Colonel Panic Nov 18 '13 at 14:20
  • @ColonelPanic that's because the `SPxxxx` rules come from StyleCop+ and not original StyleCop, hence you won't find StyleCop+ documentation on the StyleCop page. It seems StyleCop+ suppression rules are not as well documented as they are for StyleCop – Seph Nov 19 '13 at 05:05
  • So how can I silence it? – Colonel Panic Nov 19 '13 at 10:14
  • @ColonelPanic `[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCopPlus.StyleCopPlusRules", "SP0100:AdvancedNamingRules", Justification = "Your justification here"]` The `StyleCopPlus.StyleCopPlusRules` part is the fully qualified name of the StyleCopPlus analyzer class, which inherits from `StyleCop.SourceAnalyzer`, you can find that class's name using VisualStudio's or MonoDevelop's assembly browser, or Reflector. It's a pity we don't have right-click->ignore like we have for FxCop. Note I had issues copy-pasting this comment from SO (hidden unicode chars) so you shoud copy it by hand. – Suzanne Soy May 21 '14 at 10:37
  • 2
    their document is updated here: https://github.com/DotNetAnalyzers/StyleCopAnalyzers/tree/master/documentation – Hunter Tran Mar 24 '17 at 06:19
21

An example of inline suppression would be similar to this - examine the namespaces in the code compared to the suppression

namespace Soapi
{
        ///<summary>
        ///</summary>
        ///<param name = "message"></param>
        ///<param name = "statusCode"></param>
        ///<param name = "innerException"></param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object)")]
        public ApiException(string message, ErrorCode statusCode, Exception innerException)
            : base(String.Format("{0}\r\nStatusCode:{1}", message, statusCode), innerException)
        {
            this.statusCode = statusCode;
        }

A global supression file is a file in the root of your project named GlobalSuppressions.cs and might look like this:

// This file is used by Code Analysis to maintain SuppressMessage 
// attributes that are applied to this project. 
// Project-level suppressions either have no target or are given 
// a specific target and scoped to a namespace, type, member, etc. 
//
// To add a suppression to this file, right-click the message in the 
// Error List, point to "Suppress Message(s)", and click 
// "In Project Suppression File". 
// You do not need to add suppressions to this file manually. 

[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object,System.Object)", Scope = "member", Target = "Soapi.ApiException.#.ctor(System.String,Soapi.ErrorCode,System.String,System.Exception)")]

And you can generate this code automatically by right-clicking on the warning.

Ilmari Karonen
  • 49,047
  • 9
  • 93
  • 153
Sky Sanders
  • 36,396
  • 8
  • 69
  • 90
  • 3
    I've tried right-clicking the warning (in the Error/Warning list) but no context menu item allow me to supress it. I'm using VS 2010. Do you know why? – Nam G VU Jul 20 '10 at 07:17
  • @Nam - Not sure, the example I cite is using vs2008. let me fire up 2010 and take a peek. – Sky Sanders Jul 20 '10 at 07:35
  • @poet: I've post my related question here http://stackoverflow.com/questions/3287957/how-to-supress-stylecop-warning-sa1201-all-methods-must-be-placed-after-all-pro – Nam G VU Jul 20 '10 at 07:50
  • @Nam - having some issues with vs 2010 - will take me a few hours. If you haven't gotten an good answer by then I will report back. But really it should be quite similar process. till then.. – Sky Sanders Jul 20 '10 at 08:09
  • @Nam - check the image - as I suspected, the behavior is same. what are you seeing? – Sky Sanders Jul 20 '10 at 17:12
  • @poet: Here is the screenshot captured what I see http://dl.dropbox.com/u/6194904/right%20click%20StyleCop%20warning%20but%20no%20Supress%20options.png – Nam G VU Jul 21 '10 at 11:20
  • 1
    hmmm, i guess you cannot use context menu on StyleCop warnings. Those that I show are from FxCop. But - the supression syntax is the same. So I guess your issue is finding the namespace of the rule you are breaking so that you can manually supress, right? – Sky Sanders Jul 21 '10 at 12:01
  • @Code Poet: You're absolutely right! I don't know how to put in the parameter for the suppressing commands. – Nam G VU Jul 26 '10 at 10:52
9

Starting with StyleCop 4.3.2, it is possible to suppress the reporting of rule violations by adding suppression attributes within the source code.

Rule Suppressions http://stylecop.soyuz5.com/Suppressions.html

but it says -

Global Suppressions

StyleCop does not support the notion of global suppressions or file-level suppressions. Suppressions must be placed on a code element.

akjoshi
  • 15,374
  • 13
  • 103
  • 121
  • Same info is provided here too - http://blogs.msdn.com/b/sourceanalysis/archive/2009/08/10/rule-suppressions.aspx – akjoshi Sep 19 '11 at 12:56
7

If you've installed StyleCop, you can right-click your project and there will be a StyleCop option. Click this and you'll see you can prevent certain rules from even running against your project. Moreover, you can create a separate rules file to share between different projects. This means you can configure the rules once the way you want them and then share that configuration between all your projects.

For individual overrides, SuppressMessage is the way to go.

Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
6

Read the admonition from Style Cop, looking for the alphanumeric code. In your case 'SA1202'. Then browse to the corresponding page on the Style Cop website. Change the URL as appropriate https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1202.md

Copy the line labelled 'How to Suppress Violations'. Paste the attribute above the class about which Style Cop moans

[SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1202:ElementsMustBeOrderedByAccess", Justification = "Reviewed.")]
DaggeJ
  • 2,094
  • 1
  • 10
  • 22
Colonel Panic
  • 132,665
  • 89
  • 401
  • 465
6
  1. Go to Solution Explorer
  2. Go to your project
  3. Expand references
  4. Expand Analyzers
  5. Expand StyleCop.Analyzers
  6. Right click on a particular rule which you want to disable at a global (project) level
  7. Set Rule Set severity -> Select None
Akshunya
  • 153
  • 1
  • 2
  • 8
3

Cant you just remove the rule instead of soiling your code?

Same goes for FxCop...

leppie
  • 115,091
  • 17
  • 196
  • 297
2

You can disable the rules you don't want in Settings.StyleCop file, which is in the project root folder. You will need the namespace that contains the rule, which can be found here: http://stylecop.soyuz5.com/StyleCop%20Rules.html

Settings.stylecop file code for your reference:

<StyleCopSettings Version="105">
  <Analyzers>
    <Analyzer AnalyzerId="StyleCop.CSharp.LayoutRules">
      <Rules>
        <Rule Name="ElementsMustBeSeparatedByBlankLine">
          <RuleSettings>
            <BooleanProperty Name="Enabled">False</BooleanProperty>
          </RuleSettings>
        </Rule>
      </Rules>
      <AnalyzerSettings />
    </Analyzer>
  </Analyzers>
</StyleCopSettings>
2

1. In your case, correct SuppressMessage attribute should like like the following:

[SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1202:ElementsMustBeOrderedByAccess")]
private void SomeMethod()
{
}

Note that you can place it on any other element (e.g, on the class - then all similar violations in the entire class will be supressed).

I also agree that it's quite unobvious what to write in these fields.

Actually, the first one should be the fully qualified name of StyleCop analyser class and could be found from the source code (e.g. from here). The second one should start with rule code, then colon and the name of the rule enumeration (luckily, it always looks like the rule name displayed in the Settings Editor, but with no whitespaces).

2. Regarding suppressing rules "globally" - why don't just turn them off via Settings Editor? Settings files are inherited through the file system, so you could easily have one "main" settings file at the "top" of your folder structure, and some other files (holding the "difference" from main) with exceptions made for some projects, if you want so (like described here).

Good luck!

Oleg Shuruev
  • 1,339
  • 8
  • 10
1

Alternatively you could move the code in regions into partial classes. Then the issue with the stylecop rule will go away.

Philip Smith
  • 2,741
  • 25
  • 32
1

In addition to the helpful answers already in place:

If you suppress a warning in the suppression file GlobalSuppressions.cs, you can edit that [assembly: SuppressMessage(StyleCop...blabla line and entirely remove the Scope=... and Target=... tags. That makes the suppression global in the project.

Stefan Bormann
  • 643
  • 7
  • 25
0

The README.md for the StyleCop.Analyzers NuGet package used by Visual Studio 2015+ contains a link to the documentation for the rules. The documentation for each rule contains a "How to suppress violations" section. For the SA1202 rule, the options are:

[SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1202:ElementsMustBeOrderedByAccess", Justification = "Reviewed.")]

and

#pragma warning disable SA1202 // ElementsMustBeOrderedByAccess
#pragma warning restore SA1202 // ElementsMustBeOrderedByAccess
Ryan Prechel
  • 6,592
  • 5
  • 23
  • 21