FxCop, compose list of callers from dependent assembly - fxcop

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.

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.

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.

Related

Implements vs Binary Compatibility

I have one VB6 ActiveX DLL that exposes a class INewReport. I added some new methods to this class and I was able to rebuild it and keep binary compatibility.
I have a second DLL that exposes a class clsNewReport, which implements the first class using:
Implements RSInterfaces.INewReport
Since I added new methods to INewReport, I had to also add those new methods to clsNewReport.
However, when I try to compile the second DLL, I get the binary-compatibility error "...class implemented an interface in the version-compatible component, but not in the current project".
I'm not sure what is happening here. Since I'm only adding to the class, why can't I maintain binary compatibility with the second DLL? Is there any way around this?
I think this is a correct explanation of what is happening, and some potential workarounds.
I made up a test case which reproduced the problem in the description and then dumped the IDL using OLEView from the old & new DLL which contained the interface.
Here is a diff of the old (left) and new IDL from INewReport:
Important differences:
The UUID of interface _INewReport has changed
A typedef called INewReport___v0 has been added which refers to the original UUID of the interface
(I assume that this is also what is happening to the code referred to in the question.)
So now in the client project the bincomp DLL refers to the original interface UUID; but that UUID only matches against a different name (INewReport___v0 instead of INewReport) than it did originally. I think this is the reason VB6 thinks there is a bincomp mismatch.
How to fix this problem? I've not been able to do anything in VB6 that would allow you to use the updated interface DLL with the client code without having to break bincomp of the client code.
A (bad) option could be to just change the client DLL to use project compatibility... but that may or may not be acceptable in your circumstances. It could cause whatever uses the client DLL to break unless all the consumers were also recompiled. (And this could potentially cause a cascade of broken bincomp).
A better but more complex option would be to define the interface in IDL itself, use the MIDL compiler to generate a typelib (TLB file), and reference that directly. Then you would have full control over the interface naming, etc. You could use the IDL generated from OLEView as a starting point for doing this.
This second option assumes that the interface class is really truly an interface only and has no functional code in it.
Here's how I setup a case to reproduce this:
Step 1. Original interface definition - class called INewReport set to binary compatible:
Sub ProcA()
End Sub
Sub ProcB()
End Sub
Step 2. Create a test client DLL which implements INewReport, also set to binary compatible:
Implements INewReport
Sub INewReport_ProcA()
End Sub
Sub INewReport_ProcB()
End Sub
Step 3: Add ProcC to INewReport and recompile (which also registers the newly built DLL):
(above code, plus:)
Sub ProcC()
End Sub
Step 4: Try to run or compile the test client DLL - instantly get the OP's error. No need to change any references or anything at all.
I was able to recreate your problem, using something similar to DaveInCaz's code. I tried a number of things to fix it, probably repeating things you've already tried. I came up with a possible hypothesis as to why this is happening. It doesn't fix the problem, but it may throw some additional light on it.
Quoting from This doc page:
To ensure compatibility, Visual Basic places certain restrictions on changes you make to default interfaces. Visual Basic allows you to add new classes, and to enhance the default interface of any existing class by adding properties and methods. Removing classes, properties, or methods, or changing the arguments of existing properties or methods, will cause Visual Basic to issue incompatibility warnings.
Another quote:
The ActiveX rule you must follow to ensure compatibility with multiple interfaces is simple: once an interface is in use, it can never be changed. The interface ID of a standard interface is fixed by the type library that defines the interface.
So, here's a hypothesis. The first quote mentions the default interface, which suggests that it may not be possible to alter custom interfaces in any way. That's suggested by the second quote as well. You're able to alter the interface class, because you are essentially altering its default interface. However, when you attempt to alter the implementing class in kind, to reflect the changes in your interface, your implementation reference is pointing to the older version of the interface, which no longer exists. Of course, the error message doesn't hint at this at all, because it appears to be based on the idea that you didn't attempt to implement the interface.
I haven't been able to prove this, but looking at DaveInCaz's answer, the fact that the UUID has changed seems to bear this idea out.

Does COM's put_XXX methods change to set_XXX in a .NET RCW

