suppress warning for generated c# code - c#

I have turned on "Treat warnings as errors" for my VS project which mean that I get errors for missing documentation (nice reminder for this particular project).
However, part of the code is generated by a custom tool which does not insert xml documentation so I'm looking for away to ignore the missing xml documentation for the generated code only, not for the entire project. I have no influence on the actual file generated and cannot really insert anything in the file (as it is regenerated frequently by the tool) so I looking for something existing outside the generated file (the classes that are generated are partial, if that helps)

The best way to avoid having warnings or Code Analysis error on generated code is to decorate your generated classes with the GeneratedCodeAttribute and make the code file ends with the *.generated.cs pattern.
If your code files also have a file header, you should had these tags:
//----------------------
// <auto-generated>
// Tool description
// </auto-generated>
//----------------------
This is not mandatory, but if you have code file header it is a good practice.
This way, FxCop and other tools like StyleCop will not analyse your code anymore.
What is abnormal is that your code generation tool is not decortating your code elements with the attribute mentioned above. Try to look if there is an option to enable in your tool settings or contact the developing team.
EDIT:
Does the generated classes are partial classes and do the actual classes name and number changes often? Because if the generated code content is not moving a lot, what you can do is simply create another code file and just declare the generated partial class to decorate them with the GeneratedCodeAttribute. One time it saved my life (and my time!).

EDIT: See comments indicating that this doesn't work with C# 4. I'm not clear whether it worked in earlier versions of the compiler. The C# 4 spec makes this pretty clear though. Section 2.5.8.1 states:
A #pragma warning restore directive restores all or the given set of warnings to the state that was in effect at the beginning of the compilation unit. Note that if a particular warning was disabled externally, a #pragma warning restore (whether for all or the specified warning) will not re-enable that warning.
Jeff has a workaround in a blog post - basically to reprocess autogenerated code as part of the build.
As Tom says, you can add an "ignore" to the whole project (Build / Suppress Warnings - enter 1591 as the warning number) - but then you can restore the warning yourself at the top of each of your non-generated files:
#pragma warning restore 1591
It's pretty ugly, but it works (I've just tested it).

The best you will be able to do in this is suppress the particular warning in the project that contains the generated code. You can do this in the Project Properties on the Build tab. It's not ideal, but short of putting the pragmas in the generated code, it is the best you can do.

Related

"CA 1852 Type X can be sealed because it has no subtypes in its containing assembly and is not externally visible" error while compiling

I tried to compile a .NET app I got from GitHub and got a
"CA 1852 Type X can be sealed because it has no subtypes in its containing assembly and is not externally visible" error. This seems to be a code style error instead of a real error.
To try to suppress it, I added the 1852 line to the .csproj file:
<PropertyGroup>
<NoWarn>$(NoWarn);1591</NoWarn>
<NoWarn>$(NoWarn);1852</NoWarn>
</PropertyGroup>
plus this to the .editorconfig file:
dotnet_diagnostic.CS1852.severity = none
'dotnet_diagnostic' might be incorrect. Both didn't work.
So what worked was adding this above the error line:
#pragma warning disable CA1852
My question is what triggered this type of error to show up? .editorconfig doesn't have anything for 1852, unless it's a computer wide setting on my machine or something?
Also, how do I suppress it for the whole solution or project?
CA1852 is not a compiler error or warning. It is a static code analysis warning where the analysis is done by "Rosyln". If it is actually preventing you from compiling code, then you have WarningsAsErrors turned on.
Regardless, you can follow the advice or suppress the warning. All of #jmcilhinney's comments are correct and relevant, and the fact that the warning is new is likely the trigger.
To my knowledge, there is no built-in global way to suppress a warning solution wide. That said, you can effect the same result by including a "standard" bit of configuration stored in a separate file. It's still not technically global because each .csproj will need to be modified to import the settings.
To do that, create a file such as CommonStuff.xml with
<PropertyGroup>
<NoWarn>1852</NoWarn>
</PropertyGroup>
in it. Then modify each of your .csproj to include this file:
<Import Project="$(SolutionDir)\CommonStuff.xml" />
In the above, I chose SolutionDir as that is probably the best place to add this file and reference it from all the projects. Other paths can be used; see Common macros... in the Microsoft documentation. The other good choice would be ProjectDir if that's the level of granularity you need.

Why am I not getting warnings for missing xml documentation on public API?

My C# project (a Unity Package library) is not getting warnings on missing xmldoc of public classes, properties or methods.
I want to ensure all of my public API has XML documentation in code, but I've noticed there's undocumented public methods with no warnings. The csproj for my lib was basically copied from the csproj auto-generated by Unity, with a few changes. I'm not suppressing any warnings related to documentation as far as I can tell.
What I wanted was basically CS1591:
Missing XML comment for publicly visible type or member 'Type_or_Member'
The DocumentationFile compiler option was specified, but one or more constructs did not have comments.
It seems I have to make sure the <DocumentationFile> tag is specified to a non-empty file path (and WarningLevel 4 is not disabled) in the csproj.
<DocumentationFile>some/path/AssemblyName.xml</DocumentationFile>
I hadn't specified it before because I don't actually need documentation in a separate xml if my lib will be distributed as source code (Unity already picks the docs from code comments). I would need it if I had to compile the dll.
After specifying the DocumentationFile to some temp path, VSCode / Omnisharp will emit warnings like CS1591, CS0419.

