When creating a Web Part in SharePoint 2010 that will store configuration/data inside the SP Hierarchical Store at the SPWeb level, using automatic serialization of an object, I got into the following error: System.Runtime.Serialization.SerializationException was unhandled Message=Unable to find assembly ‘MFD.SandBoxWebPart, Version=188.8.131.52, Culture=neutral ….’
Now to explain in more details the problem and how I choose to resolve it.
The configuration class is nothing else than a DTO class containing the configuration items as public properties and the [Serializable] attribute and be as simple as this example:
I got the previous error when adding an instance of this class into the SPWeb Properties as in the following example (the exception gets thrown at line 5):
Now there is nothing wrong with accessing the SPWeb properties inside the Sandbox solutions as the following code will work just fine:
The problem is that the serialization mechanism inside .NET requires to load the assembly for reflection. The SandBox assembly can’t be found because it is not saved in the GAC or any of the SharePoint folders as it only resides in memory and on the Content Database.
A work around for this to create your own serialization to xml/string using custom methods that will save/restore your data using one of the .NET classes (that can be serialized because they live in GAC).
An example of new MyConfig class will look like this:
Now all you have to do to store the config in SPWeb properties is to: