0% found this document useful (0 votes)
55 views9 pages

Introduction To Features

This document provides an overview of how to create and deploy custom features in SharePoint. Key points include: 1. Features allow defining site elements that can be activated on a site or site collection. They consist of XML files defining the elements and event handlers. 2. Features are deployed as directories within the SharePoint FEATURES system directory. The feature.xml file defines the feature and references other XML files. 3. Event handlers allow code to run when a feature is activated or deactivated. The code is deployed to the GAC and referenced from the feature.xml file.

Uploaded by

amsin9688
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views9 pages

Introduction To Features

This document provides an overview of how to create and deploy custom features in SharePoint. Key points include: 1. Features allow defining site elements that can be activated on a site or site collection. They consist of XML files defining the elements and event handlers. 2. Features are deployed as directories within the SharePoint FEATURES system directory. The feature.xml file defines the feature and references other XML files. 3. Event handlers allow code to run when a feature is activated or deactivated. The code is deployed to the GAC and referenced from the feature.xml file.

Uploaded by

amsin9688
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 9

Introduction to Features

Features provide a mechanism for defining site elements and adding them to a target site or site collection
through a process known as feature activation. The element types that can be defined by a feature include
menu commands, link commands, page templates, page instances, list definitions, list instances, event
handlers, and workflows.

At a physical level, a feature consists of a directory created within a special WSS system directory
located within the file system of each front-end Web server. The directory for a feature contains one or
more XML-based files that contain Collaborative Application Markup Language (CAML).

Besides the feature.xml file, a feature usually contains one or more additional XML files (for example,
elements.xml) that define the actual elements that make up the feature.

Also note that the Site Features page will look very different if you have installed MOSS because there
will be more than 100 features

Once you have created a feature, you then must install it with WSS at a farm-level scope. Once a feature
has been installed with WSS, it can then be activated within the context of a site or a site collection using
an administrative page accessible through the Site Settings page.

Before creating the feature.xml file, consider that the files for this feature must be deployed in their own
special directory inside the WSS system directory named FEATURES. The FEATURES directory is
located inside another WSS system directory named TEMPLATE.
c:\Program Files\Common Files\Microsoft Shared\web server
extensions\12\TEMPLATE\FEATURES

The Scope defines the context in which the feature can be activated and deactivated. The feature we are
creating has a scope equal to Web, which means it can be activated and deactivated within the context of
the site. If you assign a Scope value of Site, your feature will then be activated and deactivated within the
scope of a site collection. The two other possible scopes for defining a feature are WebApplication scope
and Farm scope

<Feature
Id=""
Title="Hello World Feature"
Description="This is my very first custom feature"
Scope="Web"
Hidden="FALSE"
ImageUrl="menuprofile.gif"
xmlns="http://schemas.microsoft.com/sharepoint/">

<ElementManifests>
<ElementManifest Location="elements.xml" />
</ElementManifests>

</Feature>
The last part of the feature.xml file shown previously is the ElementManifests element. This element
contains inner ElementManifest elements that reference other XML files where you will define the
elements that make up the feature. In our case, there is a single ElementManifest element that uses the
location attribute to point to a file named element.xml

Inside the TEMPLATE directory there is a directory named XML that contains several XML schemas,
including one named wss.xsd. If you associate this schema file with feature files such as feature.xml and
elements.xml, Visual Studio will provide IntelliSense, which makes it much easier to author a custom
feature. You may also copy these XSD files into C:\Program Files\Microsoft Visual Studio
8\Xml\Schemas\.

Now it’s time to create the element.xml file and define a single CustomAction element that will be used
to add a simple menu command to the Site Actions menu. Add the following XML, which defines a
CustomAction element to elements.xml.

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<CustomAction
Id="SiteActionsToolbar"
GroupId="SiteActions"
Location="Microsoft.SharePoint.StandardMenu"
Sequence="100"
Title="Hello World"
Description="A custom menu item added using a feature"
ImageUrl="_layouts/images/menuprofile.gif" >
<UrlAction Url="http://msdn.microsoft.com"/>
</CustomAction>
</Elements>

