Overriding method in DLL using reflection - c#

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.

Related

Is there any way to auto run some code in DLL?

I have some DLL from third party that I need to license. It has some method that I must call from my own DLL. My DLL is referenced in couple of projects and I don't want to make changes to every hoster. Is there any method that I can use within my DLL which will call some method in my DLL? Like add some static class or constructor but without explicit call to that class from hosters? I am not sure if I am explaining it clearly. Please ask questions if needed.
ThirdPartyType license = new ThirdPartyType();
license.Load("license.xml");
This is a piece of licensing code that I want to place in my DLL and call it within the same DLL.
At the low level, the runtime supports "module initializers". However, C# does not provide any way of implementing them, so the closest you can manage is a static constructor ("type initializer") or just a regular constructor.
However, it is probably a bad idea to hook your licencing into either a module initializer or a type initializer, as you don't know when they will run, and it could impact code that wasn't going to access your lib. It is somewhat frowned upon to take someone's app down because your licensing code decided it was unhappy - especially if your library wasn't actively being invoked at the time.
As such: I suggest the most appropriate place to do this is in either a constructor, or a post-construction Initialize(...) method (with the tool refusing to work unless supplied with valid details).

How to replace a static class at runtime

I know you cant override or inherit from a static class and why. That is clear.
I am looking for some advice on how to replace that static class with my own static class. Any hackish or wildest attempts please.
I am basically writing a MOD for a game and the way the game writer wrote one class in particular, he set it as static and put the implementation in there. So when we write our own DLL with this thing, the only way to execute a calculation on the pixel grid is when his code calls this particular calculation in his static class. Both classes are static but I only need to change one.
That is great for him but I want my thing to do another calculation and make it more awesome. I used ILspy and can see all the code in that static class of the base game, so I can copy and paste it and I only need to modify two or three lines.
But now I want to nuke the games core static class and make mine the only implementation.
I want to force replace that static class at runtime, before the static class is ever called and after loading my mod, how? There must be a way to swap static classes?
I read about creating a proxy DLL that redirects all methods to the old DLL and my method to my DLL but that would require gamers to replace a core game DLL and that is even dirtier than just telling people what my mod does. I am changing thas implementation for this mod, if you dont like don use my mod. That is more reasonable.
I will assume you don't have access to the source and thus can't modify it directly.
You COULD (probably shouldn't) use microsoft fakes since it is mainly for testing. You could create a fakes assembly based on the original author's dll, and override just the type you want. It even supports overriding static classes. Again, I am not saying that you necessarily SHOULD do this, but you COULD.
Here is the page for isolating code under test, it includes an example for shimming a static class (DateTime) https://msdn.microsoft.com/en-us/library/hh549175.aspx
A few options ...
Review how the original developer said to modify the game
You could use something like JustDecompile to get their code.
Use Fakes as suggested above
Create your own assembly that calls into their assembly and hack the IL dynamically
This seems pretty close to this question: Can I redirect .NET method calls to a new method at runtime?
One of the answers to this post suggests looking at a library called Moles which seems to be similar to Detours and may help
Moles allows to replace any .NET method with a delegate. Moles supports static or non-virtual methods

How is compiler dealing with these Generic Plugin Interface instance methods?

I'm working with some, unfortunately largely undocumented, existing code and I'm having trouble understanding how it calls upon the methods of the plugins it loads.
My aim at the moment is simply to step into one of the methods loaded via the plugin manager, as it's causing an exception. However I had to rebuild the pluginManager from the source to get debug symbols and when I reference this new DLL version the compiler throws up arms.
The code appears to load the plugin into plug.Instance and then access the specific methods like so plug.Instance.ReturnLeaNumber();
This compiler error makes sense, because it doesn't know the details of the plugins. What confuses me is how the compiler ever knew these where valid before run time, when no plugins are initialized. I can step through the code that doesn't work now with the older DLL!
This is an example of where the program loads up a plugin.
plug = GenericServicePlugins.AvailablePlugins.Find(Application.StartupPath + "\\Dlls\\SchoolInterface.dll");
// Compiler doesn't like this next line anymore though
plug.Instance.Initialize(null, null);
If there are any differences between my rebuilt library and the previously working one, I can't tell how as the versions match up with the ones in our source control. Would appreciate some advice on where to start looking!
public interface IGenericPluginMasterInterface
{
String returnName();
void Initialize(ExceptionStringResources.Translate ExceptionStrings);
Object ExecuteFunction(String macAddress, bool log, String functionName, LoginCredentials logonCredentials, WebConfiguration webConfig,
Int64 dataLinkId, DataLinkParam[] dataLinkParams, String dataName,
DataParam[] dataParams, Object[] additionalParams);
}
Rest of Manager code on PasteBin
How does the compiler know about these plug.Instance.Method() methods before runtime?
Edit:
I've not quite worked this out yet, but there was a "PluginsService" file I missed which partly mirrors the "GenericPluginServices".
I think this error could have been caused when I removed parts of this class that related to an now defunct plugin, which I am looking into. However I figured posting this other code snippet would help the question.
PluginService.cs code
GenericPluginService code
Find returns AvailablePlugin, so .Instance is of type IGenericPluginMasterInterface; if so, indeed; that .Instance.ReturnLeaNumber() can't possibly work...
The only way that could work (without introducing some generics etc) is if .Instance actually returned dynamic. With dynamic the name/method resolution is happening at runtime. The compiler treats dynamic very deliberately such as to defer all resolution to runtime, based on either reflection (for simple cases) or IDynamicMetaObjectProvider (for more sohpisticated cases).
However, if the code you have doesn't match what was compiled, then: we can't tell you what it was. IMO, the best option is to get hold of the working dll, and look at it in reflector to see what it is actually doing, and how it is different to the source code that you have.
Actually, strictly speaking it could still do that with the code you've pasted, but only if plug is typed as dynamic, i.e. dynamic plug = ...

I want to modify an opensource wpf library, but update it as the donor library improves: how?

I'm intending to extend & alter an opensource library (LIB_A), which is itself composed of other libraries which have been modified for it's release.
My modifications are probably to be made to all of the libraries.
What is the best way to make subsequent importing of LIB_A into my library as painless as possible when new features are added/bugs are squished, without creating integration issues?
I was thinking of having my library sublass the classes I want to change, and override methods I want to change, but can't figure out if this is possible. The reasoning here is that I might only modify two methods in each class, so that when LIB_A bugs are fixed, if they're not in my modified methods - there is no collision, and I take advantage of the updates for free. If they are in the same method, there's no way around that, which I accept.
If I just copy the whole LIB_A, then I'll have to laboriously go through every file with a diff to see what has been changed, and then incorporate the updates. There must be an established way of doing this?
Is a source repository (local or otherwise) with it's associated check-in and diff behaviour the accepted method?
Thanks
EDIT: This SO question is asking exactly the same thing..
Well, you said it. If you can do it by subclassing, then by all means this is the simplest method.
The problem is that you not always can do it just via subclassing -- e.g. when you need to change a sealed or private method, change other non-virtual methods or properties etc. In this case, there is nothing you can do except to either (1) copy the code and create your own version, (2) modify the code such that those methods/properties are virtual and public -- but make sure it doesn't break anything elsewhere.
Even if you can subclass it, and the new version of the library does not touch the few methods that you overrode, you still have to test your changes fully agian, because your new code may depend on certain implementation details that the new version changed. Of course, the vendor of the library will have modified those few methods for the new version, but your version won't change. So the best way is to do a diff of the vendor's new version of your overridden methods with the old version to detect whether you need to change something in your own version as well.

Justification for Reflection in C#

I have wondered about the appropriateness of reflection in C# code. For example I have written a function which iterates through the properties of a given source object and creates a new instance of a specified type, then copies the values of properties with the same name from one to the other. I created this to copy data from one auto-generated LINQ object to another in order to get around the lack of inheritance from multiple tables in LINQ.
However, I can't help but think code like this is really 'cheating', i.e. rather than using using the provided language constructs to achieve a given end it allows you to circumvent them.
To what degree is this sort of code acceptable? What are the risks? What are legitimate uses of this approach?
Sometimes using reflection can be a bit of a hack, but a lot of the time it's simply the most fantastic code tool.
Look at the .Net property grid - anyone who's used Visual Studio will be familiar with it. You can point it at any object and it it will produce a simple property editor. That uses reflection, in fact most of VS's toolbox does.
Look at unit tests - they're loaded by reflection (at least in NUnit and MSTest).
Reflection allows dynamic-style behaviour from static languages.
The one thing it really needs is duck typing - the C# compiler already supports this: you can foreach anything that looks like IEnumerable, whether it implements the interface or not. You can use the C#3 collection syntax on any class that has a method called Add.
Use reflection wherever you need dynamic-style behaviour - for instance you have a collection of objects and you want to check the same property on each.
The risks are similar for dynamic types - compile time exceptions become run time ones. You code is not as 'safe' and you have to react accordingly.
The .Net reflection code is very quick, but not as fast as the explicit call would have been.
I agree, it gives me the it works but it feels like a hack feeling. I try to avoid reflection whenever possible. I have been burned many times after refactoring code which had reflection in it. Code compiles fine, tests even run, but under special circumstances (which the tests didn't cover) the program blows up run-time because of my refactoring in one of the objects the reflection code poked into.
Example 1: Reflection in OR mapper, you change the name or the type of the property in your object model: Blows up run-time.
Example 2: You are in a SOA shop. Web Services are complete decoupled (or so you think). They have their own set of generated proxy classes, but in the mapping you decide to save some time and you do this:
ExternalColor c = (ExternalColor)Enum.Parse(typeof(ExternalColor),
internalColor.ToString());
Under the covers this is also reflection but done by the .net framework itself. Now what happens if you decide to rename InternalColor.Grey to InternalColor.Gray? Everything looks ok, it builds fine, and even runs fine.. until the day some stupid user decides to use the color Gray... at which point the mapper will blow up.
Reflection is a wonderful tool that I could not live without. It can make programming much easier and faster.
For instance, I use reflection in my ORM layer to be able to assign properties with column values from tables. If it wasn't for reflection I have had to create a copy class for each table/class mapping.
As for the external color exception above. The problem is not Enum.Parse, but that the coder didnt not catch the proper exception. Since a string is parsed, the coder should always assume that the string can contain an incorrect value.
The same problem applies to all advanced programming in .Net. "With great power, comes great responsibility". Using reflection gives you much power. But make sure that you know how to use it properly. There are dozens of examples on the web.
It may be just me, but the way I'd get into this is by creating a code generator - using reflection at runtime is a bit costly and untyped. Creating classes that would get generated according to your latest code and copy everything in a strongly typed manner would mean that you will catch these errors at build-time.
For instance, a generated class may look like this:
static class AtoBCopier
{
public static B Copy(A item)
{
return new B() { Prop1 = item.Prop1, Prop2 = item.Prop2 };
}
}
If either class doesn't have the properties or their types change, the code doesn't compile. Plus, there's a huge improvement in times.
I recently used reflection in C# for finding implementations of a specific interface. I had written a simple batch-style interpreter that looked up "actions" for each step of the computation based on the class name. Reflecting the current namespace then pops up the right implementation of my IStep inteface that can be Execute()ed. This way, adding new "actions" is as easy as creating a new derived class - no need to add it to a registry, or even worse: forgetting to add it to a registry...
Reflection makes it very easy to implement plugin architectures where plugin DLLs are automatically loaded at runtime (not explicitly linked at compile time).
These can be scanned for classes that implement/extend relevant interfaces/classes. Reflection can then be used to instantiate instances of these on demand.

Categories