Using Features and Solutions to Deploy your SharePoint Customizations

citied: http://www.simple-talk.com/dotnet/.net-tools/using-features-and-solutions-to-deploy-your-sharepoint-customizations/

What are Features?

So what are these features I’ve mentioned?

Well, features are packages of functionality that you can activate or deactivate in a SharePoint farm. They have four possible scopes:

  • Farm
  • Web application
  • Site
  • Web

A farm level feature, as the name suggests, is something that affects the whole farm, for example provisioning a custom timer job or deploying a Business Connectivity Services model.

A web application feature can be activated so that it only affects a single web application, and a typical example is a feature that modifies the web.config file.

A site scoped feature can be activated so that it only affects a site collection, an example being the deployment of a master page to the master pages catalogue.

Finally, a web scoped feature can be activated for a single site, for instance setting the default master page for that site.

What are Solutions?

They are the files you use to deploy your changes to SharePoint. They have the WSP file extension, and are often referred to as just WSP files. In reality, they are cabinet files that contain your customizations, plus a manifest XML file that tells SharePoint how to deploy your changes.

In SharePoint 2010 there are two types of solutions: farm solutions and sandboxed solutions.

Farm solutions are the same as the solutions we had in SharePoint 2007 and are deployed to the farm. In layman’s terms, your application or update is deployed as is; files on the file system are deployed exactly as that, files on the file system.

Sandboxed solutions are new to SharePoint 2010 and deploy your files to the SharePoint Content Database.

If your solution contains either a farm or a web application scoped feature, it can only be deployed as a farm solution.

Solutions that only contain site and web scoped features can usually be deployed using either a sandbox or farm solution. However, be aware that unless you take care, you could successfully deploy code using a sandboxed solution that is not permitted to run. The Community SharePoint Kit for Developers contains a great tool which limits Intellisense Visual Studio 2010 to show only supported methods and properties when building for sandbox solutions.

Sandboxed or Farm Solutions?

As I previously mentioned, whether you design for sandboxed or farm solutions is often driven by project requirements. Let’s say I want to deploy a new master page for a site; this is perfectly achievable through a sandboxed solution. But then let’s also say I need to deploy a new custom control that I’ve included in the master page, and that control needs to be deployed to the %SharePoint Root%\Template\CONTROLTEMPLATES folder as an ASCX file and its associated DLL needs to be placed into the GAC; now the story is different and I have to deploy using a farm solution.

As a guideline, the accepted best practice is to aim for a sandboxed solution initially, but move to a farm solution if your project functionality dictates this. However, it is important to remember that hosted SharePoint environments will often only permit sandboxed solutions, so in this case the platform is a major influencer in your decision.

Creating the feature

Open up Visual Studio 2010 and select File -> New -> Project. In the Add New Project dialog box (shown in Figure 2), under Installed Templates, select SharePoint -> 2010, highlight Empty SharePoint Project, and then name your project accordingly.

Figure 2: Add New Project dialog box

Next, on the SharePoint Customization Wizard dialog box, we want to select Deploy as a sandbox solution. Add in the URL to your site collection, which should be different from the one you edited your master page in, and click Finish. This will create a project called SimpleTalk.

Now select the SimpleTalk project node in the Solution Explorer, right-click and select Add -> New Item, then select Start Master Page (CKSDev), give it a name of simpletalk and click Add.

At this point we have all the files we need to deploy our master page and we just need to do a little cut-and-paste. But let’s examine in a little more detail what we actually have in the solution, which should now look as in Figure 3.

Figure 3: SimpleTalk Solution Explorer

The feature folder contains two files used by Visual Studio 2010 (VS2010) for constructing the final feature that SharePoint will need in order to deploy your master page. These files are:

  • The feature control file with the extension .feature; this is used by VS2010 only and is never deployed.
  • The feature template XML file. This contains the outline XML that VS2010 will use to construct the final feature.xml file, which must be present in a SharePoint feature. This too is used only by VS2010 and is never itself deployed. 

It is the feature.xml file which actually gets deployed and which tells SharePoint 2010 what is in the feature, and thereby what SharePoint needs to do with the files associated with the feature. The feature.xml file will only be created when you instruct VS2010 to package your solution.

Next, we see the package control file and the package template. This works in a similar manner to the feature. Neither of these two files ever gets deployed, but they are used by VS2010 to construct a file called manifest.xml, which exists in the WSP solution file.

Finally, the folder simpletalk has been added with two files: Elements.xml and simpletalk.master. The second is plainly an ASP.NET Master Page; the former is another SharePoint specific file, and whilst it does not strictly need to be called Elements.xml, by convention it nearly always is. The Elements.xml file in this case looks as shown in Figure 4:

Figure 4: Elements.xml file

All this mark-up has been added by the CKS Item and will tell SharePoint that a file called simpletalk.master should be made available at a relative URL _catalogs/masterpage. Most of the other properties are metadata and should be replaced with meaningful data, and one I will mention specifically is Type=’GhostableInLibrary’, for two reasons:

  • Reason one is that this is the attribute that tells SharePoint that this document should be made available and versioned through a document library, which means that any change to the document through SPD2010 will result in the file being uploaded into the SharePoint content database and thereafter that is where the source code for the file will be held.
  • Reason two is that without this attribute, you will not see the document in the library listing and for some inexplicable reason it is omitted from the standard SharePoint Module Template in VS2010, which is why I used the CKS Template.

