Print a message in the build output (that is not a warning) - c#

At build time, I'd like to be able to print a message to the build output window without having it be classified as a warning. I.e. In the Visual Studio Error List, I would want it to display only if you had the "Messages" filter turned on.
So, I want identical functionality to
#warning Warning Message
But I don't want it to be classified as a warning.
Context:
I have a lot of projects that currently generate a lot of warnings. What I'd like to do first is prevent new warnings from being introduced. So, I've:
Turned on "Warnings as Errors"
Gone through and used #pragma warning disable/restore to eliminate existing warnings.
However, for the warnings I disabled, I'd like to print out a message indicating that there is a warning here that needs to be investigated (since I haven't yet investigated what needs to be done for these warnings). For example, many of the warnings are "obsolete" type warnings, where we do need to go and do some work at some point. So, I don't want these warnings to disappear.
Ideally, I'd do something like this:
#pragma warning disable 0618
#message Existing Warning: 0618: IObsoleteInterface is obsolete.
class MyClass : IObsoleteInterface
#pragma warning restore 0618
I'm open to other approaches of dealing with the issue.

According to MSDN you cannot extend #pragma: http://msdn.microsoft.com/en-us/library/x74w198a.aspx
But if ErrorList isn't strict requirement, you can work around this: you may use comments to highlight things important to you.
If you add special token at the begining of your comment, you'll be able to track it in TaskList window.
So, your code will look like:
#pragma warning disable 0618
//TODO: Existing Warning: 0618: IObsoleteInterface is obsolete.
class MyClass : IObsoleteInterface
#pragma warning restore 0618
And after that, if you'll open View -> Task List -> select Comments in dropdown, you'll see your comment there.
There are 3 predefined tokens: TODO, HACK and UNDONE - and you can add your own like MESSAGE and change it's priority to make your code look similar to what you initially expect:
#pragma warning disable 0618
//MESSAGE: Existing Warning: 0618: IObsoleteInterface is obsolete.
class MyClass : IObsoleteInterface
#pragma warning restore 0618
More information about tokens you will find here: http://msdn.microsoft.com/en-us/library/zce12xx2(v=vs.100).aspx
Worth to mention that if you use Resharper, it has another tool for TODO's. I'll find it here: ReSharper -> Tools -> To-do Items

You should have a look at the csc task's WarningsNotAsErrors parameter. When the list of the "acceptable" warnings are specified to this parameter with TreatWarningsAsErrors=true you should get your existing warnings logged while new ones will show up as errors.
Ofcourse this is not exactly existing versus new warnings but a way to work with exact warning numbers that you are comfortable with leaving in.
But my first suggestion would be to just fix these. Once hidden outside of build they rarely get addressed.

If you are using "Premium" or "Ultimate" edition of Visual Studio, it has a feature of code analysis using Rule Set.
For any project when you right click & go to properties, select Code Analysis Tab, it has various out of box settings like treating warning as error, disabling some of the warning.
You can configure warning to be ignored or treated as error. You can use out of box Microsoft rule sets or alternatively you can build a custom ruleset as per your requirements (which is not very difficult & worked for my requirement).
To enable code analysis for managed code:
Select a project in Solution Explorer.
On the Project menu, click Properties.
Click Code Analysis.
Select Enable Code Analysis on Build (defines CODE_ANALYSIS constant).
For details on configuring Code Analysis, please visit:
http://seesharper.wordpress.com/2010/04/02/code-analysis-in-team-build-2010/
For building Custom Rulesets:
http://msdn.microsoft.com/en-us/library/dd264974.aspx
http://blogs.msdn.com/b/codeanalysis/archive/2010/03/26/how-to-write-custom-static-code-analysis-rules-and-integrate-them-into-visual-studio-2010.aspx
For Learning about Ruleset & code analysis:
http://msdn.microsoft.com/en-us/library/dd264996.aspx

Related

How to disable compiler warnings in only generated code without editing file(s)

