Question

I'm building a couple of customs FxCop rules and one of the rules needs to enforce that a constructor is called in specific methods. For that, I need to create a list of callers, to that specific constructor, prior to performing the actual test. How is this possible? Is there some kind of handle to acquire a list of all loaded assemblies in the ApplicationDomain, where I can iterate through the classes and find the constructor Method object? Ideally the list of callers should be composed in the BeforeAnalysis method.

Was it helpful?

Solution 2

I think I haven't explained the question very well, but I see your point. I have 3 different assemblies and for certain method calls from one assembly to another, I need to ensure that a benchmark constructor invoked. The benchmark class resides in a 4th assembly. Now my problem was that only VS2010 only loads one target assembly for analysis and when I used the CallGraph to construct the a list of methods calling the constructur, it would not find any. When Invoking FxCopCmd.exe manually I could just add the dependent assemblies manually with the /file: parameter.

My solution is to load the different assemblies manually (not relying on the loaded assembly in RuleUtilities.AnalysisAssemblies and contruct the list of callers in the BeforeAnalysis method.

            RuleUtilities.GetAssembly(
            RuleUtilities.AnalysisAssemblies
            .First().Directory + "\\" + additionalAssemblyFilename)
            .Types.SelectMany(type => type.Members)
            .Where(member => member.IsPublic)
            .Where(CanBeCastedToMethod)
            .Cast<Method>()
            .SelectMany(CallGraph.CallersFor);

With this approach I can contruct a list of callers, for each of the assemblies and for the benchmark class constructor. Works perfectly i VS2010.

OTHER TIPS

The Microsoft.FxCop.Sdk.CallGraph.CallersFor(Method) method may give you what you want. However, the general approach you seem to be describing is rarely a good idea because it would typically assign the problems to the wrong target. For example, in the scenario you describe, it would presumably be desirable to attribute the problems to the methods that should but do not contain the target contructor call. However, if your analysis target is the constructor, the detected problems will be attributed to the constructor rather than the methods that should have called it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top