4.3. Features

Features could be said to be the most ground-breaking addition to this version of WSS. A SharePoint Feature is a collection of SharePoint elements that can help a user accomplish a particular goal or task. Features can also be described as logical groups of elements that together serve a common purpose. How many times have you had a need to add a chunk of functionality to an existing server farm, web application, Site Collection, or site, such as an event handler, custom navigation, or maybe even a set of lists or document libraries all at once? An example is a set of lists and libraries combined with workflow and custom navigation that contain the functionality required to enable a certain business process to function within SharePoint. Features make it possible to activate or deactivate functionality in the course of a deployment, and administrators can easily transform the template or definition of a site simply by toggling a particular Feature on or off in the user interface. As noted in the SDK, Features provide the following capabilities:

  • Scoping semantics for determining where custom code runs

  • Pluggable behavior for installing or uninstalling Features within a deployment

  • Pluggable behavior for activating or deactivating Features at a given scope

  • A scoped property bag for storing data required by a Feature within its scope

  • The basis of a unified framework for distributed deployment of WSS v3 solutions

A Feature is implemented by adding a subfolder containing a Feature definition file in the following folder ([WSS]TEMPLATEFEATURES). If you were to take a look at this folder after performing a default installation of Office SharePoint Server, you would see 137 Features installed with the product. It is very apparent that SharePoint itself leverages Features throughout its own implementation. Each Feature subfolder must include a Feature.xml file that defines the base properties of the Feature and lists the element manifests associated with it, which are XML files containing additional information about the functionality included in the Feature, along with any other supporting files that the Feature may require in order to function. After a Feature folder is created, you can install, activate, deactivate, and uninstall the Feature using the stsadm.exe command-line tool or through the object model. Features can also be activated and deactivated through the user interface.

When you install a Feature you make its definition known to all front-end web servers across the entire server farm, meaning the area to which the Feature is scoped now displays the Feature in its list of available Features to activate. When you activate a Feature, you make it available at the scope defined within the Feature definition.

The Feature element is used in Feature.xml to define a Feature and to inform SharePoint of the location of all the Feature's supporting files. Items that were previously contained within an extremely large Site Definition file have now been broken out as separate elements within various Features. An element can be described as an atomic unit of functionality within a Feature. A Feature may include any number of elements. Examples of elements, as previously mentioned, may include a custom menu item or an event handler among others. Each element on its own may not be very useful, but a combination of several elements together could make up a very powerful and versatile solution.

4.3.1. Feature Definition File

In a Feature definition file, the Feature element defines a Feature and specifies the location of assemblies, files, dependencies, or properties that support the Feature. Feature.xml contains a top-level Feature element, which in turn has three child elements, ActivationDependencies, ElementManifests, and Properties. The Feature element defines a Feature to activate or deactivate at a specified scope using the attributes in the following table, as noted in the SDK.