Now that we have created the feature.xml file and the elements.xml file to define the HelloWorld feature,
there are three steps involved in installing it for testing purposes. First, you must copy the HelloWorld
feature directory to the WSS system FEATURES directory. Second, you must run a STSADM.EXE
operation to install the feature with WSS. Finally, you must activate the feature inside the context of a
WSS site. You can automate the first two steps by creating a batch file named install.bat at the root
directory of the HelloWorld project and adding the following command line instructions.

REM – Remember to remove line breaks from first two lines


@SET TEMPLATEDIR="c:\program files\common files\microsoft shared\
web server extensions\12\Template"
@SET STSADM="c:\program files\common files\microsoft shared\
web server extensions\12\bin\stsadm"

Echo Copying files


xcopy /e /y TEMPLATE\* %TEMPLATEDIR%

Echo Installing feature


%STSADM% -o InstallFeature -filename HelloWorld\feature.xml -force

Echo Restart IIS Worker Process


IISRESET
Adding an Event Handler to a Feature

Now it’s time to take the example of the HelloWorld feature a little further by adding event handlers and
programming against the WSS object model. First, start by adding a project reference to
Microsoft.SharePoint.dll. Next, locate the source file named Class1.cs and rename it to
FeatureReceiver.cs. Next, add the following code.

using System;
using Microsoft.SharePoint;

namespace HelloWorld{
public class FeatureReceiver : SPFeatureReceiver {
public override void FeatureInstalled(
SPFeatureReceiverProperties properties){}
public override void FeatureUninstalling(
SPFeatureReceiverProperties properties) { }

public override void FeatureActivated(


SPFeatureReceiverProperties properties){
SPWeb site = (SPWeb)properties.Feature.Parent;
// track original site Title using SPWeb property bag
site.Properties["OriginalTitle"] = site.Title;
site.Properties.Update();
// update site title
site.Title = "Hello World";
site.Update();
}

public override void FeatureDeactivating(


SPFeatureReceiverProperties properties) {
// reset site Title back to its original value
SPWeb site = (SPWeb)properties.Feature.Parent;
site.Title = site.Properties["OriginalTitle"];
site.Update();
}
}
}

The first thing you should notice is how you create an event handler that fires when a feature is activated
or deactivated. You do this by creating a class that inherits from the SPFeatureReceiver class. As you can
see, you handle events by overriding virtual methods in the base class such as FeatureActivated and
FeatureDeactivating. There are also two other event handlers that fire when a feature is installed or
uninstalled, but we are not going to use them in this introductory example.

The FeatureActivated method has been written to update the title of the current site using the WSS object
model. Note the technique used to obtain a reference to the current site–the properties parameter is used
to acquire a reference to an SPWeb object. The properties parameter is based on the
SPFeatureReceiverProperties class that exposes a Feature property that, in turn, exposes a Parent property
that holds a reference to the current site. The site title is changed by assigning a new value to the Title
property of the SPWeb object and then calling the Update method.

Also note that this feature has been designed to store the original value of the site Title so that it can be
restored whenever the feature is deactivated. This is accomplished by using a persistent property bag
scoped to the site that is accessible through an SPWeb object’s Properties collection. Note that many of
the objects in the WSS object model have a similar Properties property, which can be used to track name-
value pairs using a persistent property bag. WSS handles persisting these named value pairs to the content
database and retrieving them on demand.
Now that we have written the code for the feature’s two event handlers, it’s time to think about what’s
required to deploy the HelloWorld.dll assembly. The first thing to consider is that this assembly DLL
must be deployed in the Global Assembly Cache (GAC), which means you must add a key file to the
project in order to sign the resulting output DLL during compilation with a strong name.

