WP7dev

Windows Phone 7 development tips

Tag Archives: crash

One of the known types provided to the serializer via ‘knownTypes’ argument was invalid because it was null.

When using multiple projects in the same solution where your main project references data types declared in another project or assembly, you may encounter crash when getting out of tombstoning.

For example in this project :

Project overview

Class1.cs :


public class Class1

{

    public String str { get; set; }

}


MainPage.xaml :


public MainPage()

{

    InitializeComponent();

    ClassLibrary.Class1 test = new ClassLibrary.Class1() { str = “test” };

    var store = PhoneApplicationService.Current.State;

    store[“test”] = test;

}


If your MainPage.xaml or App.xaml saves any object of type Class1 to PhoneApplicationService.Current.State, when getting back from tombstone, you will get an Exception :

One of the known types provided to the serializer via ‘knownTypes’ argument was invalid because it was null. All known types specified must be non-null values.

The reason behind this is quite simple, yet hard to find the first times you run through it. When going to tombstone mode, WP7 serializes the current application state, when getting back from it, serialized state is deserialized and loaded back into memory. But when using data types from another project, WP7 tries to deserialize data before loading other assemblies data types. This explains the exception : Class1 is not a known type when it tries to get deserialized.

How to work around this bug ? Quite easily. We’re lucky enough that in App.xaml.cs, the constructor (App()) gets called before the Application State is deserialized. All we have to do is to force the framework to create an object from ClassLibrary :

App.xaml.cs


public App()

{

    ClassLibrary.Class1 dummy = new ClassLibrary.Class1();

    dummy.str = “”;


By doing this, the framework creates an instance of the desired class before deserializing the application state. Thus, the assembly defining your type is loaded, and the exception disappear. In release mode, you need to add the second line (dummy.str = …), assigning a value to one of your class attributes, to avoid your statement from being completely removed by compiler optimizer.

This is based on Windows Phone 7.0 framework, I hope this bug will get fixed in later versions and this workaround won’t be needed any more.

You can get the project used to reproduce this bug here.