简体   繁体   中英

How to write Code Analysis (FxCop) rule to prevent a method call

How do I write a code analysis tool for vs2008 to prevent a specific framework call, such as GC.WaitForFullGCComplete() or Application.DoEvents()

I tried overriding the VisitMethodCall in my custom rule, but I cannot figure out what the Microsoft.FxCop.Sdk.MethodCall parameter really has in it. Could not find example on the web.

Can someone point me in the correct direction?

Replace System.Web.HttpUtility.HtmlEncode(System.String) with the method signature that you are trying to find and prevent.

    public override ProblemCollection Check(Member member)
    {
        if (member is Method)
        {
            var callees = new List<Method>(Callees.CalleesFor((Method)member));
            foreach (var callee in callees)
            {
                if (callee.FullName == "System.Web.HttpUtility.HtmlEncode(System.String)")
                {
                    Problems.Add(new Problem(GetResolution()));
                }
            }
        }

        return Problems;
    }

I remember a Debugging book that I think that had a chapter on FXCop rules and discussed how to write one. For the life of me I cannot find my copy. And I suspect you'll need reflector

An alternative to the mess of writing FxCop rules would be to use the tool NDepend. This tool lets write Code Rules over C# LINQ Queries what we call CQLinq . Disclaimer: I am one of the developers of the tool

More than 200 code rules are proposed by default. Customizing existing rules or creating your own rules is straightforward thanks to the well-known C# LINQ syntax.

How do I write a code analysis tool for vs2008 to prevent a specific framework call, such as GC.WaitForFullGCComplete() or Application.DoEvents()

For this particular need, the simple following CQLinq rule is enough (notice the usage of AllowNoMatch() to make this rule work in any situation):

// <Name>Don't call these methods</Name>
warnif count > 0
from m in Methods 
where m.IsUsing ("System.GC.WaitForFullGCComplete()".AllowNoMatch()) ||
      m.IsUsing ("System.GC.WaitForFullGCComplete(Int32)".AllowNoMatch()) ||
      m.IsUsing ("System.Windows.Forms.Application.DoEvents()".AllowNoMatch())
select m

CQLinq queries can be edited live in VisualStudio, and offer instant result, with result browsing facilities:

在此输入图像描述

Let's precise that rules can be verified live in Visual Studio and at Build Process time, in a generated HTML+javascript report .

虽然它与NDepend,甚至FxCop本身都不匹配,但我在这里发布了一个非常轻量级的方法,它适用于简单的事情,例如阻止对特定方法的调用: http//activesharp.codeplex.com/wikipage?title =使用%20ActiveSharp%20AS%20A%20Unit%20Test%20Tool

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM