PVS Studio Suppress Single Warning For Entire C# File - c#

I am trying to suppress a warning for an entire C# file using syntax found at https://www.viva64.com/en/m/0017/.
According to the documentation //-V::3085 at the beginning of a file should suppress all V3085 warnings in the file.
Using the following code I still see the warning. What am I doing wrong?
//-V::3085
namespace ClassLibrary
{
public class Class
{
public static string Property => null;
public sealed class InnerClass
{
public string[] Property { get; set; }
}
}
}

According to the documentation //-V::3085 at the beginning of a file
should suppress all V3085 warnings in the file.
This syntax works for compilation units, not for single files, and it works as a comment in source file in C++ only - for C# you need to add a pvsconfig file (described in the link you've provided above) to your project, and add this line there - this will disable the warning for the whole project (as, in C#, the whole project is a single compilation unit).

Related

Access source generated class property/method in main code MSVS 2022

I created my first source generator (ISourceGenerator) with public property and public method.
Let this class be like this:
public partial class MyClass1 // Manually written code
{
}
public partial class MyClass1 //Source Generated code
{
public string GeneratedProperty { get; set; }
public string GeneratedMethod() => "lala";
}
Both of these classes are located in the same namespace (for example, MyNamespace - it doesn't matter really).
So, I'm trying this:
var myClass = new MyClass1(); // Correct
Console.WriteLine(myClass.GeneratedMethod()); //Wrong, "MyClass1 doesn't contain definition for GeneratedMethod..."
When I say MSVS generate sources as files in the concrete directory, I have the code above working well.
So, I want to have an ability to use generated code "on fly" when I write code without generation source files each time manually. Also earlier manually generated source files are not deleted when I'm generating new source files.
Is it possible?
Thank you.
UPD. I have this message from Visual Studio:
"Warning CS8032 An instance of analyzer Generators.Factory.AbstractFactoryGenerator cannot be created from ...\bin\Debug\netstandard2.0\SourceGeneratorsLibrary.dll: Exception has been thrown by the target of an invocation."
Maybe this significant?
UPD2. https://pastebin.com/qtvrugu3 - this is my Source Generator code. Pls, don't blame me, It's just my first steps.
As far as I know, programming is case sensitive, well at least C# so myClass() is different from MyClass(). also hence you are using the string data type, try casting it as string via
Convert.ToString(MyClass1().GeneratedMethod());
or
MyClass1().GeneratedMethod().ToString();
hope this answers you question.
It seems you have developed your analyzer but not actually referenced it from a project?
To use your analyzer you simply add it as as project reference, but make sure it's marked up as an analyzer in the .csproj file:
<ItemGroup>
<ProjectReference Include="MyGenerator\MyGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>
Or something like that, adjusted to your solution.

Specifying cs file to build with dotnet CLI

Suppose I have two files in my current working directory:
// file1.cs
Console.WriteLine("file1");
//file 2.cs
Console.WriteLine("file2");
In powershell, I do a dotnet new and delete the automatically generated Program.cs file. Then I do a dotnet build and get an error:
Only one compilation unit can have top level statements
I understand why this occurs, but I would like to be able to have full control of which .cs file is being targetted, while the other ones get ignored.
Is there any way to achieve this without having to create a whole new project for every file?
Doing this with .NET doesn't seem to be possible as of now. An issue on the dotnet/sdk GitHub has requested for this feature to be implemented.
However, you can use the C Sharp Compiler to compile a Windows executable and specify a .cs file with csc file1.cs
file1.cs:
using System;
Console.WriteLine("File 1");
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/top-level-statements
These files both use top-level statements. It implies that they both contain the Main method where program execution starts. You can only have one entry point. Generally, C# code is going to be contained within classes. Define a class in one (or both) files and put your methods within.
// Program.cs
public class Program
{
static void Main()
{
Console.WriteLine("Program.cs");
}
}
// Util.cs
public class Util
{
public static void Display()
{
Console.WriteLine("Util.cs");
}
}

Can't import classes from same namespace

I'm fairly new to .NET and I'm trying to get an old program to work that no longer has it's .csproj file. I've managed to receive an old .sln file from the creator and opened the solution in VS.
From what I can see this is a Developer Web Server project?
Here is the issue.
In the folder Smreka there are 2 files, log.cs and smreka.cs. The log.cs contains the implementation of a class Logger, which I am trying to import in to smreka.cs. They are both using the same namespace Bum.Iglavci.Smreka so as far as I know, I should be able to import the Logger class without any issues.
The problem is that the compiler just can't see it. If I try to directly import it with using static Bum.Iglavci.Smreka.Logger;, I get an error Feature 'using static' is not available in C# 5. Please use language version 6 or greater.
I would like to know why the namespace can't see each other. Is it because I'm missing the .csproj file? Does Developer Web Server even need a .csproj file? If so what's the best way to generate one?
EDIT:
Due to some confusion I'll try to add more details regarding how log.cs and smreka.cs look like. The files are actually a lot longer but I think this should give an idea.
log.cs:
namespace Bum.Iglavci.Smreka{
public class Logger{
public Logger(){
}
public void DoSomething(){}
}
}
smreka.cs:
namespace Bum.Iglavci.Smreka{
public class Baza{
private Logger log;
public Baza(){
log = new Logger();
}
}
}
The compiler has no idea what Logger is under property private Logger log; It states the error The type or namespace name 'Logger' could not be found (are you missing a using directive or an assembly reference?)
I think the namespace is correctly placed, that's why i have a feeling there's something wrong with the project or the solution itself that i need to fix.
Since both classes are in the same namespace they are already able to use each other. You can acces the class by simply doing the following. Let's take Log as the class to call the other class.
Log class:
namespace Bum.Iglavci
{
public class Log
{
public static void ExecuteDoSomething()
{
Smreka.DoSomething();
}
}
}
Smerka class:
namespace Bum.Iglavci
{
public class Smerka
{
public static void DoSomething()
{
//execute code here
}
}
}
It could be possible that the files have the Buil Action property set to
None this will not compile the files. Set it to C# Compiler, this should solve it.
If you don't know how to acces the properties of a file.
Right click the file
Navigate to Properties in the bottom of the list
Set the Build Action to C# compiler (see image)
I found no simple solution. I now created a new .net framework application project and added the files in to the new project. For some reason the namespace works correctly now and the files can see each other in the same namespace.
Yes the error comes from the fact that you don't have a .csproj file.
Such files contain the list of files to compile when building a project. Just having the solution file is not enough.
I suggest some readings on project and solution using Visual Studio :
https://learn.microsoft.com/en-us/visualstudio/ide/solutions-and-projects-in-visual-studio?view=vs-2022
https://learn.microsoft.com/en-us/visualstudio/get-started/tutorial-projects-solutions?view=vs-2022

Make diagnostic errors reported by a C# source generator appear in the Visual Studio editor

I am attempting to write a C# source generator that throws a warning/error under certain conditions using GeneratorExecutionContext.ReportDiagnostic. My source generator is able to run and output errors successfully upon building a sample project in Visual Studio. However, my errors do not show up as green/red squiggles in the Visual Studio editor. This is supposed to be possible with Roslyn analyzers, according to Microsoft's documentation, but nothing is said of source generators specifically. Since source generators are treated like Roslyn analyzers, though, I imagine this should be possible. I've managed to replicate my issue with a small example, consisting of a source generator project and a test project on which to run the generator. As a test, the generator reports a diagnostic error whenever it sees a method that doesn't return void. I intend for red squiggles to appear under the offending method's name:
Source generator:
[Generator]
public class SampleGenerator : ISourceGenerator
{
public void Execute(GeneratorExecutionContext context)
{
DataReceiver r = (DataReceiver)context.SyntaxReceiver;
foreach(MethodDeclarationSyntax method in r.Methods)
{
IMethodSymbol symbol = (IMethodSymbol)context.Compilation.GetSemanticModel(method.SyntaxTree).GetDeclaredSymbol(method);
if(symbol.ReturnType.SpecialType != SpecialType.System_Void)
{
context.ReportDiagnostic(Diagnostic.Create(
new DiagnosticDescriptor(
"SG0001",
"Non-void method return type",
"Method {0} returns {1}. All methods must return void.",
"yeet",
DiagnosticSeverity.Error,
true), symbol.Locations.FirstOrDefault(), symbol.Name, symbol.ReturnType.Name));
}
}
context.AddSource("yert", "namespace test { public class testclass { } }");
}
public void Initialize(GeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(() => new DataReceiver());
}
}
public class DataReceiver : ISyntaxReceiver
{
public List<MethodDeclarationSyntax> Methods { get; } = new List<MethodDeclarationSyntax>();
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
if(syntaxNode is MethodDeclarationSyntax synt)
{
Methods.Add(synt);
}
}
}
Example code:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
static string ok() => "hello";
}
When I compile the example code with the generator, Visual Studio tells me that the build has errors, and correctly reports the custom diagnostic in the error list. I can click on the custom error, and my cursor moves to the offending method in the editor. However, no red squiggles appear. I know that my source generator is being run by Intellisense, because I am able to see the custom test namespace and class my generator defines.
Does Visual Studio support code underlining for diagnostics reported by C# source generators? If so, what is wrong with the above code? Thanks in advance.
I solved this by separating out the code analysis logic into its own class and adding an analyzer and source generator into the same assembly, with the analysis logic only doing code emmission in the source generator. The analysis logic runs in different contexts, each context having a different reportdiagnostic, so it accepted an Action to report diagnostic.

