Friday, April 24, 2009

Feature Stapling or Feature/Site Template Associations

Preface:
As the title imposes the meaning, Feature Stapling is a mechanism to attach (activate) a Feature automatically when a new site is provisioned.

History:
Lets dive back to the past a little to Site Definitions. You generally create a site definition and include a feature in the definition file (onet.xml). Once you are happy with your definition, you would start creating new sites with this definition. Once any one site is created, you dont have liberty to change the definition due to other risk factors etc. So far So Good.

Now, think about a scenario where you really want to add an additional feature for subsequent newly created sites that will be associated with your existing site definition. One of the cool mechanism's is Stapling.

Stapling (Feature Stapling in this case) is the method by which you staple a feature (required) with another feature (like a catalyst/driver/secondary) to drive the required feature. However the catalyst must implement FeatureSiteTemplateAssociation to achieve this.

Implementation:
Step 1: Creating the Primary Requirement Feature - is as simple as creating any other normal feature (say with GUID#1). Nothing new. You can see my previous blog for that.

Step 2: Create the catalyst Feature - Create a new Feature which will have its own Feature.xml with its own GUID (say GUID#2). However the elements file will have the following code instead.

<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
 <FeatureSiteTemplateAssociation Id="GUID#1" TemplateName="GLOBAL#0" />
</Elements>

The FeatureSiteTemplateAssociation element maps the associations of the GUID#1 to the site definition. Intresting attribute is TemplateName that is meant to specify if you want to staple Globally or at Team Site level. You can achieve it by declaring as shown below.

<FeatureSiteTemplateAssociation Id="GUID#1" TemplateName="STS#1" />

or you can do it together as below.

<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
 <FeatureSiteTemplateAssociation Id="GUID#1" TemplateName="GLOBAL#0" />
 <FeatureSiteTemplateAssociation Id="GUID#1" TemplateName="STS#1" />
</Elements>

* "GLOBAL" would staple it at the Farm Level and "STS" would staple it to the Team Site Level. Hence, if you want to deploy at both levels, you want to use both together.

Limitations:
1. You cannot apply Feature Stapling to already existing sites. You either have to manually activate it or write a small functionality that would deactivate features on all the site and reactivate.
2. Feature Stapling cannot be applied for 'Blank Sites'.

No comments: