How to: Add a Configuration Setting
The following procedure demonstrates how you can use the Application Setting Manager to store a configuration setting. In this example, the configuration setting is stored at the Web application level. However, you can use the same procedure to store data at the site level, the site collection level, or the farm level.
Note
To store settings at the farm level, your code must run in a context that has permissions to write to the farm—for example, in a console application, a feature receiver installed event, the Central Administration Web site, or a farm-scoped feature receiver class. You cannot write to farm-level configuration from standard SharePoint Web applications.
To add a configuration setting
Add a reference to the SharePoint Guidance Library assembly. In Visual Studio, right-click your project node in Solution Explorer, and then click Add References. Click the Browse tab, and then navigate to the location of the Microsoft.Practices.SharePoint.Common.dll assembly.
Using the same procedure, add a reference to the Microsoft.Practices.ServiceLocation.dll assembly.
Add the following using statements to the top of your source code file.
using Microsoft.Practices.ServiceLocation; using Microsoft.Practices.SharePoint.Common.Configuration; using Microsoft.Practices.SharePoint.Common.ServiceLocation;
Use the SharePointServiceLocator.GetCurrent method to get a reference to the current service locator instance.
IServiceLocator serviceLocator = SharePointServiceLocator.GetCurrent();
Use the service locator to request an implementation of the IConfigManager interface.
IConfigManager configManager = serviceLocator.GetInstance<IConfigManager>();
(Optional) If your code is running in an environment where the SPContext.Current property is not available, call the SetWeb method and pass in an SPWeb object from which to build the storage hierarchy. If a SharePoint context exists, you can skip this step.
configManager.SetWeb(web);
Retrieve the IPropertyBag instance in which you want to store your application setting.
IPropertyBag bag = configManager.GetPropertyBag(ConfigLevel.CurrentSPWebApplication);
Call the IConfigManager.SetInPropertyBag method. The first parameter is the key string with which you want to identify your configuration data. The second parameter is the object that you want to store as configuration data, which in this case is an object of type DateTime. The third parameter is the IPropertyBag in which you want to store your configuration setting.
configManager.SetInPropertyBag("MyApplication.LastUpdate", DateTime.Now, bag);