AttributeDescription
ActivateOnDefaultOptional Boolean. TRUE if the Feature is activated by default during installation or when a web application is created; FALSE if the Feature is not activated. This attribute equals TRUE by default. The ActivateOnDefault attribute does not apply to site collection (Site) or web site (Web) scoped Features.
AlwaysForceInstallOptional Boolean. TRUE if the Feature is installed by force during installation even if the Feature is already installed. For example, if set to TRUE, Feature installation callouts will always fire anytime a user tries to install the Feature (even if it is already installed) by using either the scanforfeatures or installfeature command-line operation. This attribute equals FALSE by default. The AlwaysForceInstall attribute affects Features of all scopes.
AutoActivateInCentralAdminOptional Boolean. TRUE if the Feature is activated by default in the Administrative web site, site collection, or web application. This attribute equals FALSE by default. The AutoActivateInCentralAdmin attribute does not apply to Farm-scoped Features.
CreatorOptional Text.
DefaultResourceFileOptional Text. Indicates a common resource file for retrieving Feature XML resources. If you specify a resource in the file, WSS v3 looks by default in 12TEMPLATEFEATURESFeatureNameResourcesResources.<Culture>.resx. However, if you want to provide a shared core resource file for all the Features in your application, you can specify an alternate file through which to access resources by using DefaultResourceFile. For example, if you set DefaultResourceFile="MyFile", WSS v3 looks in 12ResourcesMyFile.<Culture>.resx to retrieve localized resources for your Feature.
DescriptionOptional String. Returns a longer representation of what the Feature does.
HiddenOptional Boolean. This attribute equals FALSE by default.
IdRequired Text. Contains the globally unique identifier (GUID) for the Feature.
ImageUrlOptional Text. Contains the site-relative URL for an image to use to represent the feature in the user interface (UI).
ImageUrlAltTextOptional Text. Contains the alternate text for the image that represents the feature.
ReceiverAssemblyOptional Text. If set along with ReceiverClass, specifies the strong name of the signed assembly located in the Global Assembly Cache from which to load a receiver to handle Feature events.
ReceiverClassOptional Text. If set along with ReceiverAssembly, specifies the class that implements the Feature event processor.
RequireResourcesOptional Boolean. TRUE to specify that WSS v3 check whether resources exist for the Feature by verifying that the standard "sentinel" resource for the Feature is present for a particular culture. The resource file is named according to the format <FeatureDir>ResourcesResources.xx-xx.resx, where xx-xx is the culture. The RequireResources attribute allows you to constrict the visibility of certain Features depending on whether resources exist in a particular language for the Feature.
ScopeRequired Text. Can contain one of the following values: Farm (farm), WebApplication (web application), Site (site collection), Web (web site).
ScopeRequired Text. Can contain one of the following values: Farm (farm), WebApplication (web application), Site (site collection), Web (web site).
SolutionIdOptional Text. Specifies the solution to which the Feature belongs.
TitleOptional Text. Returns the title of the Feature. Limited to 255 characters.
VersionOptional Text. Specifies a System.Version-compliant representation of the version of a Feature. This can be up to four numbers delimited by decimals that represent a version.

The ActivationDependencies element is used to specify a list of Features on which the activation of the current Feature depends. If the Feature on which the current Feature depends is hidden and inactive, it is activated automatically. Such a hidden Feature is deactivated when the last Feature depending on it is deactivated. If the Feature is visible, it is not activated automatically. A hidden Feature on its own cannot have any activation dependencies.

Here is an example of a very basic Feature definition. Note that the ElementManifests element is not required. All that is required is a Scope and an ID. A title is useful and recommended, but if not supplied, the system will generate one.

<Feature Title="My Feature"
  Scope="Web"
  Id="24A46E4D-7D86-47c4-A139-06F8B3E4B5AD"
  xmlns="http://schemas.microsoft.com/sharepoint/">
  <ElementManifests>
    <ElementManifest Location="Elements.xml" />
  </ElementManifests>
</Feature>

The ElementManifests element contains references to element manifests and element files that contain definitions for the Feature's elements.

The Properties element contains a list of the default values for Feature properties.

4.3.2. Feature Scope

A Feature is activated for a single scope, including farm (see Figure 4-12), web application (see Figure 4-13), site collection (see Figure 4-14) and site (see Figure 4-15). The Feature scope is set by the Scope attribute of the Feature element.

Figure 4.12. Farm Features, Operations Tab in Central Administration.

Figure 4.13. Web Application Features, Application Management Tab in Central Administration.

Figure 4.14. Site Collection Features, Site Setting of Top-Level Site.

Figure 4.15. Site Features, Site Settings of Site.

While a site Feature is one that you scope at the individual site level, a site collection Feature contains items that apply to the entire site collection (for example, content types that are shared across the site collection), as well as items that can be activated on a per site basis. You also might deploy a custom Forms Based Authentication login screen that you would want to be available to all sites in a site collection, for example. Elements that can have either site collection or site scope include list definitions (templates and instances), modules (file sets), and item content type behaviors (per item custom menu options and per item events).

A Feature that is scoped at the web application level can contain elements for web application assemblies as well as web application administrative links.

A Feature that is scoped to the farm level can contain elements that can function anywhere in a SharePoint farm and can contain links to globally available pages, such as those in the _layouts folder.

Two types of resources can be implemented in Features to support files.

  • Local resources stored in a subdirectory within the Features folder in the TemplateFeatures directory.

  • Shared application Feature and Site Definition resources that are stored in web server extensions 12Resources and are designed to be used across Features and Site Definitions.

4.3.3. Activation Dependencies and Scope

A Feature activation dependency can be defined as a requirement in the relationship between two Features. You can define activation dependencies either for Features of the same scope or for Features across different scopes. A cross-scope activation dependency exists when a Feature at a particular scope has a dependency on another Feature that is at a different scope. Generally speaking, activation dependencies are used for either Feature groupings, as is demonstrated in the following code with the TeamCollab Feature, or to guarantee particular resources for a Feature.

<?xml version="1.0" encoding="utf-8"?>
<Feature
  Id="00BFEA71-4EA5-48D4-A4AD-7EA5C011ABE5"
  Title="$Resources:core,teamcollabFeatureTitle;"
  Description="$Resources:core,teamcollabFeatureDesc;"
  ImageUrl="WssTeamCollaborationFeature.gif"
  ImageUrlAltText=""
  Scope="Web"
  DefaultResourceFile="core"
  xmlns="http://schemas.microsoft.com/sharepoint/">
  <ActivationDependencies>
    <ActivationDependency FeatureId="00BFEA71-D1CE-42de-9C63-A44004CE0104"/>
    <!-- AnnouncementsList Feature -->
    <ActivationDependency FeatureId="00BFEA71-7E6D-4186-9BA8-C047AC750105"/>
    <!-- ContactsList Feature -->
    <ActivationDependency FeatureId="00BFEA71-DE22-43B2-A848-C05709900100"/>
    <!-- CustomList Feature -->
    <ActivationDependency FeatureId="00BFEA71-F381-423D-B9D1-DA7A54C50110"/>
    <!-- DataSourceLibrary Feature -->
    <ActivationDependency FeatureId="00BFEA71-6A49-43FA-B535-D15C05500108"/>

<!-- DiscussionsList Feature -->
    <ActivationDependency FeatureId="00BFEA71-E717-4E80-AA17-D0C71B360101"/>
    <!-- DocumentLibrary Feature -->
    <ActivationDependency FeatureId="00BFEA71-EC85-4903-972D-EBE475780106"/>
    <!-- EventsList Feature -->
    <ActivationDependency FeatureId="00BFEA71-513D-4CA0-96C2-6A47775C0119"/>
    <!-- GanttTasksList Feature -->
    <ActivationDependency FeatureId="00BFEA71-3A1D-41D3-A0EE-651D11570120"/>
    <!-- GridList Feature -->
    <ActivationDependency FeatureId="00BFEA71-5932-4F9C-AD71-1557E5751100"/>
    <!-- IssuesList Feature -->
    <ActivationDependency FeatureId="00BFEA71-2062-426C-90BF-714C59600103"/>
    <!-- LinksList Feature -->
    <ActivationDependency FeatureId="00BFEA71-F600-43F6-A895-40C0DE7B0117"/>
    <!-- NoCodeWorkflowLibrary Feature -->
    <ActivationDependency FeatureId="00BFEA71-52D4-45B3-B544-B1C71B620109"/>
    <!-- PictureLibrary Feature -->
    <ActivationDependency FeatureId="00BFEA71-EB8A-40B1-80C7-506BE7590102"/>
    <!-- SurveysList Feature -->
    <ActivationDependency FeatureId="00BFEA71-A83E-497E-9BA0-7A5C597D0107"/>
    <!-- TasksList Feature -->
    <ActivationDependency FeatureId="00BFEA71-C796-4402-9F2F-0EB9A6E71B18"/>
    <!-- WebPageLibrary Feature -->
    <ActivationDependency FeatureId="00BFEA71-2D77-4A75-9FCA-76516689E21A"/>
    <!-- WorkflowProcessLibrary Feature -->
    <ActivationDependency FeatureId="00BFEA71-4EA5-48D4-A4AD-305CF7030140"/>
    <!-- WorkflowHistoryList Feature -->
    <ActivationDependency FeatureId="00BFEA71-1E1D-4562-B56A-F05371BB0115"/>
    <!-- XmlFormLibrary Feature -->
  </ActivationDependencies>
</Feature>

Recalling the Site Definition you created earlier in this chapter; you may have observed that it used a number of Features. Upon closer inspection, you would have noticed that the TeamCollab Feature defined in the Site Definition's Onet.xml file was actually a wrapper Feature that included a number of dependent Features, noted prior.

  • A BasicWebParts Feature

  • A Three-state Workflow Feature

  • A TeamCollab Feature

  • A MobilityRedirect Feature

The concept of Features containing Features and activation dependencies is immediately clear once you have a basic understanding of how Features work. Start from the most widely scoped Features and work your way down to the most narrowly scoped features in the Onet.xml file of the custom Site Definition.

The MobilityRedirect Feature is an example of a hidden feature that is scoped to the site level. It is installed to allow the site to be rendered seamlessly by mobile devices. If you did not need this Feature in the custom Site Definition you could have easily removed this Feature and not installed it. It is hidden to keep an administrator from inadvertently deactivating it.

The TeamCollab Feature is an example of a Feature that is not hidden, is scoped to the site level, and is activated in the Onet.xml of your custom Site Definition. By inspecting the Feature.xml file for the TeamCollab Feature, you can see that it contains 19 ActivationDependency elements. The TeamCollab Feature is essentially a wrapper feature that subsequently activates the following Features when it is itself activated.

  • AnnouncementsList Feature

  • ContactsList Feature

  • CustomList Feature

  • DataSourceLibrary Feature

  • DiscussionsList Feature

  • DocumentLibrary Feature

  • EventsList Feature

  • GanttTasksList Feature

  • GridList Feature

  • IssuesList Feature

  • LinksList Feature

  • NoCodeWorkflowLibrary Feature

  • PictureLibrary Feature

  • SurveysList Feature

  • TasksList Feature

  • WebPageLibrary Feature

  • WorkflowProcessLibrary Feature

  • WorkflowHistoryList Feature

  • XmlFormLibrary Feature

As you can see, the Feature framework has completely encapsulated many of the items that used to be included in individual Site Definitions in the previous version of WSS. There is no longer a need to define a list or document library in a Site Definition, simply activate the List Template Feature (assuming that it is installed).

The BasicWebParts Feature is an example of a hidden Feature that is scoped to the site collection level. It makes the following familiar Web Parts available to an entire site collection and is activated in the Onet.xml of your custom Site Definition.

  • Content Editor Web Part

  • Page Viewer Web Part

  • Image Web Part

  • Site Users Web Part (Members)

  • Form Web Part (SimpleForm)

  • Relevant Documents Web Part (UserDocs)

  • User Tasks Web Part

  • XML Web Part

When creating activation dependencies there are certain rules you should keep in mind in order to avoid scenarios such as circular dependencies, performance limiting dependency chains, and so on. These rules, from the SDK, are grouped into three distinct categories: same-scope rules, cross-scope rules and general rules.

  • Same-Scope Rules

    1. If a Feature is dependent on another Feature at the same scope, and the second Feature is not activated when the first one is activated, WSS v3 activates the second Feature.

    2. If a Feature is deactivated, WSS v3 deactivates a same-scope dependent hidden Feature when the last visible Feature that has an activation dependency on that hidden Feature is deactivated.

  • Cross-Scope Rules

    1. Cross-scope activation dependencies are not supported if the Feature depended upon is at a more restrictive scope. For example, a site collection-scoped Feature cannot have an activation dependency on a web site-scoped Feature.

    2. Feature activation dependencies are not supported across scopes if the Feature that is depended upon is not visible. In other words, a web site–scoped feature cannot be dependent on a site collection–scoped Feature that is not visible in the user interface.

    3. If the Feature that is depended upon is not activated, activation of the depending Feature fails. For example, if a web site–scoped Feature depends on a site collection–scoped Feature that is not activated, provisioning of the web site Feature (or of a site definition that contains such a web site Feature) fails.

  • General Rules

    1. Dependencies can work only one level deep. In other words, dependency chains are not supported. WSS v3 does not support more than one level in activation dependencies if the last Feature is visible; that is, if a visible Feature depends on a second visible Feature that, in turn, depends on a third visible Feature. However, WSS v3 does support more than one level in activation dependencies if a visible Feature depends on a second visible Feature that, in turn, depends on a hidden Feature.

    2. You can target an activation dependency against hidden or visible Features, but hidden Features cannot have activation dependencies. The Hidden attribute on the Feature element determines whether the Feature is displayed in the user interface.

    3. When more than one Feature has a dependency on a given Feature, keep in mind the danger of leaving one of the depending Features in a bad state. For example, assume that a visible, site collection–scoped Feature named Feature B depends on a hidden, site collection–scoped Feature named Feature A, and that a third visible, web site–scoped Feature named Feature C is also dependent on Feature A. Deactivating Feature B also deactivates Feature A, thus leaving Feature C in a bad state.

4.3.4. Feature Elements

As always, the best way to learn more about how Features are built is to look at the Features that are installed with the product. The following table from the SDK illustrates the various elements and their scoping options that you can include in your own hand-rolled custom Features.

ElementScopeDescription
Content TypeSiteContains a schema definition you can reuse and apply to multiple list definitions.
Content Type BindingSiteContent type binding enables you to provision a content type on a list defined in the Onet.xml schema. Lists defined in the Onet.xml schema cannot be modified directly.
ControlFarm, WebApplication, Site, WebA delegate control contains a registration for a well-known control installed on a web page. This lets you replace existing controls, such as the WSS v3 search control, with another control.
Custom ActionFarm, WebApplication, Site, WebYou can define the following kinds of custom actions:
  • Content type links for the content type settings page

  • Drop-down menu actions for the drop-down menu that appears for an item

  • Form toolbar buttons for New, Edit, or Display form toolbars

  • Site Settings link for the Site Settings page

Custom Action GroupFarm, WebApplication, Site, WebDefines a group of custom actions.
DocumentConverterWebApplicationContains the definition of a document converter. A document converter is a custom executable file that takes a document of one file type, and generates a copy of that file in another file type.
Feature/Site Template AssociationFarm, WebApplication, SiteBinds a feature to a site definition or template so that created sites are provisioned with the feature.
FieldSiteContains a field definition that can be reused among multiple lists.
Hide Custom ActionFarm, WebApplication, Site, WebHides a custom action that has been added through another custom action.
List InstanceSite, WebProvisions a SharePoint site with a specific list of data.
List TemplateSite, WebContains a list definition or template, which defines a list that can be provisioned in a SharePoint site.
ModuleSite, WebContains a set of files with which to provision sites.
ReceiverWebContains an item event receiver registration.
WorkflowSiteContains the definition for a workflow in a list.

The requirements for all of the preceding Feature elements vary, depending on the type of customization you are making. In most cases, a Feature.xml file contains a Feature element that uniquely identifies the Feature, specifies its scope, and points to an XML file whose top-level Elements element defines the elements composing the Feature. The following sections describe a selection of the above Feature element options in more detail. For details on all of the available Feature elements, consult the SDK by visiting http://msdn2.microsoft.com/en-us/library/ms474383.aspx. Alternatively, search the WSS SDK for "Element Types."

4.3.4.1. ListTemplate Element

A ListTemplate element defines a list definition in the Schema.xml file of a particular list type. A list template, once defined, can then be used to create instances of a list. The Schema.xml file for a list can be stored in a ListTemplates subdirectory of the Feature folder, or it can point to another directory. The meat and potatoes of list schemas are beyond the scope of this book, but if you are the curious type, take a look at the Features for each of the out-of-the-box lists because that is where their list schemas are now defined. Remember, they are no longer defined in the Site Definition Onet.xml but have been encapsulated into individual Features.

Imagine that your company has invested many hours in defining a list to use on a Team Site, perhaps for a development project site. This list may have many fields already defined that are required to be on every list instance when it is created. This particular Feature would most likely be scoped to a site collection so that content administrators of all sites in a site collection would be able to create this list simply by going to the Create page. As mentioned earlier, the team collaboration lists Feature is an example of a wrapper Feature that encapsulates many of the lists you see on the Create page. Many of these lists, on their own, are hidden ListTemplate Features. If you were to deactivate this Feature, you would see that you would not be able to create many of the lists normally included on the Create page.

4.3.4.2. List Instance Element

The ListInstance element defines the default data with which to provision a given list type. This element maps to the List element located within the Configuration element in Onet.xml, as discussed earlier in this chapter.

Perhaps your company does not want to burden its development project Team Site users with creating instances of certain predefined lists. They want to ensure that these lists are instantiated correctly, along with default data required that may be specific to each list instance. A list instance Feature could serve that purpose. By activating a list instance Feature, certain lists would be immediately created within a particular site, perhaps enabling standards to be better followed. This Feature becomes very valuable if you have a need to instantiate many lists at once, as this could take some time if done manually as well as be prone to user error.