I want the feature to be scoped at the SiteCollection level, which means that it is available to all sites within the SiteCollection. I can do this quite easily in the Feature Designer shown in Figure 5. So, double-click on the Feature1 folder and in the Scope drop-down list change the scope to Site. We can see the simpletalk item is included in the feature as it is shown on the right-hand side of the designer.

Figure 5: Feature Designer

All we need to do now is copy the mark-up from our master page in SPD2010 and paste it into the simpletalk.master file in our VS2010 project, then save the master page. Once that is done we’re good to go.

Deploying our feature

To deploy our feature, we need to do the following:

  1. Add it to a solution.
  2. Upload it to the Site Collection Solution Store.
  3. Activate the solution.
  4. Activate the feature.

Sounds a lot of work to you? It does to me too. And in Microsoft Office SharePoint Server (MOSS) 2007 it was, but now with VS2010, it’s a breeze. Just right-click the SimpleTalk project and click Deploy. Wait a few seconds, and then open your SharePoint site and select Site Actions -> Site Settings -> Galleries ->Solutions, and you will see your solution appearing in the solutions gallery as in Figure 6. Note that the status is Activated, so the relevant features have all been deployed.

Figure 6: Solution Gallery

Select Site Actions -> Site Settings ->Site Collection Administration -> Site Collection Features, scroll down, and you should see the feature has been activated as shown in Figure 7:

Figure 7: Site Collection Feature

Finally, select Site Actions -> Site Settings -> Galleries -> Master Pages and page layouts. You will then see your deployed master page in the master page gallery.

Figure 8: Master page gallery

Where is our brown bar? We haven’t set it as the default, so the master page is still the original v4.master. Let’s enhance our feature so that it sets our new master page as the default master page.

Enhancing the feature with code

In our Visual Studio project, select the Feature1 folder, then right-click and select Add Event Receiver, which will create a class called Feature1.EventReceiver.cs.

We will add code to two protected overridden methods. Insert the following code into the FeatureActivated and FeatureDeactivating methods:

    public class Feature1EventReceiver : SPFeatureReceiver
    {
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPSite site = properties.Feature.Parent as SPSite;
if (site != null)
{
SPWeb web = site.RootWeb;
web.AddProperty(“OldMasterUrl”, web.MasterUrl);
web.MasterUrl = String.Format(“{0}/{1}”
                  , (new Uri(web.Url)).AbsolutePath
, properties.Feature.Properties[“MasterUrl”].Value);
web.Update();
}
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
SPSite site = properties.Feature.Parent as SPSite;
if (site != null)
{
SPWeb web = site.RootWeb;
web.MasterUrl = web.AllProperties[“OldMasterUrl”].ToString();
web.DeleteProperty(“OldMasterUrl”);
web.Update();
}
}
}

Code sample 2: Feature code

In a production environment you will need code that is a bit more defensive than this, but it will suffice for our example. So what does this code do?

SPSite site = properties.Feature.Parent as SPSite;

This line retrieves a reference to the site collection in which we are deploying the master page.

SPWeb web = site.RootWeb;

This creates a reference to the root web site of the site collection.

web.AddProperty(‘OldMasterUrl’,web.masterUrl);

This stores the existing master page URL into the ‘bucket’ collection for the root web site.

The next line is the line that actually sets the new master page.

    web.MasterUrl = String.Format(“{0}/{1}”
,(new Uri(web.Url)).AbsolutePath
, properties.Feature.Properties[“MasterUrl”].Value);

Code sample 2: Feature code

In a production environment you will need code that is a bit more defensive than this, but it will suffice for our example. So what does this code do?

SPSite site = properties.Feature.Parent as SPSite;

This line retrieves a reference to the site collection in which we are deploying the master page.

SPWeb web = site.RootWeb;

This creates a reference to the root web site of the site collection.

web.AddProperty(‘OldMasterUrl’,web.masterUrl);

This stores the existing master page URL into the ‘bucket’ collection for the root web site.

The next line is the line that actually sets the new master page.

    web.MasterUrl = String.Format(“{0}/{1}”
,(new Uri(web.Url)).AbsolutePath
, properties.Feature.Properties[“MasterUrl”].Value);

The Uri object AbsolutePath property is used to ensure the correct path to the master page is used. The URL relative to the SiteCollection is read from the Feature Properties, a collection of user properties that you can add into the Feature.Template.xml shown in Figure 9:

Figure 9: Feature Properties

This configuration property is then available at runtime and makes your code more generic.  To ensure your changes are saved we must include the following line:

web.update();

In the FeatureDeactivating code, we simply restore the original master page. The ability to rollback is one of the key benefits of using features and solutions, and I recommend that you always properly test rollback code in the FeatureDeactivating method.

With this code in place, just hit Deploy again. This will build and package your solution, deactivate the existing feature, retract the existing solution, deploy your revised solution, activate the solution, and activate your feature. So wait a few seconds and you will see your site with the SimpleTalk brown band across the page beneath the top navigation menu, as shown in Figure 1 above.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s