Introduction
This is just a quick tip to help people avoid issues with XML serialization in .NET 4.5, particularly with applications written in 4.0 or earlier versions.
Background
I spent a number of days trying to figure out why our application written in .NET 4.0 can't serialize CLR objects to XML if .NET Framework 4.5 is installed. Backwards compatibility has never been an issue for me in .NET which is why I found this particular problem quite so frustrating. Given that frustration, if this tip helps only one other person avoid this problem I'll be a very happy man.
I kept on getting the following exception when calling XmlSerializer.Serialize
:
System.InvalidOperationException: There was an error generating the XML document.
---> System.InvalidProgramException: Common Language Runtime detected an invalid program.
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterFrmFrm.Write53_FrmTable(
String n, String ns, FrmTable o, Boolean isNullable, Boolean needType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterFrmFrm.Write55_FrmFrm(
String n, String ns, FrmFrm o, Boolean isNullable, Boolean needType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterFrmFrm.Write56_frm(Object o)
--- End of inner exception stack trace ---
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o,
XmlSerializerNamespaces namespaces, String encodingStyle, String id)
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o)
Messing around with version settings didn't help one bit, e.g.:
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
Neither did changing the project settings:
I eventually managed to formulate a search that found an answered question on StackOverflow:
Which pointed me in the right direction. I was certain that it was something to do with the .NET versions, but how to configure it so that it actually works?
Using the code
All you need to do is to tell the CLR in your .config file to use the legacy XmlSerializer
that isn't part of version 4.5. For this there is a dedicated configuration section:
<configuration>
<system.xml.serialization>
<xmlSerializer useLegacySerializerGeneration="true"/>
</system.xml.serialization>
</configuration>
In the process I learnt a bit about how the different .NET major and minor versions relate to each other. 4 and 4.5 are basically just CLR 4. Once you install 4.5 the CLR assumes you want to use the latest and greatest XmlSerializer
instead of the one that ships with 4.0, so you have to explicitly tell the CLR which one to use.
History
- 19.06.2013 - First version.