Once you have added the key file and configured the HelloWorld project to build HelloWorld.dll with a
strong name, you can also add another instruction line to the post-event build command line to install (or
overwrite) the assembly in the GAC each time you build the current project. The command line
instructions for the post-event build should now look like this:

"%programfiles%\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe" -if $


(TargetPath)
cd $(ProjectDir)
Install.bat

The next step is to update the feature.xml file with two new attributes so that WSS knows that there are
event handlers that should be fired whenever the feature is activated or deactivated. This can be
accomplished by adding the ReceiverAssembly attribute and the ReceiverClass attribute, as shown here.

<Feature
Id=""
Title="Hello World Feature"
Description="This is my very first custom feature"
Version="1.0.0.0"
Scope="Web"
Hidden="FALSE"
ImageUrl="menuprofile.gif"
ReceiverAssembly="HelloWorld, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=b59ad8f489c4a334"
ReceiverClass="HelloWorld.FeatureReciever"
xmlns="http://schemas.microsoft.com/sharepoint/">

<ElementManifests>
<ElementManifest Location="elements.xml" />
</ElementManifests>

</Feature>

The ReceiverAssembly attribute should contain the four-part name of an assembly that has already been
installed in the GAC. The ReceiverClass attribute should contain the namespace-qualified name of a
public class within the receiver assembly that inherits SPFeatureReceiver.

Once you have made these changes to the feature.xml file, you should be able to test your work. When
you rebuild the HelloWorld project, Visual Studio should run the install.bat file to copy the updated
version of the feature.xml file to the WSS FEATURES directory and to install the updated version of
feature.xml with WSS. The build process should also compile HelloWorld.dll with a strong name and
install it in the GAC. Note that you will likely be required to run an IISRESET command to restart the IIS
worker process. This is due to the fact that features and assemblies loaded from the GAC are cached by
WSS within the IIS worker process.

At this point, you should be able to test your work by activating and deactivating the feature within the
context of a WSS site. When you activate the site, it should change the Title of the site to “Hello World.”
When you deactivate the feature, it should restore the Title of the site to the original value.

If you have successfully completed these steps, you are well on your way to becoming an accomplished
WSS developer. That’s because creating features and programming against the WSS object model are the
two most basic skills you need to acquire.
Features and Solutions
As I’ve mentioned throughout, a major purpose for developing Windows SharePoint
Services as a platform is to make it extensible; that is, to make WSS and MOSS functionality
extendable and customizable, but also to provide this same platform to anyone who wants
to create custom applications on top of it.
In the past, adding anything to SharePoint took some effort and even creating web parts
could be a very long and painful process. Fortunately, Microsoft had this same problem and
decided that with WSS and MOSS it would be a great idea to develop some sort of a framework
that designers and developers could use to add features to SharePoint. So maybe they did it
for themselves or for us, but either way, the Feature and Solution Framework is built into
WSS to directly support deploying functionality in SharePoint.
Features are either services or applications, made up of components and/or pages that
can be deployed to a SharePoint instance. Using a few XML definition files, Features are
installed in SharePoint and can then be activated on a Shared Service Provider, Site Collection,
or even Site level. Examples include user-defined (from Designer) or custom workflows,
custom site definitions, master pages and styles, and so on. Once installed, site administrators
can enable or disable Features at any time, putting control in the hands of the user instead
of the developer.

Solutions are just like features, with the exception that they are intended to provide
solutions other than add-on functionality. While this might seem like splitting hairs,
there is a difference: the intention is that Solutions provide a specific use and are not
necessarily SSP or site wide. For example, all web parts are installed as Solutions—it
would be common to install a web part on a specific site and but not as a Shared Service.
And installation is a snap—Visual Studio 2005 now provides automatic installation of
Solutions and debugging!
As I mentioned, Features and Solutions can include a lot of things, from DLLs to pages;
the framework is intended to accomplish the following:
• Copy the Feature or Solution definition files into the SharePoint Features folder
• Copy the support files from a folder (aka package) and place them in the correct
locations in the SharePoint Hive (folder structure)
• Install the Feature which loads the name and description as well as the definition
into SharePoint (pointing it to the right assets defined in Elements Manifest File)
• Activate the feature which makes it available in SharePoint sites