I have some generated code that has a bunch of compiler warnings. I want to disable them in the generated file, but keep those warnings in the rest of the project so they can be fixed. I'm using Visual Studio 2019 Community Edition, with the generated files coming from Entity Framework and other NuGet packages.
I want to do this without changing the files, so I won't get the warnings back if they get regenerated. I also don't want to disable the warnings project wide, since they are normally useful warnings. I also don't want to edit the NuGet packages, since that would either require not upgrading them as newer releases are available or possibly having to make changes to the new version.
I've already done plenty of reading, but evidently posting the links is "too much", so I've removed them. Look in the edit history if you want to see them.
The file in question is a Reference.cs for a Connected Service. It has the namespace of Proxy.ProvisioningService and this one file contains a couple of dozen classes. I also have a couple of Entity Framework migration files that have the same problem in a completely different solution.
I have a GlobalSuppressions.cs file that I'd like to add the CS1591 (specifically) to, but my current entry isn't working. Other entries work for other warnings and I've tried variations of the below code to work, including trying to match the format of the other entries, but nothing is working so far. I've changed the "Build" from "Compile", removed the MessageId, changed Scope to be "module", "assembly", and "namespaceanddescendants", and I've tried a couple different ways to set the Target.
[assembly: SuppressMessage("Build", "CS1591:Missing XML comment for publicly visible type or member", Justification = "Generated code", MessageId = "CS1591", Scope = "namespaceanddescendants", Target = "Proxy.ProvisioningService")]
In one of the off-site links, it suggests that I right-click the error, go to Suppress -> In Suppression File, but that's not a listed option. Is that a clue that I can't do it in the GlobalSuppressions.cs file?
I've tried to have Visual Studio 2019 Community Edition automatically suppress the warning by the menu item Analyze -> Build And Suppress Active Issues -> For Project, but that just added a bunch of #pragma directives to the file, which would have to be replaced if the file was regenerated, which I want to avoid.
One of the linked answers suggested writing a script to add the #pragma directives on compile, but that script seems like a hack to me. I'd rather just not edit the generated code at all.
I also don't want to put it in the Project -> Properties -> Build -> Suppress Warnings section, since I want the hand written code to still throw these warnings.
Another SE/SO answer suggests using the GeneratedCodeAttribute attribute to prevent warning from generated files. Unfortunately, my file already has this and it's still throwing the warnings.
Another suggestion was to turn off warnings for these generated files:
To suppress warnings for generated code in a project
Right-click the project in Solution Explorer and then click Properties.
Choose the Code Analysis tab.
Select the Suppress results from generated code check box.
Unfortunately, this option is already selected and not suppressing the CS1591 warning.
So my actual question is:
How can I suppress warnings, specifically CS1591, from generated code files without editing them and without suppressing the warning throughout the whole project?
You said that you consider using a script to update the files to add #pragma a hack, but I can't think of another solution.
I think that you can do this easily with a MSBuild Task by adding something like this to your .csproj file:
<Target Name="DisableWarnings" BeforeTargets="CoreCompile">
<ItemGroup>
<AutoGeneratedFiles Include="**/*.Designer.cs" />
</ItemGroup>
<WriteLinesToFile File="%(AutoGeneratedFiles.FullPath)"
Condition="!$([System.IO.File]::ReadAllText(%(AutoGeneratedFiles.FullPath)).StartsWith("#pragma warning"))"
Lines="$([System.String]::Concat("#pragma warning disable 1591",$([System.IO.File]::ReadAllText(%(AutoGeneratedFiles.FullPath))),"#pragma warning restore 1591"))"
Overwrite="true"
Encoding="Unicode" />
</Target>
The SuppressMessage attribute works only for code analysis warnings. Its summary goes:
Suppresses reporting of a specific code analysis rule violation, allowing multiple suppressions on a single code artifact. Does not apply to compiler diagnostics.
If there is a file name pattern identifying the generated code, compiler warnings can be suppressed in the generated code using EditorConfig. For example, this is how I disabled the warnings for using obsolete code elements in my generated code -- I still need to suppress the warnings in manually written code using #pragma.
[*.generated.cs]
dotnet_diagnostic.CS0612.severity = none
dotnet_diagnostic.CS0618.severity = none
For a WCF connected service, the simplest solution is probably to not have the warning in the first place.
Since the CS1591 warning is about public types, you could use the dotnet-svcutil tool to generate your Reference.cs file and pass the --internal option so that the generated types are internal instead of public, thus getting rid of CS1591 altogether.
For other tools that generate code, look for a similar option to generate internal types instead of public types. For example, you would use the --assemblyVisible option with the xscgen tool.