Following is an example of a List Instance element that creates a Project Announcements list and adds it to the Quick Launch menu. Because this list instance is based on the existing announcements list that is installed with the product, you must reference that list using the FeatureId attribute as well as the TemplateType attribute. This list instance also defines a default item to place in the list.

<ListInstance
  Id="10002"
  Title="Project Announcements"
  FeatureId="00BFEA71-D1CE-42de-9C63-A44004CE0104"
  Description="All Project Announcements should be added to this list."
  TemplateType="104"
  Url="ProjectAnnouncements"
  OnQuickLaunch="TRUE">
  <Data>
    <Rows>
      <Row>
        <Field Name="Title">Welcome to the site!</Field>
      </Row>
    </Rows>
  </Data>
</ListInstance>

4.3.4.3. Custom Action Element

Custom actions can be used to include additional actions to menus of the user interface within WSS v3. They can define a new menu item in the administration menu, or perhaps a new link in the Site Actions drop-down menu. Custom actions can be added to a number of existing menus. To define a custom action for a particular menu, identify the menu by setting the Location attribute, and if needed, set the GroupID attribute to the specific location within that menu. The following table shows the available Location and GroupId values as defined in the WSS SDK.

AreaLocationGroupID
Display form toolbarDisplayFormToolbarn/a
Edit form toolbarEditFormToolbarn/a
New form toolbarNewFormToolbarn/a
List view toolbarViewToolbarn/a
Edit control block menu (per item)EditControlBlockn/a
New menu for list and document library view toolbarsMicrosoft.SharePoint.StandardMenuNewMenu
Actions menu for list and document library viewtoolbarsMicrosoft.SharePoint.StandardMenuActionsMenu
Settings menu for list and document library view toolbarsMicrosoft.SharePoint.StandardMenuSettingsMenu
Upload documents menu for document librariesMicrosoft.SharePoint.StandardMenuUploadMenu
Site Actions menuMicrosoft.SharePoint.StandardMenuSiteActions
Site Settings Site Collection Administration linksMicrosoft.SharePoint.SiteSettingsSiteCollectionAdmin
Site Settings Site Administration linksMicrosoft.SharePoint.SiteSettingsSiteAdministration
Site Settings Galleries LinksMicrosoft.SharePoint.SiteSettingsGalleries
Site Settings Look and Feel linksMicrosoft.SharePoint.SiteSettingsCustomization
Site Settings Users and Permissions linksMicrosoft.SharePoint.SiteSettingsUsersAndPermissions
Site Actions menu for surveysMicrosoft.SharePoint.StandardMenuActionsMenuForSurvey
Site Settings links for surveysMicrosoft.SharePoint.SiteSettingsSettingsMenuForSurvey
Content Type Settings linksMicrosoft.SharePoint.ContentTypeSettingsn/a
Central Administration Operations pageMicrosoft.SharePoint .Administra tion.Operationsn/a
Central Administration Application Management pageMicrosoft.SharePoint .Administration .ApplicationManagementn/a

In addition to specifying the Location and GroupID to have the custom action placed in the appropriate menu location, you also may need to specify the user permissions (Rights) required to perform the action or the placement (Sequence) of the custom action in relation to existing actions in the menu. The URL tokens in the following table are also available to you if needed when building a URL for your custom action:

Custom Action URL TokenPurpose
~siteWeb site (SPWeb) relative link
~sitecollectionSite collection (SPSite) relative link
{ItemId}Integer ID that represents the item within a list
{ItemUrl}URL of the item being acted upon
{ListId}GUID that represents the list
{SiteUrl}URL of the web site (SPWeb)
{RecurrenceId}Recurrence index

4.3.5. Additional Feature Features

There is a rich set of classes available in the object model that allows you to manipulate Features and their properties programmatically. The details on how to use these classes are beyond the scope of this book, but here is a list for reference:

  • Microsoft.SharePoint.SPFeature (SPFeatureCollection)

  • Microsoft.SharePoint.SPFeatureProperty (SPFeaturePropertyCollection)

  • Microsoft.SharePoint.SPFeatureScope

  • Microsoft.SharePoint.Administration.SPFeatureDefinition (SPFeatureDefinitionCollection)

  • Microsoft.SharePoint.SPFeatureDependency (SPFeatureDependencyCollection)

  • Microsoft.SharePoint.Administration.SPElementDefinition (SPElementDefinitionCollection)

The Feature framework also includes a set of classes for responding to Feature events. The following events are supported:

  • FeatureInstalled

  • FeatureUninstalling

  • FeatureActivated

  • FeatureDeactivating

Note that some of these events are post events, meaning that they fire after the respective behavior has been committed and the Feature definition is created in the collection of Feature definitions for the farm.

4.3.6. Installing and Activating Features

During development, Features can be installed and activated via the stsadm command-line administration tool. For production environments, deploying via a WSS v3 Solution, as discussed later in this chapter, is the recommended approach. The following table illustrates the stsadm commands used for Feature management. Regardless of the environment, a Feature must be installed and activated before it can be used. Features must be deactivated before uninstalling them unless they are WebApplication-scoped or Farm-scoped Features.

Feature stsadm CommandDescription
stsadm.exe -o installfeature
{-filename <relative path to Feature.xml> |-name <feature folder>}
[-force]
stsadm.exe -o uninstallfeature
{-filename <relative path to Feature.xml> |-name <feature folder> |-id <feature Id>}
[-force]

stsadm.exe -o activatefeature
{-filename <relative path to Feature.xml> |-name <feature folder> |-id <feature Id>}
[-url <url>]
[-force]

stsadm.exe -o deactivatefeature
{-filename <relative path to Feature.xml> |-name <feature folder> |-id <feature Id>}
[-url <url>]
[-force]


4.3.7. Creating a Feature

The following example demonstrates how to create a Feature. Once created and installed, it can be activated and deactivated as needed within the scope specified in the Feature.xml file. You create two list instance Features as well as a custom action that provides a direct link to www.wiley.com from the Site Actions menu.

4.3.7.1. Create Feature.xml

Follow these steps to create a Feature:

  1. Create a new project by clicking Project under the New option from the File menu.

  2. Under Project types, select the Class Library template under Windows in the language of your choice.

  3. In the Location text box, browse to C:Documents and SettingsAdministratorMy DocumentsVisual Studio 2005projects and click Open.

  4. Uncheck the Create directory for solution check box.

  5. Give your Feature project a meaningful name such as WileyFeature, and click OK.

  6. Add a reference to System.Web.

  7. Add a reference to Microsoft.SharePoint.

  8. Delete the Class1.cs file.

  9. Add a new .xml file to the root of the project by right-clicking the project node and selecting New Item from the Add context menu. Select the XML File template, name the file Feature.xml, and click Add.

  10. Add the following code to your Feature.xml file to define your Feature. Be sure to give your Feature a unique GUID by using the Create Guid external tool on the Tools menu within Visual Studio. You will scope your Feature to Web so that it can be activated on a site-by-site basis.

    <Feature Title="Wiley Feature"
      Scope="Web"
      Id="C4F991C4-4DA8-4af3-94C3-4F416EB76C0F"
      xmlns="http://schemas.microsoft.com/sharepoint/">
      <ElementManifests>
        <ElementManifest Location="Elements.xml" />
      </ElementManifests>
    </Feature>

4.3.7.2. Create Elements.xml

