Send Object as parameter to Dll function - c#

I have a Class Library (dll) that holds operations with reports. My dll needs a object to fill the desired report.
The problem is that I can't convert the object from my main .exe to the same object in the dll.
[A]MyMainEXE.Model.MyObject can't be converted to [B]MyClassLibrary.Model.MyObject
The type A cames from 'MyMainEXE', Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'
in the context 'Default' at
'C:\fakepath\DummyName.exe'.
The type B cames from 'MyClassLibrary', Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'
in the context 'Default' at
'C:\fakepath\DummyName.dll'
I'm just trying to pass like this:
doWorks(myObjectname);
and receive like this:
public void doWorks(object myobject)
{
MyObject thing = (MyObject) myobject;
//Do something
}
I already know how to pass using a array or List but
Why can't I do with objects?/What am I doing Wrong?

Since both objects are of the same name but probably different namespace, I think you have to serialize/deserialize the object from MyMainEXE.Model.MyObject to XML/Binary to MyClassLibrary.Model.MyObject

Related

Binary serialization between .NET Core and .NET

So i have dictionary of key and value where value is an object, when exchanging the binary data between .NET Core and .NET and vice versa the serialization fails with
System.Runtime.Serialization.SerializationException: 'Unable to load type System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Collections.Generic.IDictionary`2[[SharedLib.HostPropertyType, DataInterfaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]] required for deserialization.'
which makes perfect sense since target type is located in another library, the question is whether there is a way to avoid this without creating custom types ?
Thanks.
Although it's something you haven't specified, it looks like you're using the BinaryFormatter. This is a awkward formatter to use, becasue it can be very picky about what assemblies the types it uses comes from, which it looks like you've run in to.
However, you should be able to specify how the formatter binds its types by setting the Binder property.
If you check out the MS Docs link above, you should be able to see what you need to do. I've copied it here too:
sealed class Version1ToVersion2DeserializationBinder : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
Type typeToDeserialize = null;
// For each assemblyName/typeName that you want to deserialize to
// a different type, set typeToDeserialize to the desired type.
String assemVer1 = Assembly.GetExecutingAssembly().FullName;
String typeVer1 = "Version1Type";
if (assemblyName == assemVer1 && typeName == typeVer1)
{
// To use a type from a different assembly version,
// change the version number.
// To do this, uncomment the following line of code.
// assemblyName = assemblyName.Replace("1.0.0.0", "2.0.0.0");
// To use a different type from the same assembly,
// change the type name.
typeName = "Version2Type";
}
// The following line of code returns the type.
typeToDeserialize = Type.GetType(String.Format("{0}, {1}",
typeName, assemblyName));
return typeToDeserialize;
}
}
The general idea that you want to do I think is essentially tell the formatter that it's OK to use the .net core version of the IDictionary, by swapping the assembly that it's looking for with the one you're using.
As you haven't specified exactly what versions of .net core and fraemwork you're using, I can't really be any more specific, but that should help you out.

'object' does not contain a definition for '...' within same assembly

