Continuing in my series of articles showing the many ways in which we can store configuration data for your SharePoint applications, this time we look at how to use SPPersistedObject to achieve this.
Don’t forget to check out part 1 of the series in which we find out how SPWebConfigModification can be used for persisting application configuration in SharePoint 2010.
Persistence Using SPPersistedObject
SPPersistedObjects let you store hierarchical configuration data for your application in SharePoint. An SPPersistedObject is a class you subclass. You can then add fields (not properties) to your class, attribute them with [Persisted], and SharePoint will serialise the object to Xml in the SharePoint Configuration database.
The above code creates a class with two fields (string Value1 and int Value2) which can be persisted for the current Web Application with the following code:
We can later retrieve – and optionally delete – the settings by calling GetChild<> on the WebApplication object.
As an alternative to storing at the Web Application level, you can use a Farm object instead.
You configuration data is stored in the SharePoint Configuration database. This means it will be backed up along with the rest of your SharePoint data – assuming you perform SharePoint backups, of course.
Your data is also safe from prying eyes as there is no UI to edit these settings.
There is no built in user interface to manage SPPersistedObjects. This is both a good and a bad thing: you have to provide your own way of editing the values you wish to store. To read and write these values you also need to impersonate a user, such as a Farm Administrator, with read and write privileges on the Config database (SPSecurity.RunWithElevatedPriviliges() won’t help here!). There are some reports of SPPersistedObject use corrupting the Hierarchical Object Store; it’s unclear whether this is due to incorrect usage or something more flaky. Reading the comments, one of our readers has suggested this corruption happens for them if they use obfuscated assemblies. (Many thanks, Joe!)
Proceed with caution, and thoroughly test your code first on a virtual, scratch, SharePoint farm.