mercredi 1 décembre 2021

How to get all types into a reference interop assembly

I have a couple interop assemblies which i need to get all types in them. I have seen this question and it does not work and doesn't apply to my case. All these referenced assembly are used in my application directly but are not showing anywhere.

What i have tried and with the results i get is the following. Note that i simply tried with a single random class i have laying around and it does do same for all the other interop library i have in the project.

// Doesn't contain the assembly SldWorks.
var allAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();

// {MyApp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null}
// this is wrong
var assemblyOfClassInDLL = System.Reflection.Assembly.GetAssembly(typeof(Component2));

// {MyApp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null}
// this is wrong
var assemblyOfClassInDLL2 = typeof(Component2).Assembly;

// SldWorks.Component2, MyApp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// this is very wrong
var assemblyNameOfClassInDLL = typeof(Component2).AssemblyQualifiedName;

// Doesn't contain the assembly SldWorks.
var referencedAssemblies = System.Reflection.Assembly.GetExecutingAssembly().GetReferencedAssemblies();

try
{
    var testLoad = System.Reflection.Assembly.Load(assemblyNameOfClassInDLL);
}
catch (Exception ex)
{
    // Could not load file or assembly 'SldWorks.Component2\, MyApp\, Version\=0.0.0.0\,
    // Culture\=neutral\, PublicKeyToken\=null' or one of its dependencies. The given assembly name or codebase
    // was invalid. (Exception from HRESULT: 0x80131047)
}

Note above that Component2 is a class within the assembly SldWorks which is an interop dll. Although the only line that seems to find it is typeof(Component2).AssemblyQualifiedName which return it wrong as it thinks it's in MyApp. Then you see in the Try...Catch that i am tryin to load that same assembly i just receive from the code and it crashes. Why C# return an assembly name that definitively do not exist ?

It msut be possible as i can in visual studio browse everything within the Object Browser window. So if the solution is to use the same code the Object Browser window does it's not an issue and performance either. This code save literally about 2 or 3 days work every time it's used instead of writing manually every class in a DLL in the code and update every time the companies release automatic updates.

I only have 2 requirements :

1 - I ONLY get to receive an object that i need to find it's type and assembly it come from and return all the types in the same assembly

2 - My app is a dynamically loaded addin so it is NOT an executable





Aucun commentaire:

Enregistrer un commentaire