C# DLL Injection - Call Method of Running Application - c#

Lets say I have an executable 'foobar.exe' written in C# and now compiled, running on a Windows box. One of the functions in the application is the following (example):
public static async Task LoadBox(string msg)
{
System.Windows.Forms.MessageBox.Show(msg);
}
I would like to write a DLL in C# that calls this method in the application. The DLL, say 'injected.dll', will be injected into the running 'foobar.exe' process using the injector referenced here: http://www.codingvision.net/miscellaneous/c-inject-a-dll-into-a-process-w-createremotethread
Is it possible from the newly injected DLL to call the public function in the original exe? If so, any example code in C# would be appreciated.

My approach would be to use the concepts of Reflection. We could make the EXE load an assembly through reflection, discover a Type and invoke a method on this Type and then pass an instance of a class in your EXE to this method, which in turn does a call back. A round about way - but it would work.
You can use the method System.Reflection.Assembly.LoadFrom( to load an assembly compiled for .NET. This is a fairly old technique, nothing new about it. Dependency contains and applications that are meant to load plugins post deployment are written using this method.
Step 1
Load the plugin assembly into the current Appdomain using System.Reflection.LoadFrom
Step 2
Find the Type in this plugin assembly by using Assembly.GetTypes()
Step 3
Pass an instance of a class defined in your EXE into the plugin and have the plugin do a call back. This is what an event call back would actually do.
Link
https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance?view=netframework-4.7.2#System_Activator_CreateInstance_System_AppDomain_System_String_System_String_System_Boolean_System_Reflection_BindingFlags_System_Reflection_Binder_System_Object___System_Globalization_CultureInfo_System_Object___

Related

How to run managed code on different version assemby

I'm working with one application that that has and C# API. This program has different versions of it. But the api stays the same through its versions.
So i have written a managed code to one of its versions, and now i want to run the same code at different version of the application at runtime where i exactly know witch version of the app is running.
Question is:
Is it possible to replace assembly version and dll location at run time without writing unmanaged code using reflections?
Yes, you can use Assembly.LoadFrom to load an assembly. You can then use reflection to go thru the types of said assembly and call methods.
To avoid needing to use reflection for everything there should be a shared interface-assembly that define your api. There should also be a single entry point to the API. So you can use reflection find the class that implements the entry-interface, create an instance of this class and cast it to the interface. That lets the rest of the code use actual types.
You still need to be careful however, if there is any miss match between the interface and the actual types, you will get an runtime exception. You will not get an exception when the interface method is called (as might be expected), but when the method that calls the interface method is called. This due to the jitter resolving types when a method is compiled, and this is done the first time it is called.

How do I know that a method in a DLL calls a method of another DLL?

For example:
There is API a.1 in DLL A and API B.1 in DLL B.
API A.1 calls API B.1.
Is there an open source tool or method to know this call path(A.1->B.1)?
.Net assemblies contain a list of referenced assemblies. This can be inspected by tools like IL SPy.
There is no easy way to check if a specific method on one assembly may calls another assembly. You could perhaps inspect the CIL code for this, but it will require a bit more work.
There is also native dependencies, these are not listed in the same way, and use another method to load.

How to handle dynamically loaded managed libraries in c#

I wrote an application in C# and added a kind of API for it.
With this API you can write plugins as dll´s which underlie some interface rules.
I want to make it possible to open the dll file via OpenFileDialog and use its content.
My API is a managed library, so I just add a reference, but I want to use the dll without knowing the name of the dll file. Also the namespace is another each library.
How do I load a dll and run the code within it?
What you are describing is commonly termed a Plugin System. Googling for something like "Create Plugin system using C#" will probably give you lots of information such as the below:
http://www.codeproject.com/Articles/4691/Plugin-Architecture-using-C
The basic idea is:
Define an interface that your program implements to allow a plugin to get information from your program.
Define an interface that all plugins will implement, to allow your program to call the plugin's methods that will do something.
Put those interfaces in a separate dll that's referenced by your program and by any plugin dlls.
Provide some way of finding dlls with types implementing your plugin interface, e.g. your OpenFileDialog.
Load the dll and find types that implement your plugin interface (using reflection).
Instanciate those types using reflection.
Call the methods on those types via the interface, as appropriate.
Regarding managed/non-managed. A managed DLL is one that is built/coded using the .net managed runtime. This would be things coded in a .net language such as c#.
A non-managed dll is more or less anything coded in a different language.
What you referred to as a non-managed dll I would refer to as a dynamically loaded managed dll. I.e. it's still a managed dll (coded in a .net language), but isn't loaded until the program is already running.
You can load a managed assembly from a dll file with Assembly.LoadFrom Method (String) (See also Best Practices for Assembly Loading).

Console App to start a CodedUI test

I have a coded ui test that I want to start by using batch, its a .dll file.
The reason I'm calling it from a batch file is that the server has to be restarted before this test can be carried out.
Is it just a simple call test.dll or do I have to do other stuff?
Update Code Found
Playback.Initialize();
TestProject.CodedUITest1 coded = new TestProject.CodedUITest1();
coded.CodedUITestMethod1();
Playback.Cleanup();
Take from Here, Its missing two reference addings from the private assemblies:
Microsoft.VisualStudio.TestTools.UITest.Extension.Uia.dll
Microsoft.VisualStudio.TestTools.UITest.Extension.IE.dll
Hope this helps other people looking to do this
You can't run a Dll file like you can an exe. A Dll contains code intended to be used by a program, it means one source of code can be used by many programs, which saves duplicating the code.
Usually the Dll will have documented functions you can call via a program, unless you built it yourself in which case you would know :)
Try and find the program that uses the Dll and call that, or find the docs for it and run the function from rundll32 as #PA. suggested.
DLLs are dynamic libraries that need to be linked and called from an application program. Every DLL has its own exported interface, or collection of entry points to be called from the external executable, or, may be, from another DLL.
Windows provides a set of calls to help caller programs to load, detect entry points, and unload DLLs. Beyond this limited common functionality, there are endless combinations of ways of using a DLL, in the calling conventions, in the ways of passing parameters, in the types of the parameters, in the ways of returning data, in the ways of synchronizing, notifying events, interrupting, multithreading, in almost every aspect of programming models.
Having said so, it is possible that your DLL is expected to be called from some specific application program, and thus is possibly following and strict and well defined API. One such type of DLLs are Windows System DLLs that are intended to be run with rundll executable program. rundll32.exe is the Windows system executable that launches and invokes functions that are packed and shipped in .dll files, from a DLL that is explicitely programmed to be called this way.
to invoke your TestFunction inside your TEST.DLL, passing 1234 as a parameter, you'd use
RUNDLL32 TEST.DLL, TestFunction 1234
Rundll will perform for you the following tasks
Load TEST.DLL via LoadLibrary().
Address the TestFunction function via GetProcAddress().
Call TestFunction function, passing the rest of the command line
Unload the DLL and exit.

Marshalling Assembly from another AppDomain

Is it possible to hold a reference to an Assembly from another appdomain without having that assembly loaded into the current appdomain?
I'm working on fixing a memory leak in a Windows Service that dynamically generates Assemblies and runs the dynamically generated code. The problem is the generated Assemblies are loaded into the Current app domain and can never be unloaded.
There is a method in one of the Windows Service libraries that has the follow signature:
public Assembly CreateMethod(ObservableCollection<Field> sourceFields, Field destinationField)
This method creates the code for the assembly and loads it with the CSScript library LoadMethod function:
result = CSScript.LoadMethod(scriptFunction.ToString());
Later this Assembly reference from CreateMethod is used to run a function inside the generated assembly.
public object Run(Field destinationField, ObservableCollection<LinkField> sourceLinkFields, DataRow mainRow, Assembly script) {
...
var method = script.GetStaticMethodWithArgs("*.a" + Id.ToString().Replace("-", String.Empty), argumentTypes.ToArray());
return method(arguments.ToArray());
}
I'm wondering if it is possible to load the dynamically generated assembly into another app domain and run them through some type of proxy without having it loaded into the current app domain.
Edit:
I want to know if I can use an Assembly class reference in one AppDomain when the assembly is loaded in another AppDomain. Looking at the MSDN documentation they show how to use MarshalByRefObject. Basically I am trying to avoid changing the signature to my CreateMethod function, however I may need to change it to return MarshalByRefObject if this is not possible.
Update:
I ended up putting the call to CSScript.LoadMethod in the other app domain where I keep a Dictionary I then made CreateMethod return a Guid instead of an Assembly and then I pass this Guid around until the Run call. The Run call now takes a Guid as an argument instead of an Assembly. Inside the Run call I pass the Guid to the other app domain, run the method, and return the result object through a class that inherits MarshalByRefObject.
If you don't want the dynamic assembly in your main AppDomain, you have to move CreateMethod to another AppDomain, because as soon as you have an instance of Assembly, it's been loaded. In other words, no it is not possible to hold a reference to an assembly in another application domain, only to call into that assembly across application domains.
Without changing the signature and a bunch of your code, it seems like you need to move the minimum amount: 1) assembly creation and 2) Run. Then have the implementation of Run marshall the results.
As far as CreateMethod I think you want a method in the other assembly to "wrap" CreateMethod and return some sort of token that can be passed to Run. It's almost like changing the signature in a way...
This is one of the major features of an AppDomain! Just go look at the documentation

Categories

Resources