Follow these steps to create an element:

  1. Add a new .xml file to the root of the project by right-clicking the project node and selecting New Item from the Add context menu. Select the xml File template, name the file Elements.xml and click Add. Add the following code to your Elements.xml file to define the two ListInstance elements you want to include in your Feature.

    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
      <ListInstance
        Id="10001"
        Title="Project Contacts"
        FeatureId="00BFEA71-7E6D-4186-9BA8-C047AC750105"
        Description="All Project Contacts should be added to this list."
        TemplateType="105"
        Url="ProjectContacts"
        OnQuickLaunch="TRUE">
        <Data>
          <Rows>
            <Row>
              <Field Name="Last Name">Gates</Field>
              <Field Name="First Name">Bill</Field>
            </Row>
            <Row>
              <Field Name="Last Name">Balmer</Field>
              <Field Name="First Name">Steve</Field>
            </Row>
          </Rows>
        </Data>
      </ListInstance>
      <ListInstance
        Id="10002"
        Title="Project Announcements"
        FeatureId="00BFEA71-D1CE-42de-9C63-A44004CE0104"
        Description="All Project Announcements should be added to this list."
        TemplateType="104"
        Url="ProjectAnnouncements"
        OnQuickLaunch="TRUE">
        <Data>
          <Rows>
            <Row>
              <Field Name="Title">Welcome to the site!</Field>
            </Row>
          </Rows>
        </Data>
      </ListInstance>
    </Elements>

    NOTE

    Be sure to copy the above code exactly as it appears. The FeatureId for both the Contacts List instance and Announcements List instance must match the GUID of their respective Features if the list instance is being based off of an existing list (as they are in this particular case). If they do not, you won't be able to successfully activate your Feature. It will however install. This particular requirement is very difficult to troubleshoot, so pay very close attention.

    As an aside, take a closer look at the GUIDs for the out-of-the-box list template Features you are using in this example. It is interesting to note that the last few characters in their respective GUIDs (Contacts List = 105, Anouncements List = 104) match the list template ID of that particular list in WSS v3.

  2. Add the following Custom Action Element to the Elements collection in your Elements.xml file.

    <CustomAction
      Id="WileyLink"
      Title="Wiley.com"
      Description="Link directly to the Wiley Website"
      GroupId="SiteActions"
      Location="Microsoft.SharePoint.StandardMenu" >
      <UrlAction Url="http://www.wiley.com/" />
    </CustomAction>

4.3.7.3. Deploy Feature

Follow these steps to put your Feature into action.

  1. Enter the following command in the "Post-build event command line" text box to copy the Feature.xml file to the correct location:

    xcopy ....Feature.xml "C:Program FilesCommon FilesMicrosoft Sharedweb
    server extensions12TEMPLATEFeaturesWileyFeature" /y

  2. Enter the following command in the "Post-build event command line" text box to copy the Elements.xml file to the correct location.

    xcopy ....Elements.xml "C:Program FilesCommon FilesMicrosoft Sharedweb
    server extensions12TEMPLATEFeaturesWileyFeature" /y

  3. Save your changes and build the project.

Your Feature is now deployed to the appropriate location on the file system thanks to the post-build events you created above. SharePoint is not aware of the Feature, however, because it is not yet installed.

4.3.7.4. Install Feature

Installing the Feature can be done manually, as demonstrated in the following steps, or through a WSS v3 Solution. The next section returns to this example to demonstrate the use of a Solution to install a Feature, but for now, you will install the Feature manually. Then you will activate it and see the results!

  1. Open a Visual Studio 2005 Command Prompt window by clicking on Start Programs Microsoft Visual Studio 2005 Visual Studio Tools Visual Studio 2005 Command Prompt.

  2. Navigate to the bin directory of the 12 Hive by typing the following command, including the double quotation marks:

    cd "C:Program FilesCommon FilesMicrosoft Sharedweb server
    extensions12BIN"

  3. Install your Feature by typing the following stsadm command:

    stsadm -o installfeature -name WileyFeature

  4. Activate your Feature by browsing to the Site Settings page of a site by clicking on Site Settings under Site Actions. Click on Site features under Site Administration. Click the Activate button next to your newly installed Feature.

  5. Click on Home or the appropriate tab representing the current site's home page to return to the current site's home page.

Notice that you have two new links in the Quick Launch navigation, one for Project Contacts and one for Project Announcements (see Figure 4-16). If you mouse over one of the links, you will notice the URL in the status bar appears. The URL does not contain any spaces (%20) as was explicitly indicated in each of the list instance Feature elements defined earlier.

If you click on either of the two new list instances, you can see that our default items have also been added for you (see Figure 4-17). Clicking on Site Actions after activating your new Feature also reveals your new link to www.wiley.com (see Figure 4-18). Remember, you hard-coded your link right into your Feature's element definition. You could have, with a little bit of work, created a link that was populated from a database, or perhaps even opened in a new window. We'll leave that exercise up to you. A good starting point might be to look at the classes available to you in the Microsoft.SharePoint.WebControls namespace.

We have only touched on two of the element types available for implementing Features. We simply do not have the space in this book to demonstrate them all. We encourage you to peruse the SDK and look at the examples provided. Microsoft has done extensive work in the WSS SDK, and it certainly shows as you will be able to find an example of most Feature element types.

Figure 4.16. Figure 4-16

Figure 4.17. Figure 4-17

Figure 4.18. Figure 4-18

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.197.212