Storing Configuration Settings For Timer Jobs
Friday, March 23, 2012 3:58 PM
When you develop a custom timer job, there is often a need to store configuration settings.
The best way to do this is using the Hierarchical Object Store in SharePoint, by creating an SPPerststedObject. There are plenty of articles out there that tell you to how to do this.
For more info on this subject, see this:
So it’s called "hierarchical” object store, because you have to attach the settings to a certain object in the SharePoint object model, and that object must support this by inheriting from SPPersistedObject. Most of those articles shows you how to attach settings to SPFarm, SPWebApplication, or SPSiteCollection objects, but as a matter of fact, the SPJobDefinition class is also a SPPersistedObject!
This means that you can attach settings to the job object directly, and not leave them hanging at the farm or a higher level. This has two benefits:
- It’s more organized to keep timer job related settings at the timer job level (and not web application level for example)
- When you delete the timer job, the settings are deleted as well
Here’s a sample:
1: SPWebApplication wa = SPWebApplication.Lookup(new Uri("http://MySP"));
2: SPJobDefinition job = wa.JobDefinitions.First(j => j.Name == "MyTimerJob");
4: //Store the settings
5: MyJobSettings settings = new MyJobSettings("settings", job); //here we set job as the parent
6: settings.settings1 = "Sample Data";
And the reading:
1: //Read the settings
2: MyJobSettings res = job.GetChild<MyJobSettings>("settings");
3: string setting1 = res.setting1;
-- My name is Itay Shakury, and I’m a SharePoint consultant --