Sharepoint 2010 Event receiver not firing for subsite

Matt Moriarty picture Matt Moriarty · Apr 6, 2011 · Viewed 7.7k times · Source

I have an event receiver (WebAdding and WebProvisioned) which works just fine for sites created off the root of the site collection. However, subsites (for example, teamsites created within other areas) do not trigger the code at all.

Does anyone have any idea as to why?

using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using System.Text;

namespace TestEventReceiver.EventReceiver1
{
  /// <summary>
  /// Web Events
  /// </summary>
  public class EventReceiver1 : SPWebEventReceiver
  {
    /// <summary>
    /// A site is being provisioned.
    /// </summary>
    public override void WebAdding(SPWebEventProperties properties)
    {
      base.WebAdding(properties);

      using (SPWeb web = properties.Web)
      { 
        StringBuilder output = new StringBuilder();
        output.AppendFormat("Web Adding");
        output.AppendFormat("<br>Web title: {0}",web.Title);
        SendMyEmail(web, "[email protected]", "Web Adding", output.ToString());
      }
    }

    /// <summary>
    /// A site was provisioned.
    /// </summary>
    public override void WebProvisioned(SPWebEventProperties properties)
    {
      base.WebProvisioned(properties);
      using (SPWeb web = properties.Web)
      {
        StringBuilder output = new StringBuilder();
        output.AppendFormat("Web Provisioned");
        output.AppendFormat("<br>Web title: {0}", web.Title);
        SendMyEmail(web, "[email protected]", "Web Provisioned", output.ToString());
      }
    }

    private void SendMyEmail(SPWeb Web, String toAddress, String subject, String message)
    {
      bool appendHtmlTag = false;
      bool htmlEncode = true;
      SPSecurity.RunWithElevatedPrivileges(delegate()
      {
        SPUtility.SendEmail(Web, appendHtmlTag, htmlEncode, toAddress, subject, message);
      });

    }

  }
}

Thanks in advance, Matt

Answer

Sangeet picture Sangeet · Jul 12, 2011

I think you should not be using 'Using' . The SPWeb object reference you get is from properties.Web which is being passed to the WebAdding method. You will run into issues because of this.