How to write a code analysis rule (FxCop) to prevent a method call

How to write a code analysis tool for vs2008 to prevent a specific infrastructure call, for example, GC.WaitForFullGCComplete () or Application.DoEvents ()

I tried to override VisitMethodCall in my custom rule, but I can't figure out what the Microsoft.FxCop.Sdk.MethodCall parameter really has in it. Could not find an example on the Internet.

Can someone point me in the right direction?

+6
fxcop
source share
4 answers

Replace System.Web.HttpUtility.HtmlEncode(System.String) signature of the method 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; } 
+3
source share

I remember a debug book , which I think had a chapter on FXCop rules and discussed how to write it. For the life of me I cannot find my copy. And I suspect you will need a reflector.

0
source share

An alternative to the mess of writing FxCop rules is to use the NDepend tool. This tool allows you to write code rules over LINQ C # queries , what we call CQLinq . Disclaimer: I am one of the developers of this tool

By default, more than 200 code rules are suggested. Configuring existing rules or creating your own rules directly because of the well-known C # LINQ syntax.

How to write a code analysis tool for vs2008 to prevent a specific infrastructure call, for example, GC.WaitForFullGCComplete () or Application.DoEvents ()

For this specific need, the simple following CQLinq rule is sufficient (note the use 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 in real time in VisualStudio and offer instant results with the ability to view results:

enter image description here

More precisely, the rules can be checked live in Visual Studio and during the build process, the generated HTML + javascript report .

-2
source share

While this doesn't match NDepend or even FxCop itself, I just posted a very easy approach here that works well for simple things like preventing calls for certain methods: http://activesharp.codeplex.com/wikipage?title=Using% 20ActiveSharp% 20as% 20a% 20Unit% 20Test% 20Tool

-3
source share

All Articles