Disabling OBSOLETE error in C# - c#

I am using the Microsoft TFS API and one of the properties on one of the interfaces has been marked as Obsolete and it instructs me to use a different property. Unfortunately the property the API wants me to use is used by TFS2010 and not TFS2008.
I have tried doing this:
#pragma warning disable 0612, 0618
request.CommandLineArguments = arguments;
#pragma warning restore 0612, 0618
But I still get the error that CommandLineArguments is obsolete. Is there anyway to suppress this?
EDIT
Unfortunately this is not showing up as a 'Warning as Error', in fact Treat Warning's As Error's is turned off in my project. Here is a screen cap of the offending code as well as the error list
EDIT 2:
After using ILSpy the CommandLineArguments property looks like this in the TFS2010 API:
[Obsolete("This property has been deprecated. Please remove all references. To pass command line arguments to MSBuild.exe, set the ProcessParameters property.", true)]
string CommandLineArguments
{
get;
set;
}
Unfortunately I don't think there is a way to tell the compiler to ignore the error that the Obsolete attribute is causing.
EDIT 3
As #Peter Ritchie points out this value could be set via reflection. As I thought through this problem though my guess is that if Microsoft set the property to throw an exception even if you did set it via reflection I doubt that the value would be referenced anywhere.

Visual Studio 2015
Build failing due to [Obsolete]?
This would only occur if "Treat Warnings As Errors" is enabled, and there is a method with the [Obsolete] attribute.
Method 1: Downgrade error to warning
Add <WarningsNotAsErrors>612,618</WarningsNotAsErrors> in the .csproj file (repeat for all sections):
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<WarningLevel>4</WarningLevel>
<WarningsNotAsErrors>612,618</WarningsNotAsErrors>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
If dealing with many .csproj files, see Appendix A: Notepad++ for search and replace.
Method 2: Ignore error in file
Note: This method is not recommended, because it hides the warnings for methods marked [Obsolete]. We still want to see a list of
all calls to obsolete methods so we can upgrade them.
Use #pragma warning disable 612,618
Method 3: Ignore error in project
Note: This method is not recommended, because it hides the warnings for methods marked [Obsolete]. We still want to see a list of
all calls to obsolete methods so we can upgrade them.
Edit the project (repeat for all sections):
Method 4: Ignore error in project
Note: This method is not recommended, because it hides the warnings for methods marked [Obsolete]. We still want to see a list of
all calls to obsolete methods so we can upgrade them.
Manually edit your .csproj to disable warnings for specific errors. Add the tag <NoWarn>612,618</NoWarn> (repeat for all sections):
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<NoWarn>612,618</NoWarn>
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
Appendix A: Notepad++ for search and replace
Have a lot of files? No problem!
Open all .csproj files in NotePad++, then:
Find: <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
Replace: <TreatWarningsAsErrors>true</TreatWarningsAsErrors>\n\t<WarningsNotAsErrors>612,618</WarningsNotAsErrors>

Following works for me:
#pragma warning disable 612,618
request.CommandLineArguments = arguments;
#pragma warning restore 612,618
notice no leading 0 in the numbers
EDIT:
Okay, your assembly has the "true" argument in the ObsoleteAttribute constructor. This means you can't use the property and not get an error.
If you can't re-write your code to avoid using this property, you'll have to invoke the property setter via reflection, for example:
request.GetType().GetProperty("Number").SetValue(request, arguments, null);
and getting is similar:
(string)request.GetType().GetProperty("CommandLineArguments").GetValue(request, null);

Just in case anyone else stumbles on this.
If you mark the method in which you set the property as Obsolete and DONT mark it as true the compiler will ignore the interior error throwing your higher level warning instead which you can ignore.
IE
[Obsolete("Cause it aint",false)]
public void Foo(object arguments)
{
request.CommandLineArguments = arguments;
}

Related

Visual Studio 2022 custom template [duplicate]

I'm using C# 10 new feature File-scoped namespace declaration.
I have old code like this
namespace SampleCode
{
public class MyClass
{
}
}
I'm moving this code to
namespace SampleCode;
public class MyClass
{
}
But I have a bunch of warnings : IDE0160: Convert to block scoped namespace
How do I make sure people will have warnings only with old syntax ?
To control the code style in editorconfig use this line :
To enforce this style
namespace SampleCode
{
public class MyClass
{
}
}
Add this line in .editorconfig
# IDE0160: Convert to block-scoped namespace
csharp_style_namespace_declarations = block_scoped:warning
To enforce this style
namespace SampleCode;
public class MyClass
{
}
Add this line in .editorconfig
# IDE0160: Convert to file-scoped namespace
csharp_style_namespace_declarations = file_scoped:warning
Update 2022-01-27 (all scenarios setup)
JetBrains Rider does support the dotnet_diagnostic.IDE* syntax starting from version 2021.3.2.This simplifies the setup for all possible scenarios into this:
EditorConfig
csharp_style_namespace_declarations = file_scoped
dotnet_diagnostic.IDE0161.severity = error
CSProj
<PropertyGroup>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
</PropertyGroup>
This will cover all the scenarios. Original answer below. Still worth to read it.
There are several different settings which you should control based on your desired state, used IDEs and workflow.
They are described in this article which I strongly recommend to read before you start building .editorconfig for your project.
Here is a summary for File-scoped, Block-scoped usings, respectively.
EditorConfig/CSproj setup for File-scoped usings
Visual Studio (error on violation)
EditorConfig
csharp_style_namespace_declarations = file_scoped
dotnet_diagnostic.IDE0161.severity = error
Note
Syntax option = rule:severity will be deprecated, sooner or later.
JetBrains Rider (error on violation)
EditorConfig
csharp_style_namespace_declarations = file_scoped:error
Note
Rider doesn't support dotnet_diagnostic.IDE* syntax.
CLI build e.g., CI/CD pipeline
EditorConfig
csharp_style_namespace_declarations = file_scoped
dotnet_diagnostic.IDE0161.severity = error
CSProj
<PropertyGroup>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
</PropertyGroup>
Recommended setup
EditorConfig
csharp_style_namespace_declarations = file_scoped:error
dotnet_diagnostic.IDE0161.severity = error
CSProj
<PropertyGroup>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
</PropertyGroup>
Note
Is the current .NET EditorConfig syntax a mess? Definitely.
EditorConfig/CSproj setup for Block-scoped usings
Visual Studio (error on violation)
EditorConfig
csharp_style_namespace_declarations = block_scoped
dotnet_diagnostic.IDE0160.severity = error
Note
Syntax option = rule:severity will be deprecated, sooner or later.
JetBrains Rider (error on violation)
EditorConfig
csharp_style_namespace_declarations = block_scoped:error
Note
Rider doesn't support dotnet_diagnostic.IDE* syntax.
CLI build e.g., CI/CD pipeline
EditorConfig
csharp_style_namespace_declarations = block_scoped
dotnet_diagnostic.IDE0160.severity = error
CSProj
<PropertyGroup>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
</PropertyGroup>
Recommended setup
EditorConfig
csharp_style_namespace_declarations = block_scoped:error
dotnet_diagnostic.IDE0160.severity = error
CSProj
<PropertyGroup>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
</PropertyGroup>

IronPython: Error when launching .py script from c#

I'm running into a similar problem as this guy: IronPython : Microsoft.Scripting.SyntaxErrorException: 'unexpected token '=''
Unfortunately, there we no answers on that thread.
This is my code:
var engine = Python.CreateEngine();
var scope = engine.CreateScope();
try
{
engine.ExecuteFile(String.Concat(Directory.GetParent(Environment.CurrentDirectory).Parent.Parent.FullName, "\\Client.py"), scope);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
And then here's the .py (that doesn't do anything yet, really):
#imports
import os
import tempfile
#Test
print("Here we go.")
The abomination to get the full path for my python file was an attempt to check if it got the path wrong or couldn't find the file, wasn't the case but I left it there. Debugger shows that the path is correct. However, it always fails on engine.ExecuteFile(...). and catches an exception that, according to the debugger is null. I got this error:
Microsoft.Scripting.SyntaxErrorException
and then goofed around with settings, changing Tools > Options > Debugging > General > "Enable just my Code" from checked to unchecked which lead to me not getting the SyntaxErrorException anymore but instead it's now this, but it still fails at the same line, with an exception that is still null:
IronPython.Runtime.Exceptions.ImportException in Microsoft.Dynamic.dll
At this point I don't know if I made a step in the right direction or went one back. Can anyone help with this?
EDIT: I need to correct this. There currently is an exception that states: "No module named os" instead of being just null which makes sense considering the exception type.
I moved the Lib folder to my project folder and had the search path extended by it like this:
String projectPath = Directory.GetParent(Environment.CurrentDirectory).Parent.Parent.FullName;
var engine = Python.CreateEngine();
var libs = new[]
{
String.Concat(projectPath, "\\Lib")
};
var pySP = engine.GetSearchPaths();
foreach (String resource in libs)
{
pySP.Add(resource);
}
following this thread: IronPython: No module named json.
Then I undid the changes I made to the debugging settings, and lastly added NuGet packages. Maybe there is now redundance with the added search path and the newly added packages but I am not willing to test my luck and undo any of the changes. Here is my .csproj file, for anyone who might need it when in the same position:
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UseWPF>true</UseWPF>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="IronPython" Version="2.7.10" />
<PackageReference Include="IronPython.Interpreter" Version="2.7.4" />
<PackageReference Include="IronPython.StdLib" Version="2.7.10" />
</ItemGroup>
</Project>

Is there an option to deactivate style cop rule without making an "GlobalSuppressions.cs" file?

We use StyleCop Analyzer in our project. One of my tasks is to deactivate a few rules, but without creating a GlobalSuppressions.cs file.
I found solutions, but only with creating this file, so I'm confused.
To suppress a warning outside of GlobalSuppressions.cs, you can either:
Use comments (remember to restore the warnings out of the scope!)
#pragma warning disable IDE0052 // Remove unread private members
private readonly Object _obj;
#pragma warning restore IDE0052 // Remove unread private members
or use the SuppressMessage attribute in place
[SuppressMessage("Code Quality", "IDE0052:Remove unread private members", Justification = "<Pending>")]
private readonly Object _obj;
If you want to disable them globally, you can use an .editorconfig file at the root of your solution.
root = true
[*.{cs,vb}]
dotnet_diagnostic.IDE0052.severity = none
You can also configure a Ruleset file, but this is now deprecated.
In your csproj:
<PropertyGroup>
<CodeAnalysisRuleSet>File.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
and then create File.ruleset as your per your need. It looks roughly like
<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Microsoft Managed Recommended Rules" Description="These rules focus on the most critical problems in your code, including potential security holes, application crashes, and other important logic and design errors. It is recommended to include this rule set in any custom rule set you create for your projects." ToolsVersion="10.0">
<Rules AnalyzerId="Microsoft.CodeQuality.Analyzers" RuleNamespace="Microsoft.CodeQuality.Analyzers">
<Rule Id="CA1056" Action="None" />
</Rules>
</Rules>
</RuleSet>
More details at https://learn.microsoft.com/en-us/visualstudio/code-quality/use-roslyn-analyzers?view=vs-2019#rule-sets

How to deal with Code Contracts warning CC1036 when using string.IsNullOrWhiteSpace?

