How to Attach an Event Receiver to the Web Added Event And For What Purpose

I struggled with the title of this post, because there are several different uses for the Event Receiver I’m going to talk about. In SharePoint 2007, it was common to use a Feature Receiver that was stapled to a Site/Site Definition for performing additional tasks after a Web was provisioned. We leveraged a Feature Receiver, because there didn’t exist an Event Receiver that handled the “Web Added” event. This is where the Web Provisioned event comes into play for SharePoint 2010 development. And a huge thanks to whoever was on the MS team that made that happen.

So let me setup a scenario I was working on recently and discuss the options for how that might be achieved.

Requirement: There exists a team site called Projects. Any sub sites created under Projects need to automatically inherit it’s parent site theme and navigation. We can get a little more complicated by doing things like adding web parts to the default.aspx page automatically or automatically adding an entry to the parent quick launch bar that includes a link to newly provisioned sites, but I’ll cover that in another post.

  1. Within Visual Studio, you want to create a new Project. On the left, expand the SharePoint heading and select Event Receiver on the right. Click OK to create the new project.
  2. The next screen will ask for the debugging url and whether or not you want this to be a sandboxed solution. Fill those in as required.
  3. The next screen is where we get to define what type of receiver we’re looking for. In this case, we’re going to use one of the NEW SharePoint 2010 receivers. In the drop down asking What type of event receiver we want, select Web Events. Now check the box next to A site was provisioned. Click Finish.
  4. Visual Studio will take care of all the setup for the Event Receiver, and once loaded, it should default you to the EventReceiver1.cs file.
  5. public class EventReceiver1 : SPWebEventReceiver
    {
           ///
           /// A site was provisioned.
           ///
           public override void WebProvisioned(SPWebEventProperties properties)
           {
               base.WebProvisioned(properties);
           }
    }
  6. Now let’s add the code that will be responsible for changing the navigation of the new site to inherit from it’s parent. And let’s also make the change so the sub site is themed like the parent.
  7. public override void WebProvisioned(SPWebEventProperties properties)
    {
            base.WebProvisioned(properties);
     
            SPWeb web = properties.Web;
     
            // set navigation to parent nav
            web.Navigation.UseShared = true;
     
            // set theme to parent theme
            ThmxTheme.SetThemeUrlForWeb(web, ThmxTheme.GetThemeUrlForWeb(web.ParentWeb));
     
            web.Update();
    }
  8. Go ahead and build the solution. Right click on the project in the Solution Explorer and click Deploy.
  9. Once the solution is deployed, open up your browser and navigate to your site url. Notice from the screenshot below, I have a Projects site with the Azure theme applied.
  10. An important piece to understand is that the Web Provisioned event needs to be activated at the Projects level, because we want the code we wrote to run on any sub sites created under Projects. So go ahead and navigate to Site Actions, Site Settings, Manage site features and activate our new feature.
  11. Go ahead and create a new sub site. You might notice that it appears as though nothing happened. For example, why does it appear as though the theme was not set? Well, if you hit refresh, you’ll see that the theme was in fact set. There is a property in the Event Receiver’s Elements.xml file that will fix this, so it doesn’t require a refresh. Take a look at the before and after for the xml listed below. I’ve added a line that sets the Synchronization property. The default is asynchronous, however, we want it set to synchronous. Asynchronous means that events typically run at the same time, so the custom code is run, but instead of waiting for it to finish, the page loads and we might not have finished setting it’s properties yet. By specifying that we run it synchronously, it will wait for the code to complete before attempting to load the page.
  12. Before

    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
      <Receivers >
          <Receiver>
            <Name>EventReceiver1WebProvisioned</Name>
            <Type>WebProvisioned</Type>
            <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
            <Class>WebAddedEvent.EventReceiver1.EventReceiver1</Class>
            <SequenceNumber>10000</SequenceNumber>
          </Receiver>
      </Receivers>
    </Elements>

    After

    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
      <Receivers >
          <Receiver>
            <Name>EventReceiver1WebProvisioned</Name>
            <Type>WebProvisioned</Type>
            <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
            <Class>WebAddedEvent.EventReceiver1.EventReceiver1</Class>
            <SequenceNumber>10000</SequenceNumber>
            <Synchronization>Synchronous</Synchronization>
          </Receiver>
      </Receivers>
    </Elements>
  13. Re-Deploy the solution and create another sub site. Test that it properly sets the values when the page loads. If it doesn’t work immediately, deactivate and reactivate the feature. I find I often have to do that after deploying a new version of a solution.

That’s it folks, a really simple overview of the new Web Provisioned event receiver. Please post a comment if anything is unclear.