Omitting the "The variable X is declared but never used" from VS build output

Is it possible to omit only the missing variable warnings like: The variable 'ex' is declared but never used?
I don't care about these variables.
Assuming this warning is occurring when you are building a C# project (there are very similar ones for other languages), then you can disable it in your project's "Properties".
Right-click the project in the Solution Explorer, and select "Properties" (at or near the bottom of the pop-up menu). Then, in the properties display, select the "Build" tab from the list on the left, and add 168 (you may need to enter the full warning code, CS0168) in the "Suppress Warnings" edit box:
Of course, a better way to avoid the warning is not to declare variables that you don't use! However, I understand that this is sometimes useful during developmental and debug stages: and note, this setting is configuration-specific, so you could suppress the warning in your "Debug" build but allow it in your (final) "Release" build.
If you are using another language (like C++ or C), you can suppress the warning in a very similar manner. I can modify this answer, if that it the case.

How can I disable a specific warning for a C# project in VS2012?

I am trying to generate partial XML documentation during my build process for a C# project in VS2012. When I check the XML documentation file option in Project->Properties->Build, I get a build warning for each public member that lacks documentation. Since we compile with warnings as errors, this blocks the build.
This question suggests getting past this by disabling certain warnings, but I can't figure out how to do that in VS2012! The MSFT documentation here only goes up to VS2010 and only covers VB. How can I disable these warnings at the project level in C#/VS2012?
For the project level go to Project -> Properties -> Build tab
If you want to disable the warning to some code section, try this :
#pragma warning disable XXX,XXX
//your code
#pragma warning restore XXX,XXX
Read about #pragma warning
The warning you're getting has a number (e.g. CS2000), so what you need to do is right-click on the project, go to the Build tab, and add that warning to the Suppress warnings text box. You can subsequently suppress more than one by separating them with a comma (e.g. CS2000,CS2001).
Just add NoWarn block in the csproj:
<PropertyGroup>
<NoWarn>1998;1999</NoWarn>
</PropertyGroup>
You can open the project properties and enter comma separated warning numbers you want to suppress into the Suppress Warnings textbox on the Build tab.
It's in the same place as Visual Studio 2010. In the project properties, on the Build tab, called Suppress warnings.
Try adding _ALLOW_KEYWORD_MACROS to Current Property Pages, Your Project, C/C++, Preprocessor, Preprocessor Definitions

Ignoring generated files when using "Treat warnings as errors"

