.NET 6 Code analyzer CodeAnalysisTreatWarningsAsErrors breaking - visual-studio

We are trying to enable to .NET 6 Code Analyzer on our .NET 472 projects.
In most projects we have WarningsAsErrors set to true. We dont want to CA warnings to report as an error, so we added CodeAnalysisTreatWarningsAsErrors as false.
When doing so, all the CA warnings are no longer reported
We now use the following settings
<PropertyGroup>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisLevel>latest-recommended</AnalysisLevel>
<CodeAnalysisTreatWarningsAsErrors>false</CodeAnalysisTreatWarningsAsErrors>
<WarningsNotAsErrors>$(WarningsNotAsErrors);CS8073;CS8882;CS8887;CS8848</WarningsNotAsErrors>
</PropertyGroup>
Without the settings, we have 0 warnings. With these settings, only a few additional CS warnings are triggered, the ones we had to add in the WarningsNotAsErrors
If i remove the CodeAnalysisTreatWarningsAsErrors property and set TreatWarningsAsErrors to false, i get 1700 CA warnings in our code base.
I would expect to see these 1700 warnings with above settings as well.
When i set CodeAnalysisTreatWarningsAsErrors to true, i get 1700 errors.
I am using this in my global.json file
{
"sdk": {
"version": "6.0.300",
"rollForward": "latestFeature"
}
}
and have sdk's 6.0.300 and 6.0.401 installed, along with VS 17.2
Why is CodeAnalysisTreatWarningsAsErrors breaking our code analysis scan?
Any advice would be helpful.
Edit: adding images
VS shows it wants to treat them as warning:

I set TreatWarningsAsErrors and CodeAnalysisTreatWarningsAsErrors to true or false for Combinatorial testing. Below are several test results.
scenario 1
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
This returns all CS errors.
scenario 2
<TreatWarningsAsErrors>false </TreatWarningsAsErrors>
This returns all CS warnings.
scenario 3
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisLevel>latest-recommended</AnalysisLevel>
scenario 4
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisLevel>latest-recommended</AnalysisLevel>
<CodeAnalysisTreatWarningsAsErrors>true</CodeAnalysisTreatWarningsAsErrors>
Both 3 and 4 returns CS and CA errors.
scenario 5
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisLevel>latest-recommended</AnalysisLevel>
<CodeAnalysisTreatWarningsAsErrors>false </CodeAnalysisTreatWarningsAsErrors>
This returns CS errors and CA warnings.
scenario 6
<TreatWarningsAsErrors>false </TreatWarningsAsErrors>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisLevel>latest-recommended</AnalysisLevel>
<CodeAnalysisTreatWarningsAsErrors>false</CodeAnalysisTreatWarningsAsErrors> (Or it can be removed)
This returns CA and CS warnings.
From your description,
I would expect to see these 1700 warnings with above settings as well.
My understanding is that if you want to see warnings, you can follow scenario 6. I’m afraid you can’t see these 1700 warnings with above settings as well.
<TreatWarningsAsErrors>true</TreatWarningsAsErrors> <CodeAnalysisTreatWarningsAsErrors>false</CodeAnalysisTreatWarningsAsErrors>)
But I'm not sure exactly what your question is from your last paragraph.
If there is any misunderstanding, please feel free to let me know.
UPDATE1/30/2023
If scenario 5 doesn't work in your machine, i suggest you check below setting 1 and setting 2 or try method 3.
1 Custom analysis scope
By default, compiler diagnostics run on all open documents, and, in Visual Studio 2022 and later, Roslyn analyzer diagnostics run on the currently active document only.You can custom analysis scope.For example:
2 set warning levels
3 Run code analysis manually
Error list will soon refresh with all code analysis diagnostics.Please refer to doc: Run code analysis manually
UPDATE 2/2/2013
Steps below are my process of creating demo project and getting the warnings. You can follow those steps and see if warnings are show.
1 create C# console app project named CodeAnalyzeTest.
2 copy code below to Program.cs and install package Newtonsoft.Json
using Newtonsoft.Json;
namespace CodeAnalyzeTest
{
public class Account
{
public string Name { get; set; }
public string Email { get; set; }
public DateTime DOB { get; set; }
}
public class Program
{
static void Main(string[] args)
{
Account account = new Account
{
Name = "John Doe",
Email = "john#nuget.org",
DOB = new DateTime(1980, 12, 20, 0, 0, 0, DateTimeKind.Utc)
};
string json = JsonConvert.SerializeObject(account, Formatting.Indented);
Console.WriteLine(json);
}
}
}
3 edit project file and add PropertyGroup
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisLevel>latest-recommended</AnalysisLevel>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<CodeAnalysisTreatWarningsAsErrors>false</CodeAnalysisTreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.2" />
</ItemGroup>
</Project>
4 build the project and watch error list.You'll get CA and CS warnings.
If you still get no warnings after following steps above, please provide Minimal, Reproducible Example that we can easily understand and use to reproduce the problem.

Related

Problems with running Xamarin for Visual Studio 2017