20 Responses to “How to Attach an Event Receiver to the Web Added Event And For What Purpose”

  1. webdesign August 2, 2011 at 12:05 am #

    Very helpful post man, thanks for the info.

  2. Ajithkumar August 9, 2011 at 7:21 am #

    Great Info. Thanks

  3. Mike November 9, 2011 at 4:17 pm #

    Great Post!

  4. Chris December 8, 2011 at 9:20 am #

    Thankyou!

  5. Kelly D. Jones April 4, 2012 at 7:12 pm #

    Very helpful — especially the Synchronization property. I was trying to accomplish something using feature stapling and I couldn’t get it to work (although I’m pretty sure I had it set up correctly), but this was much easier to implement.

  6. shereen April 4, 2012 at 8:29 pm #

    Glad it was helpful Kelly, I struggled with Feature stapling as well but found this to be easier. I think feature stapling was the was to go before we had web provisioning.

  7. Excellent post June 22, 2012 at 8:49 am #

    This helped a lot with writing a receiver that triggered on the sitedeleting. Unfortunately, for some reason my feature will not automatically active when I deploy it even though teh Active deployment configuration is set to default. Any idea what could be done?

    Thanks,
    Godfrey

  8. shereen June 26, 2012 at 12:32 pm #

    hmmm…that’s a bit odd. hard to help out without being able to see the feature and how it’s configured. is it packaged in a WSP? is it posted somewhere we can view it?

  9. Godfrey July 5, 2012 at 2:31 pm #

    Thank you for your response.

    I shall be glad to send the code. I am deploying the feature directly through VS 2010. I am rather new to this so it could very well be something I am doing.

    Godfrey

  10. Godfrey July 6, 2012 at 3:53 am #

    A small addtion. I am sing the WebDeleting not adding Here is some of the code:

    EventReceiver XML:

    EventReceiverWebWebDeleting
    WebDeleting
    $SharePoint.Project.AssemblyFullName$
    WebDeletionEventReceiver.EventReceiverWeb.EventReceiverWeb
    10000

    EventReceiver:
    public class EventReceiverWeb : SPWebEventReceiver
    {
    ///
    /// A site is being deleted.
    ///
    public override void WebDeleting(SPWebEventProperties properties)
    {
    base.WebDeleting(properties);
    SPWeb curWeb = properties.Web;
    deleteProjectLinkFromClient(curWeb);
    }

    public void deleteProjectLinkFromClient(SPWeb childWeb)
    {
    string mainUrl = childWeb.Site.WebApplication.AlternateUrls[0].IncomingUrl;

    }

    ///
    /// A site was deleted.
    ///
    public override void WebDeleted(SPWebEventProperties properties)
    {
    base.WebDeleted(properties);
    }
    }
    Feature XML :

    I added the publishing prerequisites, Pubishn resources, SharePoint Server Publishing Infratructure, and SharePoint Server Publishing in a staple in case I needed them.

    Please let me know if I can provide anything else.

    Thanks,
    Godfrey

  11. Webdesigner August 28, 2012 at 9:50 pm #

    Sometimes I have to activate the Feature “SharePoint Server Publishing Infrastructure” before I can deploy from Visual Studio.

    How can I automatically activate this feature using the event receiver?

  12. programmeur January 4, 2013 at 12:24 pm #

    This was exactly what I was looking for. Thanks!

  13. Stephan Onisick April 30, 2013 at 4:27 am #

    Thanks I’m studying for 70-576 and needed some background info. Great article!!

  14. Sri May 21, 2013 at 11:39 am #

    Hi Shereen,

    Is this solution works in MySite?

    How to check event receiver deployed and activated on MySite?

    Please let me know.

    Thank you

    Sri

  15. shereen June 27, 2013 at 4:42 pm #

    Hi Sri,

    I don’t think so, since a mysite is a top level site collection. You would have to use a feature stapler for this.

Trackbacks/Pingbacks

  1. Tweets that mention How to Attach an Event Receiver to the Web Added Event And For What Purpose | SharePoint Fun -- Topsy.com - October 8, 2010

    [...] This post was mentioned on Twitter by Hire SharePoint Dev, Oliver Wolf. Oliver Wolf said: reading -> How to Attach an Event Receiver to the Web Added Event And For What Purpose – http://bit.ly/a3MuKW [...]

  2. Links (10/25/2010) « Everything SharePoint/Silverlight - October 25, 2010

    [...] How to Attach an Event Receiver to the Web Added Event And For What Purpose [...]

  3. Links a lot, Sharepoint, Chartcontroll,xpath, SP Client Object Model « Just tinkering Blog - March 18, 2012

    [...] How to Attach an Event Receiver to the Web Added Event And For What Purpose [...]

  4. SharePoint Development – What to Learn? | SharePointDevWiki.com - September 25, 2013

    […] an Event/Web/Feature Receiver is (and how they’re […]

  5. Site Provisioning with an attached event receiver | SharePoint interests - November 27, 2013

    […] Article from:  http://blog.qumsieh.ca/2010/10/07/how-to-attach-an-event-receiver-to-the-web-added-event-and-for-wha&#8230; […]

Leave a Reply