Per my boss' recommendations, we are using Dapper to access our database. As this is just a quick, throwaway project, he would like to forego creating POCO objects for the results of these calls to the database, so we're just having Dapper return dynamic objects.
So I have several Web API controllers, all deriving from the same BaseController. In the base class, we have a method like this:
protected dynamic ExecuteSingle(string sql, object parameters = null, bool useStoredProcedure = true) {
using (var db = ObjectFactory.GetInstance<IDbManager>())
{
var cmd = useStoredProcedure ? db.SetSpCommand(sql) : db.SetCommand(sql);
if (parameters != null)
{
cmd = cmd.SetParameters(parameters);
}
return cmd.ExecuteObject<dynamic>();
}
}
We are able to use that successfully when taking that result and passing it as the parameter to a Ok() return value. All of the properties of the object get successfully parsed into the JSON object.
I'm now working on another section of code where instead of immediately spitting it back out, I need to use the data coming back to hit another set of functionality.
var sql = " SELECT Id FROM Table WHERE ReviewId = :ReviewId ";
dynamic dbSurvey = ExecuteSingle(sql, new {ReviewId = reviewId}, false);
var survey = sg.GetSurvey(new GetSurveyRequest(dbSurvey.Id));
It then fails on that last line where calling dbSurvey.Id with an exception saying
'object' does not contain a definition for 'Id'
Checking the object, there is a property on there named "Id".
I have checked several questions already, and even though they are all dealing with Anonymous objects (which I could understand dynamic being under that heading), I am staying within the same assembly, so those points about Anonymous objects being declared as "internal" wouldn't apply in this case.
I also tried changing the return type of ExecuteSingle to an ExpandoObject, but am getting the same results.
EDIT
Here is a screenshot of how it is being called, versus the object and properties that it contains. Perhaps the format of the properties could help determine why it's not being found.
I also used the Watch menu to try various ways to access the property, and none of the following worked:
dbSurvey["Id"]
(dbSurvey as IDictionary<string, long>)["Id"]
((IDictionary<string, int>)dbSurvey)["Id"]
Here is the result of dbSurvey.GetType() from the immediate window while running:
{<>f__AnonymousType2`1[System.Int64]}
base: {Name = "<>f__AnonymousType2`1" FullName = "<>f__AnonymousType2`1[[System.Int64, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"}
Assembly: {***.Web.Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null}
AssemblyQualifiedName: "<>f__AnonymousType2`1[[System.Int64, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], ***.Web.Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
BaseType: {Name = "Object" FullName = "System.Object"}
ContainsGenericParameters: false
DeclaringMethod: 'dbSurvey.GetType().DeclaringMethod' threw an exception of type 'System.InvalidOperationException'
DeclaringType: null
FullName: "<>f__AnonymousType2`1[[System.Int64, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"
GenericParameterAttributes: 'dbSurvey.GetType().GenericParameterAttributes' threw an exception of type 'System.InvalidOperationException'
GenericParameterPosition: 'dbSurvey.GetType().GenericParameterPosition' threw an exception of type 'System.InvalidOperationException'
GUID: {382c0269-d631-3c89-a105-38a1be8a3db7}
IsConstructedGenericType: true
IsEnum: false
IsGenericParameter: false
IsGenericType: true
IsGenericTypeDefinition: false
IsSecurityCritical: true
IsSecuritySafeCritical: false
IsSecurityTransparent: false
MemberType: TypeInfo
MetadataToken: 33554480
Module: {***.Web.Test.dll}
Name: "<>f__AnonymousType2`1"
Namespace: null
ReflectedType: null
StructLayoutAttribute: {System.Runtime.InteropServices.StructLayoutAttribute}
TypeHandle: {System.RuntimeTypeHandle}
UnderlyingSystemType: {Name = "<>f__AnonymousType2`1" FullName = "<>f__AnonymousType2`1[[System.Int64, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"}
OK, so I resolved this issue. I just figured out what the problem was. Thanks to xanatos' help in the comments, we noticed that the Module property of the type was coming from the Test harness. That didn't make any sense to me at the time, because the dynamic object was being created in the same assembly.
However, what I didn't think about until I came back to the issue this morning was that the source of the object being "created" in the base API Controller was an anonymous object that I was creating in the Test harness. So that Module was correct.
If I went and created a separate POCO object for the Mock object in the Test DLL, then it was no longer creating a dynamic off of an anonymous object created in another assembly.

InvalidCastException, wrong context?

I have an exe that does data dumps. The exe will dynamically pick up DLL's based on configuration and pass a class object into it. The DLL has a copy of this class compiled with it and can see the data, under debug, without a problem as an object. However, when I try to cast that to the class, it tells me it can't because of the context. I'm sure I've overlooked something as I do that at times.
Error:
[A]MyClass cannot be cast to [B]MyClass. Type A originates from
'MyExe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the
context 'Default' at location 'C:\MyPath\MyExe.exe'. Type B originates
from 'MyDLL, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in
the context 'LoadNeither' at location 'C:\MyPath\MyDLL.dll'.
EXE Code:
Object[] param = new Object[] { MyClass };
MethodInfo m = type.GetMethod("MyMethod");
reader = (SqlDataReader)m.Invoke(obj, param);
DLL Code:
public SqlDataReader MyMethod(Object param)
{
SqlDataReader reader = new SqlDataReader();
Type t = param.GetType(); //Returns MyClass
if (param is MyClass) //Returns false
reportItem = (MyClass)param; //Never executes
MyClass reportItem = (MyClass)param; //InvalidCastException
//other code here, pulling data
return reader;
}
The DLL has a copy of this class compiled with it
Don't do that, basically. You should have the type in one assembly, and only one assembly. As far as the CLR is concerned, these are entirely different types.
You probably want to have a common library which both the plugins and your application can refer to. Or you could make your plugins refer to the application executable and keep the type within there.

Why am I getting assembly version as 0.0.0.0? Will that make any issues if real DLL has some version number and using Type class to retrieve values?

I have a project named "Test.LiveModel" (Test.LiveModel.dll) and its version is 8.0.7.0 in my solution which contains 25 projects. I can see the information of Test.LiveModel in AssemblyInfo.cs. I have two category of objects named 'base class category' and 'user-defined class category' which are displaying in my application UI. I am displaying this through a property which is of class Type
Now I am considering one base class category object named "Server" and one user-defined class category object RoundedTree. When I set value as "Server" in Property in Grid after saving it when I restart my application I can see the saved value, but for "RoundedTree" which is not happening due to type becomes null. So I did a thorough analysis and came to know that issue is in ToType() method shown below
This is ToType() metho
For base class Server xmlSerializableType.Name, I am getting as Test.LiveModel.Server and AssemblyName I am getting as Test.LiveModel, Version=8.0.7.0, Culture=neutral, PublicKeyToken=23bd062a94e26d58 and type I am getting by using Type.GetType as type = {Name = "Server" FullName = "Test.LiveModel.Server"}
But for user defined class xmlSerializableType.Name I am getting as _Rounded_Tree. 'type' I am getting as null by using Type.GetType. AssemblyName I am getting as _Rounded_TreeTest-Machine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null, but even assembly.GetType I am getting as null. What is the reason behind it? Why am I getting assembly version 0.0.0.0? I mean full assembly _Rounded_TreeTest-Machine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null.
This is the method CreateType() which will create assembly and type as myTypeBuilder for userdefined class:
public Type CreateType()
{
// Create the assembly name by appending the machine name to the typename.
myAsmName.Name = this.TypeName + Environment.MachineName;
// Define assembly that can be executed but not saved
this.UserClassAssemblyBuilder = myDomain.DefineDynamicAssembly(myAsmName, AssemblyBuilderAccess.Run);
// Create dynamic module with symbol information
this.UserClassModuleBuilder = this.UserClassAssemblyBuilder.DefineDynamicModule("userdefinedmodule", true);
So here is my question: if real Dll has some version number, and user defined class assembly has version 0.0.0.0, is that the reason why I am getting type as null after using Type.GetType and assembly.GetType method?
Here are some suggestions which may solve the problems.
Define a assembly version
new AssemblyName(this.TypeName + Environment.MachineName)
{
Version = new Version("1.0.0.0")
};
Use full qualified names for the serialization
myObject.GetType().FullName

Get Assembly Names in Current Application Domain

I want to get Assemblies Friendly Names in Current Application Domain and hence I wrote something like this :
static void Main(string[] args)
{
foreach (System.Reflection.Assembly item in AppDomain.CurrentDomain.GetAssemblies())
{
Console.WriteLine(item.FullName);
}
}
But the problem is this is the output what I got rather than what I desired to see :
mscorlib, Version=2.0.0.0,
Culture=neutral,
PublicKeyToken=b77a5c561934e0
ApplicationDomains, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null
Actually I was expecting those names :
alt text http://www.pixelshack.us/images/xjfkrjgwqiag9s6o76x6.png
Can someone tell me if there is something I mistook.
Thanks in advance.
Or the names I was expecting weren't assemblies ?
You won't always get the pretty namespace names when you use reflection, you get the real names of the assemblies.
You also won't get all referenced libraries, only the ones that CURRENTLY loaded. If you add "XmlDocument foo = new XmlDocument()" above your code, System.XML will show up.
static void Main(string[] args)
{
XmlDocument foo = new XmlDocument();
foreach (System.Reflection.Assembly item in AppDomain.CurrentDomain.GetAssemblies())
{
Console.WriteLine(item.FullName);
}
}
Output:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
ConsoleApplication2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
It's impossible to get list of all referenced assemblies during runtime. Even if you reference it in your visual studio project, if you don't use them, C# compiler will ignore them and therefore they won't make it into your output file (exe/dll) at all.
And for the rest of your assemblies, they won't get loaded until they are actually used.
AppDomain.CurrentDomain.GetAssemblies() gives you array of all loaded assemblies and this list could be very different from what you see in visual studio project.
foreach(var assem in AppDomain.CurrentDomain.GetAssemblies())
{
Console.WriteLine(assem.GetName().Name);
}
Assembly.GetName() returns an AssemblyName object which has a Name property. That's what you're looking for.
Either use Assemly.GetName().Name or use reflection to find the AssemblyTitleAttribute and use that value.

Categories

Resources