15 October, 2010

WP7: Using DataContractSerializer and internal types => SecurityException

If you want to be able to store types on disk and these types are internal, you can not use the standard XmlSerializer; but will have to use the more recent DataContractSerializer. However - you run into a problem as you will be presented with a SecurityException stating your application failed to communicate with the server. This is in reality nonsense, but you can workaround this problem by adding an InternalsVisibleTo attribute in your assemblyInfo.cs file. This attribute should allow System.Runtime.Serialization assembly to load your internals.

[assembly: AssemblyCopyright("Copyright ©  2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: InternalsVisibleTo("System.Runtime.Serialization, PublicKey=00240000048000009400000006020000002400005253413100040000010001008d56c76f9e8649383049f383c44be0ec204181822a6c31cf5eb7ef486944d032188ea1d3920763712ccb12d75fb77e9811149e6148e5d32fbaab37611c1878ddc19e20ef135d0cb2cff2bfec3d115810c3d9069638fe4be215dbf795861920e5ab6f7db2e2ceef136ac23d5dd2bf031700aec232f6c6b1c785b4305c123b37ab")]

Technorati Tags:


Hades32 said...

Thanks for your tip. But all my classes were already public...
I found out that I had to use ObservableCollection instead of List...
But I have NO IDEA why...

Claus Konrad said...


A List is ment as a container of items to be serialized. You are not ment to serialize the list itself. It is intended as an internal contruct for manipulating data. The difference between List and ObservableCollection is that the latter implements INotityPropertyChanged which is quite convenient when you are doing databinding (e.g. Silverlight).
But to finish - both objects (List/ObservableCollection) are marked as [serializable].

Claus Konrad said...

And secondly, see this post on an example (and download) on how to serialize on WP7.