Okay, I've been searching and searching and it seems that people have somewhat similar scenarios concerning my problem, however, none of the solutions presented even offer a sound solution. I've recently installed Visual Studio 2017. I went on to test the Xamarin Android Emulator by creating an app (named "Try") with absolutely nothing on it. Mind you, this is a fresh install of Visual Studio 2017 with JDK 1.8.0_152 and Android 7.1.1 (25). Right off the bat, the build failed. I cleaned the solution and tried to build again. Fail.
I kept getting these errors:
Severity Code Description Project File Line Suppression State
Error error: <identifier> expected
package try.try; Try C:\Users\User\source\repos\Try\Try\obj\Debug\android\src\try\try\R.java 8
_______________________________________________________________________
Severity Code Description Project File Line Suppression State
Error error: class, interface, or enum expected
package try.try; Try C:\Users\User\source\repos\Try\Try\obj\Debug\android\src\try\try\R.java 8
_______________________________________________________________________
Severity Code Description Project File Line Suppression State
Error error: class, interface, or enum expected
package try.try; Try C:\Users\User\source\repos\Try\Try\obj\Debug\android\src\try\try\R.java 8
Great, so this has to have something to do with R.java 8? I go to the source and get this:
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package try.try;
public final class R {
public static final class attr {
}
public static final class id {
public static final int textureView1=0x7f040000;
}
public static final class layout {
public static final int main=0x7f020000;
}
public static final class string {
public static final int app_name=0x7f030000;
}
}
What is wrong here? I haven't even began to start coding or tinkering with Xamarin yet. Can someone please explain?
Figured it out. I don't know why, but Visual Studio 2017 put those project files in a completely different location unlike previous versions. Usually, it would have been put here: Documents>Visual Studio 2017>Projects>[Project Name]. It seems that the place you put your project is conflicting with Xamarin somehow. My suggestion would be to change the project location to what I mentioned above and then build the solution again. If that doesn't work, make a new project with the specified location and test it out. I had a similar problem and that fixed it for me.

Options Pages are only showing after disabling and enabling my Visual Studio extension

I'm the author of a small os vs2015 extension (AsmDude) and my users complain that the options pages are only visible after disabling the extension, restarting vs, enabling the extension and restarting vs again.
I have sifted through many tutorials, examples and manuals on how to use the ProvideOptionPage attribute properly, but nothing helped.
I have run devenv.exe with /LOG, but nothing strange comes up.
I have cleaned all registry entries that this plugin makes, but no fix.
The problem exists on clean installs of visual studio 2015 (sp2)
Next are some relevant c# code snippets:
[PackageRegistration(UseManagedResourcesOnly = true)]
[InstalledProductRegistration("AsmDude", Vsix.Description, Vsix.Version)]
[ProvideAutoLoad(UIContextGuids.NoSolution)]
[Guid(Guids.GuidPackage_str)]
[ComVisible(true)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[ProvideOptionPage(typeof(OptionsPageSyntaxHighlighting), "AsmDude", "Syntax Highlighting", 0, 0, true)]
public sealed class AsmDudePackage : Package {
//snip
}
[Export(typeof(DialogPage))]
[Guid(Guids.GuidOptionsPageSyntaxHighlighting)]
public class OptionsPageSyntaxHighlighting : DialogPage {
// snip
}
Question: how to debug such a vague problem? There must be a warning or error message logged somewhere that could help me pinpoint the problem.
Regards!
Edit: this question can also be found here on MSDN.

Missing Manifest exception Visual Studio 2010 project converted from 2003, 2008

I have a Win Forms C++ solution that was initially created with Visual Studio 2003, converted to 2008 (successfully) and now I'm attempting to convert it to Visual Studio 2010.
The solution builds without errors then when run I get a missing manifest exception when attempting to load an image list from the resources for a form. The exception happens on the following line of code:
this->m_imageList->ImageStream = (__try_cast<System::Windows::Forms::ImageListStreamer * >(resources->GetObject(S"m_imageList.ImageStream")));
I think I've found the problem, if I examine the manifest using ildasm of the 2008 assembly I see the following for the resources for the form:
.mresource public SDTP.SDTPDataMonitorForm.resources
{
// Offset: 0x00000000 Length: 0x00006DB0
}
The manifest for the 2010 assembly appears as follows:
.mresource public SDTPnet.SDTPDataMonitorForm.resources
{
// Offset: 0x00000000 Length: 0x00004F57
}
.mresource public '..\\temp\\Debug\\SDTP.SDTPDataMonitorForm.resources' as '..$temp$Debug$SDTP.SDTPDataMonitorForm.resources'
{
// Offset: 0x00008E80 Length: 0x00004F57
}
I'm sure it can't find it due to the extra "net" text in the first instance, and the extra ..$temp$Debug in the second instance.
So finally, my question: Where in the project settings do I fix that? The ..\temp\Debug is part of the project path... Playing around a bit if I change the "Intermediate Directory" setting to just $(Configuration) I now get:
.mresource public 'Debug\\SDTP.SDTPDataMonitorForm.resources' as Debug$SDTP.SDTPDataMonitorForm.resources
{
// Offset: 0x00008E80 Length: 0x00004F57
}
in the manifest file which still generates the exception.
Thanks for any help...
Right click on the .resx file and select properties and edit "Resource Logical Name"

Not Getting CA1822 on Local Build

I know that a software engineer usually isn't screaming, hey all I'm not getting an error, can you help me get one! But currently I need this error to show up locally because it's failing on our CI build. It's much harder to suppress (and please trust me I just need to suppress it because it's generated code from a WF workflow) when I'm not getting the error locally because the syntax for the member name is at best, painful.
The build server's CI build uses the Release configuration, and I'm building locally in Release, so ideally I'd be getting the same errors (an generally do).
Here is a snapshot of my Release section in my project file:
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<RunCodeAnalysis>true</RunCodeAnalysis>
<CodeAnalysisRuleSet>..\..\SolutionAnalysis.ruleset</CodeAnalysisRuleSet>
<StyleCopEnabled>true</StyleCopEnabled>
<StyleCopTreatErrorsAsWarnings>false</StyleCopTreatErrorsAsWarnings>
<NoWarn>1591</NoWarn>
</PropertyGroup>
And on the build server I'm getting this error (type and path names removed for security):
obj\Release\WorkflowName_BeforeInitializeComponentHelper.cs (18): CA1822 : Microsoft.Performance : The 'this' parameter (or 'Me' in Visual Basic) of 'WorkflowName.BeforeInitializeComponent(ref bool)' is never used. Mark the member as static (or Shared in Visual Basic) or use 'this'/'Me' in the method body or at least one property accessor, if appropriate.
I hope that y'all can help me figure out why Visual Studio isn't surfacing the error during a Release build locally ... oh the INSANITY!
Okay, so I'm getting this error locally now by upgrading my local version of StyleCop. I'm not sure why that has any bearing on code analysis but honestly all of these tools just don't play well together because we've also got ReSharper installed organization wide and it causes a lot of grief.
So, that being said, the way I ended up solving this anyway was to build partial classes for each WF Activity, i.e. XAML files**, that look something like this:
// ReSharper disable CheckNamespace
namespace {namespace}
// ReSharper restore CheckNamespace
{
using System.CodeDom.Compiler;
/// <summary>
/// Sets up the [GeneratedCode] attribute for the generated workflow class so that code analysis isn't performed.
/// </summary>
[GeneratedCode("", "1.0")]
public partial class {classname}
{
}
}
You can gather the {namespace} and {classname} from the x:Class attribute in the XAML that makes up the WF Activity (right-click on the XAML file and select "View Code").
** You don't need them for WF Services, i.e. XAMLX files

Visual Studio 2010 Not Recognizing Unit Test

In an existing solution I added a new Test Project. In my Test Project .cs file I have a class decorated with the [TestClass] attribute and a method decorated with the [TestMethod] attribute. I have verified that in Configuration Manager the build check box is checked for the Test Project (as my google search has revealed was the problem for others with this issue). I have set Test Project as my start up project for the solution. When I try to start the test I get "Can not start test project because the project does not contain any tests". I am really new to unit testing. What am I missing?
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Whole bunch of stuff
Assert.Inconclusive("Done");
}
}
Update: So I opened a new instance of VS, went to File => New => Project => Test Project. Did not touch or edit anything. Went straight to the cs file and here are its contents in its entirety:
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TestProject2
{
public class Inspection
{
public bool SubmitInsp()
{
return true;
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Inspection insp = new Inspection();
bool result = insp.SubmitInsp();
Assert.IsTrue(result);
}
}
}
Same error about the project not containing any test when I try to start it. Also found this in the build output "Could not load file or assembly '~\my documents\visual studio 2010\Projects\TestProject2\bin\Debug\TestProject2.dll' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)"
I don't know that units tests get much simpler than this. What the heck???
I've had the same problem, when tests in an working test project suddenly weren't recognized anymore.
Comparing the project file with one from another working test project showed me that the <ProjectTypeGuids> node was missing from the main <PropertyGroup> node.
Adding this line inside the <PropertyGroup> node solved my problem:
C#:
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
VB:
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}</ProjectTypeGuids>
I was able to get this to work by modifying the devenv.exe configuration file found here:
C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe.config.
Add the following line to the <runtime> section, then restart Visual Studio:
<loadFromRemoteSources enabled = "true" />
(Here is the link that helped me)
The FrstCBC's anwser did not worked for me.
I am on a VirtualBox machine with Windows 7 64 bits and Visual Studio 2012.
I had to move the output to a local folder : open the unit tests project properties and in the Build tab, browse the Output path to a local folder. The tests are now detected and can be run.
Test Projects saved to a network folder or anywhere locally on my computer have this issue. Created another Test Project and saved it to my flash drive, works just fine. I don't know if it is because my machine is 64 bit or because its a virtual machine or what, but I guess I just need to test everything on external storage devices.
For me it was just that my class and method weren't public (I realize the poster did have public, but I found this post by Googling "testclass testmethod margin icons missing"). Dumb mistake on my part, but maybe it will help others.
Verify that all the .cs files are marked as Compile in the Properties window. If it is marked as Content then you will hit this issue.

Resources