Storing configuration in SharePoint

I often have to store some configuration data in SharePoint. Typically I have a custom application page on the Central Administration site to configure a feature or an application. Typically this is a connection string and some other data.

To store the configuration I do not like to use the Farm or WebApplication property bag. SharePoint 2007 can under certain circumstances wipe the property bag when a WFE runs out of memory.

I am not sure if the following methods avoids this issue. But so far I have not seen any problems with that. An other advantage is that using this metods you work type safe.

Using a SPPersitedObject to store data in context of a SPFarm object requires the following steps:

  1. Define a class for you configuration data. Inherit from SPPersistedObject. Public fields for the data decorated with the Persisted attribute.
  2. Attach you data object to an SPxxxx instance using the SPPersistedObject constructor. Fill the data object and call the Update method.
  3. Retrieve the data object the GetObject method of SPxxxx objects.

Data object

public class SomeSettings : SPPersistedObject
{
     [Persisted]
     public string ConnectionString;

     [Persisted]
     public bool IsActivated;

     public SomeSettings()
     {
     }

     public SomeSettings(string name, SPPersistedObject parent, Guid id)

            : base(name, parent, id)
     {
     }
}

 

Usage

// Try to get the the config from farm.
SPFarm parent = SPContext.Current.Site.WebApplication.Farm;
SomeSettings settings = parent.GetChild<Some>("SomeSettings");
if (settings == null)
{
   settings = new SomeSettings("SomeSettings", parent,  Guid.NewGuid());
}
settings.ConnectionString = tbConnectionString.Text;
settings.IsActivated = true;
settings.Update();

Leave a Reply

Your email address will not be published. Required fields are marked *