Monday 5 October 2009

Reading Settings from the Web.Config file from an Event Handler

The SharePoint web.config is in my opinion the best place to put in any configuration settings. To read the config settings from an Event Handler isn't so straight forward but the following code does it nicely:

The SPItemEventProperties comes from the EventHandler.

You need to put in an appSettings tag in your web.config file, and then as many key value pairs as you need:

<add key="Username" value="svc-sharepoint"/>


public static string ReadKeyValueSetting(SPItemEventProperties properties, string keyName)
{
EventLog evita = new EventLog();
evita.Source = ("ReadFromConfig");
string webApplicationName = "";
using (SPSite siteCollection = new SPSite(properties.SiteId))
{
if (string.IsNullOrEmpty(siteCollection.WebApplication.Name))
throw new ApplicationException("Web application name is empty!");
else webApplicationName = siteCollection.WebApplication.Name;
}
System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("/", webApplicationName);
if (config == null)
throw new ApplicationException("Web Configuration is null");
AppSettingsSection appSettings = config.AppSettings;
if (appSettings == null)
throw new ApplicationException("Web.config appSettings section cannot be found!");
if (appSettings.Settings[keyName] == null string.IsNullOrEmpty(appSettings.Settings[keyName].Value))
{
evita.WriteEntry("KeyName doesn't exist!", EventLogEntryType.Warning);
throw new ApplicationException("Key value cannot be read from appSettings. Make sure this key and its value exist!");
}
return appSettings.Settings[keyName].Value;
}