We have started a new project but also have this problem for an existing project. The problem is that when we compile with a warning level of 4 we also want to switch on
'Treat all warnings as errors'
We are unable to do this at the moment because generated files (in particular reference.cs files) are missing things like XML comments and this generates a warning, we do not want to suppress the xml comment warnings totally out of all files just for specific types of files (namely generated code).
I have thought of a way this could be achieved but am not sure if these are the best way to do this or indeed where to start :) My thinking is that we need to do something with T4 templates for the code that is generated such that it does fill in XML documentation for generated code.
Does anyone have any ideas, currently I'm at well over 2k warnings (its a big project) :(
You can selectively disable warnings with a pragma:
// Disable warning messages 4507 and 4034.
#pragma warning( disable : 4507 34 )
If you can emit such warnings (or an #include) in the generated code files, you're done.
Alternatively, you can disable them globally on the command-line for the compiler:
/wd4326 disables compiler warning C4326.
Then re-enable them (via a header file) in the files you want them for:
// Report warning 4326 as an error.
#pragma warning( error : 326 )
Finally, you can set different compile options for each source file by altering the Properties in the project file. Personally I find that a maintenance nightmare, but there are times you have no choice.
Edit: I see that your source files are C#, not C++.
Using the C# command-line:
to suppress CS0028, you could specify /nowarn:28.
Unfortunately, /warnaserror makes all warnings errors.
I've written a PowerShell script that calls svcutil and then wraps the auto-generated code with the #pragma directives to ignore the missing xml, but still allows me to regenerate as needed.
$outFile = 'generatedCode_fromSVCUTIL.cs'
svcutil '..\XML Schema\myXsd.xsd' /dataContractOnly /n:'*,MyNamespace.GeneratedCode' /language:C# /importxmltypes /out:$outFile
# -----------------------------------------------------
# Exempt this file from XML documentation requirements
Write-Host 'Wrapping ', $outFile, ' in #pragma 1591 flags'
$a = Get-Content $outFile
# Set up pragma lines for enabling and disabling the XML doc warning
$disableWarning = '#pragma warning disable 1591'
$restoreWarning = '#pragma warning restore 1591'
# wrap the generated code in the pragma tags
Set-Content $outFile –value $disableWarning, $a, $restoreWarning
Write-Host 'Done.'
In VS 2010 you can right-click on the service reference, select 'Configure Service Reference...' and change the access modifier from Public to Internal.
This may of course not be appropriate for your particular solution but the warnings are not applicable to Internal methods and you can still re-generate the service reference.
For C# you can simply place a
#pragma warning disable 1591
at the beginning of the reference.cs file. Then the warning concerning missing XML documentation will not be issued.
But you have to do this every time, the file is regenerated (i.e. when your service definition changes). I'm not aware of any way to influence the code generation (I'm not sure if they use T4 templates or where these might be located ...)
A couple of thoughts.
1) Do you have the autogenerated tag in your file header (comments at the top of the file), like this:
// <auto-generated>
// This file is auto-generated...
// </auto-generated>
This tag is important (the contents are not), as some tools will skip such files (e.g. StyleCop can be configured to ignore these files).
2) If you are autogenerating code why not autogenerate at least some XML comments? I can understand that you don't want to spend a lot of time documenting code that probably won't ever be read, but when debugging code I often find myself dropping in to some autogenerated proxy and even a simple comment can be helpful, even if it just says "autogenerated code" :)
Edit
3) You can also suppress warnings by adding the pragmas to the build options (right click on the project, choose properties, choose the Build tab). This is more convenient than adding to code. Try adding 1591;1574;1587 to the Suppress Warnings box.
4) You could go in to the Code Analysis tab in the Project Properties and uncheck "Treat Warning as Error" for specific warnings that are causing you problems.
Obviously both these are global settings, they don't just pick on the autogenerated files.

Suppress compiler warnings using aspnet_compiler at the command line

Is there a switch to suppress specific compiler warnings when using the aspnet_compiler.exe warnings at the command line?
I've tried fixing the errors myself, rather than ignoring them - they are for events that are defined by never used. I simply commented out the events, but this caused other problems! It's as if they are used but the compiler doesn't recognise that (which seems unlikely).
I'm calling the compiler from the command line, and I'm using Visual Web Developer Express, which does not have the detailed build options in the Project Properties Build dialog that can be found in the full version of Visual Studio.
In the end I used
#pragma warning disable [warning no]
some code that triggers a warning
#pragma warning enable [warning no]
in my code, as per http://msdn.microsoft.com/en-us/library/441722ys.aspx. This works fine and although needs entering once for each compiler warning, it seems to be the best fit.

Categories