What is the best way to create custom FxCop code analysis rule that uses Roslyn

I was tasked with creating a code analysis rule that can catch swallowed exceptions. Everything worked well until I checked my rule with async methods and the rule was unable to catch swallowed exceptions.

I decided to try Roslin. For Roslyn to work, I needed to know the location of the source file, and I was able to get that from a property member.SourceContext.FileName

. The problem is that the property doesn't always exist. I've noticed that this always applies to non-public methods.

Is there a reliable way to get the original file using the FxCode code parsing engine? Is there a better way to use roslyn for code analysis?

FxCop Rule:

internal sealed class DoNotSwallowExceptionsRule : BaseFxCopRule
{
    public override ProblemCollection Check(Member member)
    {
         Method method = member as Method;
         if (method != null && method.Body != null && method.Instructions != null)
         {
             string sourcefileName = method.SourceContext.FileName; //sometimes is null

             if (sourcefileName != null)
             {
                string source = File.ReadAllText(sourcefileName);

                var result = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(source);
             }
         }
         return Problems;
    }
}

      

+3


source to share





All Articles