code analysis warning CA2000 which should not occur

I have a small issue with a CA2000 warning. In my project which is set as startup project, I get this warning, although it should not occur.
Background: I am using Visual Studio 2010 with projects in .NET 3.5. The startup project is a WPF application.
In the class App looks as follows:
public partial class App : System.Windows.Application {
/// <summary>
/// Application Entry Point.
/// </summary>
[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static void Main() {
AutoTester.App app = new AutoTester.App();
app.Run();
}
}
The warning says:
Warning 1 CA2000 : Microsoft.Reliability : In method 'App.Main()', call System.IDisposable.Dispose on object 'app' before all references to it are out of scope. C:\Projects\Freelance\svn\AutoTester\Application\Applications\AutoTester\obj\x86\Debug\App.g.cs 47 AutoTester
As one can see, the warning occurs in the App.g.cs which is an auto-generated file. In the project properties I have deactivated code analysis for autogenerated files. "Supress results from auto-generated code". Therefore, this warning should not occur, right?
Now my problem is, that I cannot locally suppress the warning because the code will be overriden. Also, I do not want to make a rule for that globally, because I don't want to deactivate CA2000.
Has anyone encountered a similar problem or any idea what is going wrong here?
Best wishes,
Christian
"Supress results from auto-generated code" indicates that results from code that is auto-generated is not shown. Visual Studio knows that code is generated by a third-party only if it contains the GeneratedCodeAttribute (see here). Apprarently, the tool that created your code didn't add the attribute.
You can try to make another partial class of App and put the attribute there:
[GeneratedCode("CodeGenerator", "1.0.0.0")]
public partial class App
{
}

Categories