One use case for interfacing with a legacy WCF is to hide all the .NET service code behind a more modern RESTful API to which we Post the (seemingly correct) XML, and deserialize it to the WCF class we need require.
A common problem is deserialization errors due to XML elements being in the wrong order. The most subtle of which is Out of order elements being silently discarded during deserialization, and it's resulting sub Class or Property value being null.
We require a viable solution that doesn't involve the risky removal of Order attributes or other manipulation of the service Classes because it could have unintended consequences for the remainder of the WCF service.
I tried to use reflection to generically create this ordered list for a given Class. It appeared to work but Class inheritance causes parent elements to appear in the wrong order.
Below is the method that I settled on - it's a bit onerous but you'll only have to do it once for each data Class and it's highly transparent when troubleshooting.
The aim of the game is to sort the Posted XML before deserializing, using a reference order for the elements / XPaths.
Step 1 probably already done if you found this article
myservicename.wsdlfile to generate all the service reference Classes usingDataContractSerializeras the preferred serializer.Step 2 schema extraction
myservicename.wsdlin an XML editor and Locate the schema which contains the data Class definition note that you need to search for it by it'sDataContractAttribute NameStep 3 Generate sample Xml File (include every possible element)
Altova XmlSpyfor this but there are other optionswsdland saving them, adding them to the Class schema withxs:importand settingschemaLocationto file pathsStep 4 In C# prepare for Xml sorting. Convert the sample XML to an XPath + order dictionary
Step5 sort the incoming Posted XML before deserializing