Why are warnings CS0108 & CS0114 *NOT* errors by default in Visual Studio?

Warning CS0108 trips when a variable is declared with the same name as a variable in a base class.
Warning CS0114 is the equivalent for methods.
Both flag up as a warning but not an error. Compilation continues and the executable can be run.
But the risk is a logic error or bug where the wrong one is invoked.
This is extremely dangerous in live production environments.
It's also very "non-obvious" when debugging: the code looks like it's doing the right thing when stepped through but is not. The bug can take forever to identify in heavily abstracted/inherited code-bases.
Surely the "new" keyword exists for a reason and (even more surely) usage should be enforced by a compile error - not just a warning.
But this is not so. You have to set it up by hand on each project in a solution; it's not even possible to enforce solution-wide.
And I haven't yet found a way to make this the default behaviour for new solutions.
Why?
Visual Studio by default considers as an error everything that makes a program unable to compile. Since these considerations do not affect the compilation but only the quality of the code, they are considered warnings. But as Styxxy has pointed out, you can treat any warning you like as an error.
You can actually set the warnings to be errors solution wide (kind of). Only restriction is that the solution has to be in the top level directory.
You can add a Directory.Build.targets file next to your solution to set up the warnings to be treated as errors. This file will automagically be loaded and used in the build process (see more in the docs: https://learn.microsoft.com/en-us/visualstudio/msbuild/customize-your-build?view=vs-2019#directorybuildprops-and-directorybuildtargets)
<Project>
<PropertyGroup>
<WarningsAsErrors>$(WarningsAsErrors);CS0108;CS0114</WarningsAsErrors>
</PropertyGroup>
</Project>
As for why it is by default a warning and not an error (my thoughts): errors are things that break the build and you can't compile the project/solution, while warnings are to warn the user about a potential mistake.

How to disable RECS* warnings in with Roslyn compiler

After updating to C# 6 and VS2015 in some projects I have started to see a lot of build warnings like these:
RECS0119 'string.Compare' is culture-aware
RECS0017 Possible compare of value type with 'null'
RECS0063 'StartsWith' is culture-aware and missing a StringComparison argument
RECS0060 'IndexOf' is culture-aware and missing a StringComparison argument
RECS0027 Operator 'is' can be used
RECS0133 Parameter name differs in base declaration
Here is the screenshot of one of the suggestions:
These are valid suggestions for code improvements, but these are all coming from a class that is installed by a nuget package (PetaPoco, I'm looking at you!) and I don't want to modify that file in any way. And I don't want to see these warnings.
I have tried using #pragma warning disable RECS0060 and variations, but could not make the warnings disappear. Is there a way to disable these Roslyn code improvements warnings on per-file basis? Don't want to hide them for all classes as these come useful sometimes.
In VS 2017 you can right click the error number in the errors window and find an entry that should read something like "suppress" (sorry, working in german). There you can choose to suppress the message with a pragma in code or project wide via a file named "GlobalSuppressions.cs". Both works fine.

Can I prevent the CLR from optimizing away debugging information?

I've written an abstract base class for unit tests that sets up just enough environment for our tests to run. The class exposes some of the runtime environment bits as properties whose types vary test by test (the property types are type arguments specified in the inheriting, concrete test class).
This is all well and good, except a co-worker noticed that he can't view any of the class' properties in the debugger. Turns out the reason is that he had no fields defined in his inheriting class, and the CLR optimized something or other away, so the debugger couldn't display the properties. Is it possible to prevent this in the base class somehow, or do I have to resort to telling everyone they need to define at least one field which is used somewhere during the tests?
Edit:
Sounds like a likely culprit should be the optimization/debug settings. That said, I'm building the app from Visual Studio in Debug mode, I've double-checked that all projects are set for a debug build, and none of the projects in this solution have the Optimize flag set.
Perhaps it would also be relevant to note that I'm using MSTest and the Visual Studio test runner.
Edit 2:
By "can't view properties" I'm referring to when I evaluate the property in Quickwatch and get a red exclamation mark and a text "Could not evaluate expression" error text. And lest you think I'm entirely off base with my suspicions, adding an instance field that gets initialized in the test initialize method makes the problem go away...
Edit 3:
Checked the build output. I notice that the compiler is invoked with these options:
/debug+
/debug:full
/optimize-
/define:DEBUG,TRACE
I should think that would be enough to stop this from happening, but there you go. :)
I've encountered this same problem before, and it's invariably due to the fact that Debug mode has been turned off in some way. Try checking each of the following:
The current build configuration for the solution and the appropiate project(s) is Debug.
In the Build tab of the property pages, the Optimize code checkbox is unchecked.
If this is all correct, then I recommend you paste the text written to the Output window here so can we can potentially spot any more unusual cause of the issue.
Make sure your arent trying to debug your release build.
All of these compile settings set behind these configurations.
The debug version is one for debugging ;-)
In my case, the project configuration was correct, but my code was the result of a decompilation from ILSpy, and it had assembly attributes like the following:
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
Removing these attributes fixed the debugger...

Categories

Resources