Posts Tagged ‘MSIL’

Deserializing data into a dynamically loaded Assembly

What does scripting languages like php, Perl, python offer over compiled languages? Well if you ask me i would say the ease of development. Make a change in the code and then see the change reflected quickly. This is one of the main reason why scripting is preferred in the web environment. Majority of the websites these days are powered by php in the LAMP stack. Performance of scripted language is far lower than any compiled binary. Compare that with the ASP.NET. The scripts are compiled into MSIL and run on the .NET runtime. Even without caching the ASP framework is almost 2-3 times faster than the Apache on php with mysql. I am not a MS fan-boy nor an open source evangelist.  I had the privilege on doing extensive development on both platforms. There are times when i wished for a platform which had the best of both worlds. When php scores on flexibility for advanced developers. ASP.NET scores on its default ability to separate UI from Logic. Enough of this Web programming. Let me get into what i started out to do.

I had been working on a .NET project where  a DLL A.dll is being used by two different applications. On one application i create an object of a class C inside A.dll, fill its members and serialize it into a binary stream using the standard .NET serializer  and save it into a file. On the second application when i get a request to load the data from the file, I dynamically load the Assembly A.dll. Then i open the file that i saved the byte dump then deserialized it back into an object of the class. Sounds easy, Not so… I was getting an Exception.
System.Runtime.Serialization.SerializationException: Unable to find assembly ‘A’. 

Then i compiled the dll with the application and checked whether its working.  I then got another exception while casting the Deserialized object into a variable of type A.C

Unable to cast type A.C into A.C. 

What the hell!!!  That was my first impression. This was one of the least helpful messages the Visual Studio debugger threw at me. I then tried searching for related resources online in vain.  That’s when i came across this elegant solution involving AppDomains and Serialization Binders. Needless to say my deserialization worked on the dynamically loaded assembly. You can find more details about creating AppDomains here.

I am attaching my C# code below. Hope this proves helpful to you. Look at the serialization binder class in the Deserialize function. The binder class allows you to change the type to which you want to deserialize the byte array to.

 Continue reading