I have a COM component that has get_XXX and put_XXX methods inside it. I used it in a .NET project and a RCW was generated for it. I now see get_XXX and set_XXX methods and NOT the put_XXX one? Is that automatic or defined somewhere in IDL?
These are property accessor methods. A compiler that uses the COM server is expected to generate a call to get_Xxx() when the client program reads the property, put_Xxx() when it writes it. A special one that C# doesn't have at all is putref_Xxx(), used to unambiguously access an object instead of a value.
The normal translation performed by Tlbimp.exe is as a plain C# property. But that doesn't always work, C# is a lot more strict about what a property can look like:
The default property, the one that's annotated as DISPID_VALUE (dispid 0) must take a single argument to be compatible. This maps to the C# indexer property, the one that makes it look like you are indexing an array.
Any other property cannot take an argument, C# does not supported indexed properties other than the indexer.
C# does not have the equivalent of putref_Xxx(), the syntax ambiguity cannot occur in a C# program because of the previous two bullets. And the core reason that the C# team decided to put these restrictions in place, they greatly disliked ambiguity in the language.
So Tlbimp.exe is forced to deal with these restrictions, if the COM property accessors are not compatible then it must fall back to exposing them as plain methods instead of a property. With default names, they'll get the get_ and set_ prefixes. The latter one explains your question, they didn't pick put_ for an otherwise unclear reason.
Notable is that C# version 4 relaxed several of these restrictions, most of all to make interop with Office programs easier. Which was quite painful in earlier C# versions, to put it mildly. It extended the property syntax to lessen the pain, but only for COM interop. Very strongly recommended if you are still stuck on an old version of .NET, now is a good time to consider updating.
The properties themselves have to prefixes (put_ etc.), they have names, getter method, setter method, but no prefixes. Method table generated from type library receives prefixes to distinguish between getters and setters, hence the prefixes. Prefix string exactly depends on preference of the one who generates the names.
See also:
#pragma import attributes - raw_property_prefixes
By default, low-level propget, propput, and propputref methods are exposed by member functions named with prefixes of get_, put_, and putref_ respectively. These prefixes are compatible with the names used in the header files generated by MIDL.

How to find and remove unused class files from a project

My XCode project has grown somewhat, and I know that there are class files in there which are no longer being used. Is there an easy way to find all of these and remove them?
If the class files just sit in your project without being part of a target, just click on the project itself in the tree view, so you see all files in the table. Make sure you see the "Target" column in the table view, iterate through your targets and find the files that don't have a check anywhere -> they are no longer compiled.
But if you still compile the classes and they are no longer used, that case is a bit more difficult. Check out this project
http://www.karppinen.fi/analysistool/#dependency-graphs
You could create a dependency graph and try to find orphaned classes that way.
Edit: Link went dead, but there still seem to be projects of Objective-C dependency graphs around, for example https://github.com/nst/objc_dep
if they are C or C++ symbols, then you can just let the linker do the work for you.
if you're looking to remove objc symbols, then try to refactor the class name (e.g. to rename the class), and preview the dependencies that it turns up. if you reference classes/selectors/etc. by strings then... it may not be so effective. unfortunately, you often have to also test manually, to verify that removing a class does not break anything. remember that resources (like xibs) may reference/load objc classes as well.
This is a tricky question due to how dynamic objective-c is as you can never guarantee that a class is not going to be used.
Consider if you generate a class name and a selector at run time and then look up that class, instantiate that class and then call a method on that newly created object using that newly created selector. No where in your code do you explicitly name and instantiate that object but you are able to use it anyways. You could get that class name and selector name from anywhere outside of your code, even from some data from a server some where. How would you ever know which class is not going to be used? Because of this there are no tools that are able to perform what you are requesting.
Searching the project with the class name might be an option, thought it may not be the best solution. Specially it might be time consuming when you have many classes.

What is the use of reflection in Java/C# etc [duplicate]

