I'm trying to replace some code/comment it with custom solution at specific position. I'm not creating an analyzer to detect the issue and waiting for user to click bulb and fix it. I'm working on a normal console Application. the purpose is I've multiple different custom Codefix which'll run as a batch and fix it through out a whole Project.
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, userDetails.Id.ToString()),
new Claim(ClaimTypes.Role, userDetails.Role),
new Claim(ClaimTypes.UserData, userDetails.Password)// Claim contains user's password
}),
// Additional parameters... //
};
current I want to comment the "new Claim(ClaimTypes.UserData, userDetails.Password)" line and also the "," before the line by replacing the Syntax node content or insert "//" at the start of the Span and "//" before the comma as well.
This is where I'm stuck, below are code snippets on how I'm deciding where to apply the fix.
/* After read the .cs file from config I'll have a List of this object by which I'll know where to apply the fix*/
public class FormattedXML
{
public string? FileName { get; set; }
public string? MethodName { get; set; }
public int? LineNumber { get; set; }
public string? LineCode { get; set; }
}
/After using CSharpSyntaxTree.ParseText(code) to read the whole .cs file/
public static void JwT001(SyntaxTree st, FormattedXML Issue)
{
var root = (CompilationUnitSyntax)st.GetRoot();
var objectCreations = from r in root.DescendantNodes().OfType<ObjectCreationExpressionSyntax>() select r;
foreach (var objectCrreation in objectCreations.ToList())
{
string Line = objectCrreation.ToFullString();
if (Line.Trim() == Issue.LineCode.Trim())
{
var span = objectCrreation.FullSpan;
var node = st.GetRoot().FindNode(span);// Has the line that needs to be commented
var abc = node.Parent.FindToken(span.Start - 1); //"," needs to be commented
// How do I access this comma which is part of the previous objeccreationExpression node
//var bc = node.WriteTo();
}
}
}
Now I've the node at hand, the span where i can apply fix.
How do I apply the fix and create the whole SyntaxTree again and create a .cs file again from it?