Anatomy of a Feature
Features and Solutions are based on two primary XML files: a Feature Manifest file and
an Elements Manifest file. The Feature Manifest file is used to identify a particular Feature
in SharePoint, including giving it a name and a global unique identifier (or GUID) that
becomes the Features ID in SharePoint. This also contains an element that specifies the
actual file location of the Elements Manifest File(s) (technically there can be more than one
Element Manifest for a single Feature). The Element Manifest file is used to identify the
components (pages, script, images, and so on) that make up the Feature. You’ll see this in
the example that follows.

When they are ready to be installed, all of the files required to install the Feature are
physically copied to the SharePoint Hive (the primary Feature files go into <drive>:\
Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\
Features in a folder named after the Feature). Once there, the Feature itself is first installed
into SharePoint, and then activated. Finally, it’s enabled from either the command line or
from the User Interface. Removing a Feature is done in reverse; it is first disabled, and then
deactivated by retracting it. Then, it can be uninstalled.
Features that are installed in a SharePoint site are always accessible from the Site Settings
page, under either Site Features or Site Collection Features. Site Features are those that are
available (installed) only on the current site, and Site Collection Features are those that
are available within any site in the collection.

Feature Manifest File


The Manifest file defines the Feature or Solution for SharePoint, including the name,
description, and ID. It also identifies the components (specifically to the Elements Manifest
files, web parts, and so on). The Feature file includes the following elements:
• Feature This element is the outer wrapper of the XML that defines the Feature and
specifies the XML Namespace (http://www.schemas.microsoft.com/sharepoint/).
It includes the Feature Title, the GUID ID, a Description, the Version, the Scope (this
sets the scope for the Feature, Web, Site, Web Application, or Farm), a flag to indicate
whether it’s hidden or not, and a pointer to a default resource file (if any).
• ActivationDependencies This element is used to identify the IDs of any Features
that it’s dependent upon, which prevents users from enabling Features in the wrong
order. This is only used if the Feature or Solution is dependent on one or more being
installed.
• Elements Manifests This lists any Elements Manifest files included in the Feature.
• Properties This defines Key-Value pairs as properties, which can be used as
presettings for a Feature.

Elements Manifest File


The Elements Manifest file is used to identify the elements of the Feature. This includes
modules (DLLs), receivers, and others that determine where elements of the Feature are to
be placed or loaded. The entries in this file depend on what is being installed. For example,
Receivers have a Receivers element. If deploying a web part, however, DLLs are referenced
as Modules. The primary elements are somewhat self-describing. These include:

• ContentType This Feature defines a content type.


• ContentTypeBinding This Feature binds a list to an existing content type.
• Control This Feature is a web control.
• CustomAction This Feature is a custom action.
• CustomActionGroup This Feature is a custom action group.
• DocumentConverter This Solution is a document converter.
• FeatureSiteTemplateAssociation This Feature is associated to a specific Site
Template.
• Field This Feature defines a field in a List Feature.
• HideCustomAction This Feature hides a custom action (for example, removing
Delete Web).
• ListInstance This Feature creates a specific list instance.
• ListTemplate This Feature is a List Template.
• Module This Feature defines a single module included in the Feature.
• Receivers This Feature defines one or more receivers included in the Feature.
• UserMigrator This Feature is undocumented (usage unknown).
• Workflow This Feature is a workflow.

Overview of Features and


Solutions
Features provide the ability for sites to reuse functionality
that exists in other sites without requiring the tedious task
of copying and pasting complex Extensible Markup
Language (XML) code from one template to another.
By installing Feature definitions at the farm level, Features
can then be activated at any site within the farm. This
allows reusable pieces of functionality to be created and
deployed without modifying site templates, and it allows
site templates to be far less complex than they used to be
by referring to Features instead of directly embedding
mountains of complex XML.
Using Features, you can do everything from adding a link
to the Site Settings page to creating a complete, fully functioning
Project Management suite that can be added to any
SharePoint site.

Programming with Features


SharePoint includes a robust object model for working with Features that allows developers
to enumerate installed and activated Features, to turn Features on and off, and to
control the installation or removal of Features.
The object model for Features includes the following key classes:
. SPFeatureCollection/SPFeature—Refers to a Feature state at a given site hierarchy
level. The presence of an SPFeature instance within a property of type
SPFeatureCollection indicates that the Feature is active at that level.
. SPFeaturePropertyCollection /SPFeatureProperty—Represents a single property on
a Feature or a collection of those properties.
. SPFeatureScope—Represents an enumeration of the possible scopes in which
Features can be activated. Possible values are: Farm, WebApplication, Site, and Web.
. SPFeatureDefinition—Represents the basic definition of a Feature, including its
name, scope, ID, and version. You can also store and retrieve properties of a Feature.
Note that Feature properties apply globally to a single Feature definition, not to
instances of Features activated throughout the farm.
. SPFeatureDependency—Represents a Feature upon which another Feature depends.
. SPElementDefinition—Represents a single element that will be provisioned when
the Feature is activated.
Feature collections can be accessed from the following properties on their respective
classes:
. Features on Microsoft.SharePoint.Administration.SPWebApplication
. Features on Microsoft.SharePoint.Administration.SPWebService
. FeatureDefinitions on Microsoft.SharePoint.Administration.SPFarm
. Features on Microsoft.SharePoint.SPSite
. Features on Microsoft.SharePoint.SPWeb
. ActivationDependencies on Microsoft.SharePoint.Administration.
SPFeatureDefinition
26 CHAPTER 3 Programming with Features and Solutions
The next few sections of this chapter provide many examples of programming with the
Features portion of the SharePoint application programming interface (API).

LISTING 3.1 Enumerating Feature Definitions and Features


usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Text;
usingMicrosoft.SharePoint;
usingMicrosoft.SharePoint.Administration;
usingSystem.Windows.Forms;
Programming with Features 27
3
namespace FeatureEnumerator
{
public partial class Form1 : Form
{
private SPSite _rootCollection;
public Form1()
{
InitializeComponent();
}
private string GetFeatureEnabled(SPFeatureDefinition featureDefinition)
{
foreach (SPFeature feature in _rootCollection.Features)
{
if (feature.Definition.Id == featureDefinition.Id)
return “Yes”;
}
return “No”;
}
private void button1_Click(object sender, EventArgs e)
{
featureList.Enabled = true;
featureList.Items.Clear();
string dbConn = @”server=localhost\OfficeServers;initial
➥catalog=SharePoint_Config_66140120-a9bf-4191-86b6-
➥ec21810ca019;IntegratedSecurity=SSPI;”;
_rootCollection = new SPSite(siteUrl.Text);
SPFarm farm = SPFarm.Open(dbConn);
statusLabel.Text = “Site Feature Status (“ +
farm.FeatureDefinitions.Count.ToString() +
“ Feature Definitions Installed)”;
foreach (SPFeatureDefinition featureDefinition in farm.FeatureDefinitions)
{
ListViewItem lvi = new ListViewItem(featureDefinition.DisplayName);
if (featureDefinition.Hidden)
lvi.ForeColor = Color.Gray;
lvi.Tag = featureDefinition.Id;
lvi.SubItems.Add(GetFeatureEnabled(featureDefinition));
featureList.Items.Add(lvi);
28 CHAPTER 3 Programming with Features and Solutions
LISTING 3.1 Continued
}
}
}
}

F eatures are the backbone of SharePoint development because every custom development
project can—and really should—be deployed as a feature. Features give tremendous control
over SharePoint configurations and capabilities at the administrator level. This means that
developers can create features and then turn them over to SharePoint administrators without
having to get involved repeatedly in small configuration changes.

You might also like