R – Problem using XmlSerializer to Serialize/Deserialize a class between a Silverlight Library and an MVC App

asp.net-mvcsilverlightxml-serialization

Here is my situation:

I have a solution with three projects: 1) Silverlight App, 2) Silverlight Library, 3) the Asp.net-MVC Web App.

In the Silverlight Library I have a class called "MyClass". In the Silverlight App I serialize that class to XML using XmlSerializer and send the XML back to the database. I retrieve and deserialize that XML periodically in the Silverlight App to use MyClass.

My problem comes when I try to deserialize that XML from within the Asp.Net-MVC App. Inside the Asp.Net-MVC App this is the code I use to deserialize the XML to MyClass:

 MySilverlightLibrary.MyClassObjects.MyClass newMyClass = null;

 Assembly ass = Assembly.Load("MySilverlightLibrary.MyClassObjects");
 Type ty = ass.GetType("MySilverlightLibrary.MyClassObjects.MyClass", true);

 XmlSerializer theSerializer = new XmlSerializer(ty);

 if( !String.IsNullOrEmpty(xmlText) )
 {
    using( XmlReader sr = XmlReader.Create(new StringReader(xmlText)) )
    {                 
       newMyClass = theSerializer.Deserialize(sr) as MySilverlightLibrary.MyClassObjects.MyClass;
    }
 }  

This is the runtime error I get:

Server Error in '/' Application.

Could not load file or assembly 'System.Xml, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. The system cannot find the file specified.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileNotFoundException: Could not load file or assembly 'System.Xml, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. The system cannot find the file specified.

I noticed that the version of the "System.Xml" reference in the Silverlight Library project is 2.0.5.0, but the "System.Xml" reference is 2.0.0.0 in the Asp.Net-MVC App. I assume that this is likely the cause of the issue, but I can't figure out how to fix it!

I have been messing with this for quite some time now and it's driving me nuts! As always, any help would be greatly appreciated!

Thanks

Jeff

Best Answer

You are correct - the cause of the problem you are having is the mismatched versions. I believe you can solve this with Assembly binding redirection.

Related Topic