Is there a way to use reflection to completely "scan" an assembly to see if System.IO.File or System.IO.Directory is ever used? These are just example classes. Just wondering if there is a way to do it via reflection (vs code analysis).
update:
see comments
As Tommy Carlier suggested, it's very easy to do with Cecil.
using Mono.Cecil;
// ..
var assembly = AssemblyFactory.GetAssembly ("Foo.Bar.dll");
var module = assembly.MainModule;
bool references_file = module.TypeReferences.Contains ("System.IO.File");
The fantastic NDepend tool will give you this sort of dependency information.
Load your dll in NDepend and either use the GUI to find what you want, or the following CQL query:
SELECT TYPES WHERE IsDirectlyUsing "System.IO.File"
and you should get a list of all the types that use this.
I'd suggest looking at Mono Cecil for this. With Cecil, you can enumerate all the classes, methods and even the IL-instructions (including all the methods calls).
I don't remember where, but I found this handy piece of code:
http://gist.github.com/raw/104001/5ed01ea8a3bf7c8ad669d836de48209048d02b96/MethodBaseRocks.cs
It adds an extension method to MethodInfo/ConstructorInfo that parses the ILByteArray into Instruction objects.
So with this, you could loop over every MethodInfo/ConstructorInfo in the assembly, then loop over every Instruction on that MethodInfo/ConstructorInfo, and check if any of those Instruction objects contains an Operand which is an instance of a MemberInfo which has a DeclaringType that is equal to either class.
You can get a list of dependent assemblies via Assembly.GetExecutingAssembly().GetReferencedAssemblies(). I don't believe you can comprehend namespace usage via reflection. Try looking at System.CodeDom. That may help you parse the code.
.NET Reflector can do this, or something close to it. The other day I checked to see where a particular type was used.
ReSharper might also help. I do this with my own symbols all the time - I suppose it would also work for .NET Framework types.
Related
I'd like to use C#'s reflection and custom attributes to simplify registering a series of types with a central management class (i.e. it provides static methods taking a string key and invoking/retrieving the proper method/parameter for the associated type). Looking at other questions here and a couple places elsewhere, it seems like the best way of doing so is to simply iterate through all public types of the assembly -- since it's intended to be a library -- and check if each type has the proper attribute before adding the relevant values to the underlying Dictionaries. The reflection and iteration will definitely be slow, but I can live with it since it should only occur once.
Unfortunately, I can't figure out how to get an attribute from a type. For methods and assemblies, I can use CustomAttributeExtensions.GetCustomAttribute<MyAttribute>(base) from System.Reflection.Extensions, but that doesn't provide an overload for Type; the same for Assembly.GetCustomAttribute(Assembly, Type) and the .IsDefined(...) methods used in this question. Other suggestions use methods on the Type itself that, from the documentation, seem to be loaded from mscorelib.dll, but it didn't seem to be showing up in Intellisense even after adding the reference and I'm not sure how that .dll interacts with .NET Standard, anyway (as in, does it reduce the ability to run on arbitrary platforms at all?)
Am I missing something obvious, or is it really this hard to get an Attribute back off of a Type?
Try typeof(YourType).GetTypeInfo().GetCustomAttributes();
Is it possible writing code that generate a class, method, member at runtime using .NET (C#)?
For more details consider this scenario :
create a dynamic workflow program to enable user for creating his own process, activities, and writing dynamic SQL SPs, …, and collect all this stuff together then generate a classes, member variables , member functions , UIs, conditions, … dynamically at run-time ! in other word your own dynamic code factory framework !
Yes, there are various options for this:
Use CodeDOM (the System.CodeDom namespace)
Use the System.Reflection.Emit namespace
Create C# code and then compile it with Microsoft.CSharp.CSharpCodeProvider
For individual methods, create an expression tree and then compile it to a delegate
Use the Roslyn CTP to either compile C# code or create your own AST and compile that
The short response is yes. You have to look and study the following technologies:
CodeDom
Windows Wordflow Foundation
If it is anyway useful can be discussed: One able to "dynamically" program a workflow in a so specific mode will probably prefer to write the code by hand himself.
Another alternative of using strong types in this case, you may consider also using
Dynamic object to allow fully featured dynamic behaviour.
Could be more appropriate then strong typing generated at runtime, in this case.
Quick answer: Yes!
For a detail of how to achieve this you would want to start your learning by looking at Reflection.
The next step would be looking for other resources on the internet and a quick search located this question on SO:
How to create a method at runtime using Reflection.emit
Dynamic Language Runtime may also be worth a look.
I am not even sure if this is possible so apologies if not. I have googled quite extensively and not found what I am looking for.
Basically we have an application produced by a third party, which, to be perfectly blunt is rubbish. We have a particular issue and have managed to trace the problem using ILSpy to a method within a DLL. Obviously we don't have (nor are able to get) the source code and the company in question is unwilling to fix the problem in any reasonable timescales.
So, we've investigated various avenues of investigation and come up with nothing. I've been looking into seeing whether this can be done using reflection and this is pretty much the last hope we have of getting this to work. In a nutshell, what I would like to do is the following:
Create a simple class library with the same name as the existing DLL
Use reflection to import the methods from the existing DLL
Somehow override the method in question with my own, correct code
Rebuild the code, so I have a new DLL, containing 99% of the functionality of the existing DLL but with my override code providing the correct functionality.
I have found, during my investigations TypeBuilder.DefineMethodOverride and also a page from StackOverflow, which seems similar but not quite what I am looking for.
http://msdn.microsoft.com/en-us/library/system.reflection.emit.typebuilder.definemethodoverride.aspx
Is there a way to "override" a method with reflection?
Any advice appreciated!
Andrew
Edit
The other possible idea I has was to produce a partial class containing the override function, but that didn't seem feasible either.
You can override the method only if it is virtual, and it doesn't matter whether you do it through reflection or statically. I would suggest using a decompiler (there are a lot of free ones available) and fixing the code in MSIL. Then you can generate a new assembly from the MSIL.
I think your first idea is good.
If the third party class isn't sealed, you can derive from it, and add your own method, with a different name, to correct the behavior that is wrong.
If you need it to be in 1 dll, you can use IlMerge.
If your third party class is sealed you can just have an instance of this third party class in your new class and call the methods when needed.
But you'll have to check that the method you want to "override" isn't called inside that library, because if it is this solution won't work...
It's not very clean, but it can be a temporary solution during the time the company that edits the library fixes the problem.
And when it's fixed you'd just have to rename the method you use, so it won't be time consuming.
From what you have described I would recommend modifying the original assembly. The process is essentially
Decompile the assembly into MSIL, C# or whatever language you so choose
Modify the decompiled assembly to include your changes
Recompile the assembly using the modified source
From what I can see Reflexil allows you to do just that, although it may require that you buy Resharper (I've not tried it myself)
Alternatively you can use ILDasm to decompile the entire assembly to a single file, modify the file and then recompile it using ILAsm
I know I'm coming in a bit late on this, but I'd agree with Charleh; if you've got a class that's not behaving well and isn't conducive to substitution, but at least declares its methods as virtual, then you're in luck. The following uses references to Castle.Core and Patterns:
var interceptor = new DelegateInterceptor(proceed: call =>
{
if(ShouldCallProceed(call)) call.Proceed();
else AlternativeLogic();
});
var generator = new ProxyGenerator();
var proxy = generator.CreateClassProxy<UncooperativeType>(interceptor);
proxy.RubbishMethod();
I've also taken the liberty of providing a running sample of this in LinqPad. It shows the difference between methods that allow interception (virtual ones) and ones that don't. It also shows a useful way of trapping exceptions without all the code using Try.Do from Patterns.
I need to use a iOS build setting in Unity3d that strips unused classes from bytecode but as it uses static analysis to discover which to remove- so any classes resolved through reflection will not be excluded from removal unless explicitly added to an exclusion list. I managed to remove all uses of reflection in my own code, but Mono itself seems to use a reflection based configuration to do a bunch of stuff and I've already added about a dozen classes to the exclusion list but now I'm to the point where exceptions are not giving any clues as to what class needs to be excluded for them to work.
My question is, is it possible to get a precise list of all the classes (with source assembly and namespace) resolved through reflection throughout every assembly that the application uses, and how would you go about it? I have Visual Studio 2012 and while I know it has powerful debugging tools I don't know how I would use them to this end.
Thanks.
The short version
You can't as there is no way to find all lookups via reflection using static analysis.
The long version
Just think of the following example: I write code that selects a class depending on user input, e.g. in pseudo code:
string action = ... ; // get some user input here, e.g. "Fire"
string clazz = "Do" + action;
var obj = Activator.CreateInstance("MyActions", clazz);
As you can see the actual full class name is not occuring anywhere in the code. So you would need to execute the code in every possible way to find out which values the clazz variable could assume. Therefore you cannot find out which classes this code would access via reflection.
Further Questions
What exact API from Mono are you using and what kind of exceptions are you getting? Maybe there is some alternative that could be used for your purpose.
I am to build a SOA gui framework, and I'd like to autodetect services, and service dependencies from client modules. I have code such as this so far, which works using attributes, placed on class modules:
[ServiceProvider(typeof(DemoService3))]
[ServiceConsumer(typeof(DemoService1))]
I am wondering how I can scan for these automagically, so that people wouldn't forget to add the marker and potentially get null references at runtime. In the code services are registered and fetched via the following commands:
Services.RegisterService(new DemoService1());
Services.FetchService<DemoService3>();
I want to find these calls, and also the types being passed in (both take a type param, implicit for the first one)... the rest of the code for doing my dependencies and construction is already done :)
You will need to analyze the IL at the CLR level, not the C# level to figure this out.
You should be able to leverage Mono Cecil to pull this off.
You can either use Mono.Cecil or .NET reflection to accomplish that.
Mono.Cecil is recommended due to its better performance and flexibility. Here are some samples (Cecil + simple extensions on top) that could get you started:
How to Find Extension Methods Targeting Object?
How to Count Methods With NotImplementedException?
How to ensure that classes marked with ImmutableAttribute are Immutable indeed?
How to Change Namespace of .NET Assembly?
If you're unable to use Mono.Cecil for some reason, you could consider parsing the IL by hand: you'd effectively just need to find call and callvirt instructions, possibly doing static analysis enough to understand the type returned by new DemoService1().
typeof(YourClass).GetMethod("YourMethod").GetMethodBody().GetILAsByteArray() is your friend.