Logging Roslyn Code Generator:
For each program that you develop , it is important ( if not vital ) to see logging. In the Roslyn Analyzer / Code Generators, the diagnostics are logged with DiagnosticDescriptor and Diagnostic – think that you should see in the output console when compiling and this will become clear.
More, the enum DiagnosticSeverity Enum (Microsoft.CodeAnalysis) | Microsoft Docs can be seen as default for Warn and Info – but not for Info. Info can be seen only with
dotnet build -v diag
The code that I used is:
static Diagnostic DoDiagnostic(DiagnosticSeverity ds,string message)
{
//info could be seen only with
// dotnet build -v diag
var dd = new DiagnosticDescriptor(“SkinnyControllersGenerator”, $”StartExecution”, $”{message}”, “SkinnyControllers”, ds, true);
var d = Diagnostic.Create(dd, Location.Create(“skinnycontrollers.cs”, new TextSpan(1, 2), new LinePositionSpan()));
return d;
}
And I called like this
string name = $”{ThisAssembly.Project.AssemblyName} {ThisAssembly.Info.Version}”;
context.ReportDiagnostic(DoDiagnostic(DiagnosticSeverity.Info,name));
( Yes , I used a Roslyn Code Generator – GitHub – kzu/ThisAssembly: Exposes project and assembly level information as constants in the ThisAssembly class using source generators powered by Roslyn. – inside another code generator – and no reference used on deploy – how cool is that ? )
Also, I use this to display some warnings when something is wrong , but I do not generate code. For example:
var ms = m as IMethodSymbol;
if (ms is null)
{
context.ReportDiagnostic(DoDiagnostic(DiagnosticSeverity.Warning, $”{m.Name} is not a IMethodSymbol”));
continue;
}
Intellisense for Code Generators:
This is something easy. First, I did not have intellisense. After reading , I discovered that I should put above the class declaration :
[GeneratedCode(“”{ThisAssembly.Info.Product}””, “”{ThisAssembly.Info.Version}””)]
[CompilerGenerated]
( Yes, again code generator – thanks, KZU ! – to the rescue).
In this manner , if something wrong, I can see the version of the SkinnyControllersGenerator right away .