I have the following code contract:
public void F(string x)
{
Contract.Requires(!string.IsNullOrWhiteSpace(x));
throw new NotImplementedException();
}
When compiling, I get the following warning:
warning CC1036: Detected call to method 'System.String.IsNullOrWhiteSpace(System.String)' without [Pure] in contracts of method [...]
How to deal with it?
What's odd, is that I'm also using string.IsNullOrEmpty, which isn't marked as [Pure] as well, in other contracts and the rewriter does not have a problem with that.
My Contract Rewriter's Version is 1.9.10714.2.
This is the relevant part from the implementation of String class I'm using (retrieved from metadata):
#region Assembly mscorlib.dll, v4.0.0.0
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\mscorlib.dll
#endregion
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace System
{
// Summary:
// Represents text as a series of Unicode characters.To browse the .NET Framework
// source code for this type, see the Reference Source.
[Serializable]
[ComVisible(true)]
public sealed class String : IComparable, ICloneable, IConvertible, IEnumerable, IComparable<string>, IEnumerable<char>, IEquatable<string>
{
// [...]
//
// Summary:
// [...]
public static bool IsNullOrEmpty(string value);
//
// Summary:
// [...]
public static bool IsNullOrWhiteSpace(string value);
Why is the [Pure] attribute missing?
Here we have two points:
1. Why is the [Pure] attribute missing in string class for IsNullorWhiteSpace function?
2. How to resolve the CC1030 warning issue?
I will try to discuss both.
1. Why is the [Pure] attribute missing? It's not missing, metadata does not seem to be showing this.
This may not be marked as Pure in previous version of .NET FX as, they were saying:
Yes, we need to make our checker sensitive to the disable pragma...
Sigh.
We currently don't have that implemented, but I've added it to our
work list.
Refer to the 5 year old discussion here.
But this has been marked as Pure in latest FX (4.6.1), Refer to .NET Framework 4.6.1, the new string class code.
[Pure]
public static bool IsNullOrWhiteSpace(String value) {
if (value == null) return true;
for(int i = 0; i < value.Length; i++) {
if(!Char.IsWhiteSpace(value[i])) return false;
}
return true;
}
Then Why CC1036?
This warning "CC1036" is from CodeContracts, developers have open this issue yesterday only (refer here).
Now why metadata is not spitting up Pure attributes, this is a different question, like for Equals method, Pure is added but only SecuritySafeCritical is displayed in metadata code.
[SecuritySafeCritical]
public static bool Equals(String a, String b, StringComparison comparisonType);
The same problem applies to Invariant(). Given the following code, the
same warnings are displayed:
private string testString = "test";
[ContractInvariantMethod]
private void TestInvariant()
{
Contract.Invariant(!string.IsNullOrWhiteSpace(testString));
}
How to resolve?
As others are also suggesting, create another method, mark it as Pure and call this in your contract condition.
Going through a pure delegate will make the warning go away. Predicate<T> is already marked pure, so you can just use that to work around the bug:
// Workaround for https://github.com/Microsoft/CodeContracts/issues/339
public Predicate<string> IsNullOrWhiteSpace = string.IsNullOrWhiteSpace;
public void F(string x)
{
Contract.Requires(!IsNullOrWhiteSpace(x));
throw new NotImplementedException();
}
Although kind of ugly, you can wrap the function string.IsNullOrWhiteSpace with an extension method and mark this new function as Pure.
I just encountered the exact same problem. I'm using VS2015, so it does not seem to be related to VS version. I also tested the exact same code on .NET 4.0, 4.5.1 and 4.6, without getting the warning.
Like others have commented before me, the IsNullOrWhiteSpace is marked as [Pure] in .NET 4.6.1, and additionally should by default be considered pure by Code Contracts because it is in the System.String namespace. This makes it look like a bug, so I have submitted an issue to Code Contracts about this, so with some luck we will see an official answer soon.
While we wait for an answer, it is possible (like #Jaco suggests) to wrap it in an extension method and mark it as Pure yourself. Optionally, you can suppress the warning for that particular method like this:
[SuppressMessage("Microsoft.Contracts", "CC1036", Justification = "string.IsNullOrWhiteSpace is Pure")]
... but note that this will also suppress this warning from other Contract definitions in the same method.
Actually, this is a problem with the way .NET 4.6+ is compiled. See this GitHub pull request.
I was able to work around this by modifying the following file(s):
For Visual Studio 2013:
C:\Program Files (x86)\Microsoft\Contracts\MsBuild\v12.0\Microsoft.CodeContracts.Targets
For Visual Studio 2015:
C:\Progarm Files (x86)\Microsoft\Contracts\MsBuild\v14.0\Microsoft.CodeContracts.Targets
In both files, ensure the <Otherwise> child element of the first <Choose> element has the following content shown below:
...
<Choose>
<When Condition="'$(TargetFrameworkIdentifier)' == 'Silverlight'">
...
</When>
<Otherwise>
<Choose>
<When Condition="'$(TargetFrameworkVersion)' == 'v4.0">
<PropertyGroup>
<CodeContractsReferenceAssemblyLibPath>$(CodeContractsInstallDir)Contracts\.NETFramework\v4.0</CodeContractsReferenceAssemblyLibPath>
</PropertyGroup>
</When>
<When Condition="'$(TargetFrameworkVersion)' == 'v4.5'">
<PropertyGroup>
<CodeContractsReferenceAssemblyLibPath>$(CodeContractsInstallDir)Contracts\.NETFramework\v4.5</CodeContractsReferenceAssemblyLibPath>
</PropertyGroup>
</When>
<When Condition="'$(TargetFrameworkVersion)' == 'v4.5.1'">
<PropertyGroup>
<CodeContractsReferenceAssemblyLibPath>$(CodeContractsInstallDir)Contracts\.NETFramework\v4.5</CodeContractsReferenceAssemblyLibPath>
</PropertyGroup>
</When>
<When Condition="'$(TargetFrameworkVersion)' == 'v4.5.2'">
<PropertyGroup>
<CodeContractsReferenceAssemblyLibPath>$(CodeContractsInstallDir)Contracts\.NETFramework\v4.5</CodeContractsReferenceAssemblyLibPath>
</PropertyGroup>
</When>
<When Condition="'$(TargetFrameworkVersion)' == 'v4.6'">
<PropertyGroup>
<CodeContractsReferenceAssemblyLibPath>$(CodeContractsInstallDir)Contracts\.NETFramework\v4.5</CodeContractsReferenceAssemblyLibPath>
</PropertyGroup>
</When>
<When Condition="'$(TargetFrameworkVersion)' == 'v4.6.1'">
<PropertyGroup>
<CodeContractsReferenceAssemblyLibPath>$(CodeContractsInstallDir)Contracts\.NETFramework\v4.5</CodeContractsReferenceAssemblyLibPath>
</PropertyGroup>
</When>
<Otherwise>
<PropertyGroup>
<CodeContractsReferenceAssemblyLibPath>$(CodeContractsInstallDir)Contracts\.NETFramework\v3.5</CodeContractsReferenceAssemblyLibPath>
</PropertyGroup>
</Otherwise>
</Choose>
</Otherwise>
</Chose>
...
After making these changes to these files (per the GitHub pull request referenced above), I no longer received Code Contracts static analysis warnings for the use of String.IsNullOrWhiteSpace.
It should be noted that the referenced pull request has been merged into the main code for Code Contracts up on GitHub; they just haven't made a new release containing these changes yet.
Also, for those concerned about changing "system files", don't be. When the next version of Code Contracts is released, it will install updated versions of these files--and hopefully the changes will be included, and all will be right with the world. (Unless, of course, the changes aren't included--in which case, you'll be coming back here to reference this post to make those changes again ;) lol.)

How to suppress a StyleCop warning?

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.
Here's what you need:
[SuppressMessage("Microsoft.StyleCop.CSharp.OrderingRules", "SA1202:ElementsMustBeOrderedByAccess")]
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.
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.
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.
Go to Solution Explorer
Go to your project
Expand references
Expand Analyzers
Expand StyleCop.Analyzers
Right click on a particular rule which you want to disable at a global (project) level
Set Rule Set severity -> Select None
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.")]
Cant you just remove the rule instead of soiling your code?
Same goes for FxCop...
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!
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>
Alternatively you could move the code in regions into partial classes. Then the issue with the stylecop rule will go away.
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.
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

Categories