This question already has answers here:
What is reflection and why is it useful?
(23 answers)
Closed 6 years ago.
I was just curious, why should we use reflection in the first place?
// Without reflection
Foo foo = new Foo();
foo.hello();
// With reflection
Class cls = Class.forName("Foo");
Object foo = cls.newInstance();
Method method = cls.getMethod("hello", null);
method.invoke(foo, null);
We can simply create an object and call the class's method, but why do the same using forName, newInstance and getMthod functions?
To make everything dynamic?
Simply put: because sometimes you don't know either the "Foo" or "hello" parts at compile time.
The vast majority of the time you do know this, so it's not worth using reflection. Just occasionally, however, you don't - and at that point, reflection is all you can turn to.
As an example, protocol buffers allows you to generate code which either contains full statically-typed code for reading and writing messages, or it generates just enough so that the rest can be done by reflection: in the reflection case, the load/save code has to get and set properties via reflection - it knows the names of the properties involved due to the message descriptor. This is much (much) slower but results in considerably less code being generated.
Another example would be dependency injection, where the names of the types used for the dependencies are often provided in configuration files: the DI framework then has to use reflection to construct all the components involved, finding constructors and/or properties along the way.
It is used whenever you (=your method/your class) doesn't know at compile time the type should instantiate or the method it should invoke.
Also, many frameworks use reflection to analyze and use your objects. For example:
hibernate/nhibernate (and any object-relational mapper) use reflection to inspect all the properties of your classes so that it is able to update them or use them when executing database operations
you may want to make it configurable which method of a user-defined class is executed by default by your application. The configured value is String, and you can get the target class, get the method that has the configured name, and invoke it, without knowing it at compile time.
parsing annotations is done by reflection
A typical usage is a plug-in mechanism, which supports classes (usually implementations of interfaces) that are unknown at compile time.
You can use reflection for automating any process that could usefully use a list of the object's methods and/or properties. If you've ever spent time writing code that does roughly the same thing on each of an object's fields in turn -- the obvious way of saving and loading data often works like that -- then that's something reflection could do for you automatically.
The most common applications are probably these three:
Serialization (see, e.g., .NET's XmlSerializer)
Generation of widgets for editing objects' properties (e.g., Xcode's Interface Builder, .NET's dialog designer)
Factories that create objects with arbitrary dependencies by examining the classes for constructors and supplying suitable objects on creation (e.g., any dependency injection framework)
Using reflection, you can very easily write configurations that detail methods/fields in text, and the framework using these can read a text description of the field and find the real corresponding field.
e.g. JXPath allows you to navigate objects like this:
//company[#name='Sun']/address
so JXPath will look for a method getCompany() (corresponding to company), a field in that called name etc.
You'll find this in lots of frameworks in Java e.g. JavaBeans, Spring etc.
It's useful for things like serialization and object-relational mapping. You can write a generic function to serialize an object by using reflection to get all of an object's properties. In C++, you'd have to write a separate function for every class.
I have used it in some validation classes before, where I passed a large, complex data structure in the constructor and then ran a zillion (couple hundred really) methods to check the validity of the data. All of my validation methods were private and returned booleans so I made one "validate" method you could call which used reflection to invoke all the private methods in the class than returned booleans.
This made the validate method more concise (didn't need to enumerate each little method) and garuanteed all the methods were being run (e.g. someone writes a new validation rule and forgets to call it in the main method).
After changing to use reflection I didn't notice any meaningful loss in performance, and the code was easier to maintain.
in addition to Jons answer, another usage is to be able to "dip your toe in the water" to test if a given facility is present in the JVM.
Under OS X a java application looks nicer if some Apple-provided classes are called. The easiest way to test if these classes are present, is to test with reflection first
some times you need to create a object of class on fly or from some other place not a java code (e.g jsp). at that time reflection is useful.

Asserting a method invocation on one of several injected types

We use RhinoMocks. I have a type into whose constructor 9 types are injected. I'd like a way of automocking the type, but being able to detect a particular method invocation on one of the injected objects (i.e. I only care about a single method invocation on one of the injected objects).
Is this possible, or do I have to manually inject all the mock objects into the constructor?
I haven't seen any frameworks that would auto-create these mocks for you. You can do it in your [SetUp] method, so at least the tests will not be cluttered with boilerplate code.
I need to check out http://autofixture.codeplex.com/. Its not really container specific, there is an extension for rhino mocks. Disclaimer: I haven't tried autofixture yet.