Pages

Follow me on Twitter

SPWeb.Properties serialization in the Sandbox

I was trying to store and retrieve some properties on an SPWeb object inside the sandbox. SPWeb has SetProperty()and GetProperty()methods, which accept and retrieve objects. I thought I’d use an enumeration to represent my value, and I’d cast my enumeration value when I retrieve it. However, when I tried this I got an exception of the form:

This worked fine, so it seemed to be something to do with the Sandbox. However, all the bits of the API I was using were allowed in the Sandbox. Eventually, I found the solution – and it turns out the problems is with Serialization inside Sandbox solutions. From Florin Muntean’s post:

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).

Actually, it’s pretty obvious when someone explains it to you!

Following that advice, instead of storing the enumeration I stored the the .ToString() of it’s value, and parsed it back to the enum when I retrieved it: