Storing Configuration Settings For Timer Jobs
Posted
Friday, March 23, 2012 3:58 PM
by
Itay Shakury
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:
http://msdn.microsoft.com/en-us/library/cc406686(office.12).aspx
http://msdn.microsoft.com/en-us/library/hh528519.aspx
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");
3:
4: //Store the settings
5: MyJobSettings settings = new MyJobSettings("settings", job); //here we set job as the parent
6: settings.settings1 = "Sample Data";
7: settings.Update();
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 --