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.

SharePoint 2010 Schema.xml, Onet.xml and Toolbar Type

I’ve been working pretty heavily the last couple weeks with List Definitions, List Instances and Site Definitions in SharePoint 2010. I’m documenting my process because I was hard pressed to find a solid example of this on the web. I’m mostly concerned with documenting the areas that I found difficult, like the View definition in the Schema.xml and the changes to the Onet.xml Modules element in 2010. What I won’t cover is how to use Visual Studio 2010 to create a new Site Definition project, and add List Definitions to it. Perhaps in another post I’ll try to outline the whole process in more detail.

Let me setup the scenario:

1. I am using Visual Studio 2010 to build a Site Definition that will contain a List Definition and an instance of that List.
2. I want the instance of the List that I create to show up on the default.aspx page of my site automatically when I provision a site using this definition.
3. Finally, I want to display a full toolbar so users can add items directly from the default.aspx page.

Schema.xml

<View BaseViewID="50" Type="HTML" MobileView="TRUE" MobileDefaultView="TRUE" ImageUrl="/_layouts/images/generic.png" WebPartZoneID="Main" WebPartOrder="1" Url="Forms/Last Modified.aspx" SetupPath="pages\viewpage.aspx">
        <Toolbar Type="None" />
        <XslLink>main.xsl</XslLink>
        <Query>
          <OrderBy>
            <FieldRef Name="Modified" Ascending="False"/>
          </OrderBy>
        </Query>
        <ViewFields>
          <FieldRef Name="DocIcon"></FieldRef>
          <FieldRef Name="LinkFilename"></FieldRef>
          <FieldRef Name="_UIVersionString"></FieldRef>
          <FieldRef Name="Editor"></FieldRef>
          <FieldRef Name="Status"></FieldRef>
          <FieldRef Name="Category"></FieldRef>
        </ViewFields>
        <RowLimit Paged="FALSE">5</RowLimit>
        <Aggregations Value="Off" />
</View>

So some things to note in the above.

  1. The Toolbar Type attribute caused a bit of confusion for me because the schema complains that it’s invalid if I set it to a value of None. It works for me anyway. There is a ton of information on the web that describes what these values are allowed to be. I find the following article from MS documents the options well:
    • Standard —The most common type of toolbar, which is used, for example, in the All Items views for most lists, and which corresponds to Full Toolbar in the Web Part tool pane.
    • FreeForm —Used in Default.aspx and Web Part Pages and corresponds to Summary Toolbar in the Web Part tool pane.
    • None —No toolbar is used in the view, corresponding to No Toolbar in the Web Part tool pane.
  2. When adding elements to this xml file, ensure that the Name you specify is the Internal name of that field, not the display name. For things like Version, I was assuming the internal name was Version when it fact it was _UIVersionString or _UIVersion. I haven’t found a neat way to discover these internal names for system or hidden fields, but if I do, I’ll update this post.
  3. Make sure you add a SetupPath tag that points to “pages\viewpage.aspx” so it knows where to go to generate your view.
  4. Finally, be really careful not to set the DefaultView property on more than one View element. I find by doing that, it creates a completely separate list, instead of a view within the current list.

Onet.xml

Ok so when we’re ready to add our List Definition to the Onet.xml, a few things slowed me down that I want to point out here. I’m going to show two ways that you would add a list/view to the default.aspx page:

<View List="Project Documents" BaseViewID="1" WebPartZoneID="Right" WebPartOrder="1" />

The above code references a List Definition I have already created called Project Documents, I’m looking for the BaseViewID of 1 (this should be defined in the Schema.xml) and I’m specifying where to position my web part. This technique works really well for me, except, I am not able to set things like the Title of the web part or it’s Chrome.

So I could have done the following:

<View List="Project Documents" Name="Last Modified Project Documents" DisplayName="Last Modified Project Documents" BaseViewID="50" WebPartZoneID="Right" WebPartOrder="2">
          <![CDATA[
              <webParts>
                  <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
                      <metaData>
                          <type name="Microsoft.SharePoint.WebPartPages.XsltListViewWebPart,Microsoft.SharePoint,Version=14.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c" />
                          <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
                      </metaData>
                      <data>
                          <properties>
                              <property name="Title">Last Modified Project Documents</property>
                              <property name="AllowConnect" type="bool">True</property>
                              <property name="AllowClose" type="bool">False</property>
                          </properties>
                      </data>
                  </webPart>
              </webParts>
          ]]>
</View>

The above now let’s me set things like Title and Chrome.

Lastly, be sure NOT TO DO THIS in SharePoint 2010:

<View List="Project Documents" BaseViewID="50" DisplayName="Last Modified Project Documents" Name="Last Modified Project Documents" RecurrenceRowset="TRUE" WebPartZoneID="Right" WebPartOrder="2">
  <![CDATA[
             <WebPart xmlns="http://schemas.microsoft.com/WebPart/v2">
                  <Assembly>Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
                  <TypeName>Microsoft.SharePoint.WebPartPages.ListViewWebPart</TypeName>
                  <Title>Last Modified Project Documents</Title>
             </WebPart>
      ]]>
</View>

The above will work fine in SharePoint 2010, but there will be some inconsistency and it won’t behave quite right. If you edit the web part, you’ll notice it’s missing a few of the options that the 2010 ones do.

Content Deployment Errors in SharePoint 2010

I’ve been doing a lot of work recently with SharePoint 2010 and the Content Deployment/Content Scheduling features, and it seems to me that not a whole lot has changed. According to the official Microsoft 2010 “Content deployment overview“, we still have to watch out for the following:

1. Always deploy to an empty site collection for the initial content deployment job – It doesn’t appear to be sufficient anymore to use the blank site template. The recommendation now is to use the <Select template later> option we now see under the Custom tab. I prefer to use the following powershell command:

New-SPSite -Url "http://silvermoon" -OwnerAlias "silvermoon\joeuser" -OwnerEmail ""

That will create a new site collection without applying a template.

I also wanted to note that I ran into some errors similar to what I had blogged about previously in 2007 (I’m surprised these still continue to be a problem). You can read more about that here. In particular, I was running into one error consistently:

Unable to import folder _catalogs/masterpage/Forms/Page Layout. There is already an object with the Id 62b662s-3344b-332bbs33-a334d-233k in the database from another site collection

I really couldn’t figure out what was causing this error. I had two web applications, with a single site collection in each, and I was creating the destination site collection without a template as prescribed by MS. Turns out, the very first time I created a site collection in my new web application, I had specified a template instead of selecting none. Even though I had deleted and recreated brand new ones several times since then, there were still residual traces of something, hence the error above.

The resolution for me was to detach the content db, and then reattach it. OR, delete my destination web application and start again.

Just wanted to note this for anyone else out there having a similar issue.