Accessing (the Right) web.config from a SiteDeleting Event Receiver

When code from a SiteDeleting event receiver accesses the web.config file it will get Central Administration’s. That’s because the Site Collection is being deleted using Central Administration’s UI and now your event receiver is running in Central Administration’s application pool.

Trying to access your application’s web.config you’ll then usually call ConfigurationManager.OpenExeConfiguration(). But this throws an exception “Failed to resolve the site ID” because the web.config’s site doesn’t use the same application pool as the event receiver. The reason for this is of course that you use application pools to isolate applications and explicitly want this behavior.

The solution is to open web.config as a normal file–the account your application pool uses should have sufficient permissions for this. Here’s a code example:

// ...

public override void SiteDeleting(SPWebEventProperties properties) {
   string webConfigPath 
      = properties.Web.Site.WebApplication.IisSettings[SPUrlZone.Default].Path.FullName;
   XmlDocument webConfig = new XmlDocument();
   webConfig.Load(webConfigPath + "\\web.config");
   string appSettingsXPath = "configuration/appSettings/add";
   //XmlNodeList appSettings = webConfig.SelectNodes(appSettingsXPath);
   XmlNode mySetting = webConfig.SelectSingleNode(appSettingsXPath + "[@key='MyKey']");
   if (mySetting != null) {
      string s = mySetting.Attributes["value"].Value;

Depending on your scenario it may be more appropriate to pass the value by using the feature’s properties. This is an often overlooked option.

Of course getting a wrong .config file is not limited to writing extensions for SharePoint’s Central Application but a more general problem. A Big Thank You to my colleague Matthias for the tip off!

Another oddity I found when creating a SiteDeleting event receiver was that using Debugger.Break() caused some really weird behavior. Attach to the respective w3wp process instead. At least Visual Studio 2010 doesn’t ask you anymore if you really want to attach.

This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

One Response to Accessing (the Right) web.config from a SiteDeleting Event Receiver

  1. Matthias says:

    Die Datei öffnen … ich geh kaputt. Warum nicht einfach den appSettings-Parameter in die andere web.config kopieren?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s