Fixing DataContractSerializer issues in builds compiled with .NET Native

With UWP apps having mandatory .NET Native compilation before uploading to the Store, a new kind of issues have started to pop up: those caused by types and methods not processed (or stripped) by the native compilation process.

While working on a pretty complex app I started experiencing this: everything worked good on Debug and Release builds that had .NET Native compilation turned off, but the moment it was switched on, the app started to experience weird crashes and exceptions raised in parts of the code that used to work without any flaws; the majority of them were related to data serialization, especially of types that relied on DataContractAttribute / DataContractSerializer.

While Microsoft published a list of instructions for migrating existing codebases to .NET Native and even it has a section explaining all issues that can happen with the different types of serialization, if you skip any of the types while updating the runtime directives file, tracking down what is happening can be a bit frustrating.

In this case, I was experiencing InvalidDataContractExceptions followed by the typical .NET Native call stack with no symbols:

Serialization exception: System.Runtime.Serialization.InvalidDataContractException: SerializationCodeIsMissingForType. For more information, visit http://go.microsoft.com/fwlink/?LinkId=623485
   at App!<BaseAddress>+0xb51dc8
   at App!<BaseAddress>+0xb525aa
   at App!<BaseAddress>+0x1384c9c
   at App!<BaseAddress>+0x13846a0
   at App!<BaseAddress>+0xb420fc
   at App!<BaseAddress>+0xb4203b

This will happen in a code block that is using DataContractSerializer. So, get the type of the variable being serialized and add it to the default runtime directives file, which should be part of your project and called Default.rd.xml under the Application XML node:

<!-- Make all members of a type visible to .NET Native -->
<Type Name="App.Models.MyModel" DataContractSerializer="Required All" />

<!-- Make all members of all types inside the namespace visible to .NET Native -->
<Namespace Name="App.Data.Models" DataContractSerializer="Required All" />

This tells .NET Native to include all members needed for serialization through DataContractSerializer so they can be properly accessed at runtime, fixing all issues that were present on the app. Please note that if you are using DataContractJsonSerializer, XmlSerializer or other third party serializers like the Newtonsoft JSON one, the changes to the Default.rd.xml file will be slightly different.