Chapter 4. SharePoint features and solutions

Since its early editions, two of the most popular characteristics of Microsoft SharePoint have been its engine for managing custom features and its ability to deploy those features through the installation of solution packages. Despite the addition of the new app model in SharePoint 2013, using features and solutions is still a common way to extend on-premises environments. This chapter will walk you through the various features that you can define, as well as explain how to package SharePoint solutions to deploy those features. Because many of these features will be covered in depth in upcoming chapters, the goal here is to provide a brief overview of all features and solutions to serve as a foundation for later discussions.

Features and solutions

A feature is a customization or extension of the native environment that you can selectively install and activate at various scope levels to deploy solutions modularly and granularly. For example, as you learned in Chapter 3 you can use a feature to deploy custom data structures, such as site columns, content types, list definitions, and so on. You can also use a feature to deploy a custom web template (as you will learn in Chapter 13), automate deployment of pages and Web Parts, and more. The upcoming “Feature element types” section contains a more complete list of the standard features that SharePoint offers.

In general, features let you develop customizations and extensions that take advantage of an out-of-the-box environment for deploying, upgrading, and managing them. The SharePoint Features engine supports automated deployment; automatic management of multiple, load-balanced, front-end web servers for reducing inconsistency issues; and automated upgrading to help avoid versioning issues. Each time you develop a feature, SharePoint creates a feature manifest, which is an XML file named Feature.xml that contains all the information about the feature. SharePoint stores the feature manifest on every front-end web server on the farm in a subfolder of the SharePoint15_RootTEMPLATEFEATURES directory.

Note

SharePoint15_Root refers to the SharePoint root folder, which is typically located at C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions15.

Each feature has its own folder, named for the contained feature; thus, two features cannot share the same folder or the same name in a farm. Each feature’s folder contains all the files required to implement that feature, together with the feature manifest file.

To deploy a feature, you need to install it (which means copying the feature’s folder to each front-end web server), recycle the application pool, and then activate it. After you have deployed a feature, you can upgrade it for maintenance and versioning purposes. You can even deactivate and uninstall a feature.

Every feature has an activation scope that can assume one of the following values:

  • Farm The feature targets the entire SharePoint farm.

  • WebApplication The feature targets a single web application and all the contained site collections.

  • Site The feature targets a single site collection and all of its sites.

  • Web The feature targets a single site.

In addition, every feature type shares the same feature manifest file structure, which is illustrated in The SharePoint feature manifest file structure.

The feature element shown in The SharePoint feature manifest file structure belongs to the http://schemas.microsoft.com/sharepoint/namespace site. It is composed of a set of attributes and accepts optional child elements. Table 4-1 lists and briefly explains each available attribute.

Table 4-1. Attributes supported by the Feature element

Attribute name

Description

ActivateOnDefault

An optional Boolean attribute with a default value of True. It applies only to Farm-scoped or WebApplication-scoped features and determines whether the feature will be activated by default during installation. For WebApplication-scoped features, if this attribute is set to True, the feature will also be activated when a new web application is created.

AlwaysForceInstall

An optional Boolean attribute with a default value of False. When set to True, it forces the feature to be installed—even if it is already installed.

AutoActivateInCentralAdmin

An optional Boolean attribute with a default value of False. It defines whether the feature will be activated by default in the Administrative website hosting SharePoint Central Administration (SPCA). It does not apply to Farm-scoped features. However, in common scenarios, it is not suggested to extend the Central Administration.

Creator

An optional description of the feature’s creator.

DefaultResourceFile

Optional text that defines the name of a common resource file, usually shared with other features released by the same creator. By default, SharePoint will look for resources in a file in the path SharePoint15_RootTEMPLATEFEATURESFeatureNameResources, with a filename such as Resources.Culture.resx (the Culture value can be any of the standard culture names defined by the Internet Engineering Task Force (IETF), such as en-US, it-IT, fr-FR, and so on). However, when you specify a name—for example, MySharedResources, SharePoint will use that name, searching for a file named MySharedResources.Culture.resx in the shared path SharePoint15_RootResources.

Description

Optional text that describes the feature in the UI. You can define it using a resource string in the form of $Resources:ResourceName. For example, if the feature description is a resource item with a key value of FeatureDescription, the corresponding value should be $Resources: FeatureDescription.

Hidden

An optional Boolean attribute with a default value of False. When set to True, the feature will be hidden from the UI and can be activated or deactivated only through the command-line tools or by using the object model.

Id

A required attribute of type text that must contain an ID (GUID) that uniquely identifies the feature.

ImageUrl

Optional text that defines the site-relative URL of an image used to render the feature in the UI.

ImageUrlAltText

Optional text that defines alternate text for the image representing the feature in the UI (see ImageUrl). You can define this using a resource string, just like the Description property.

ReceiverAssembly

Optional text that defines the strong name of an assembly that SharePoint will search for in the Global Assembly Cache (GAC) and that provides a receiver class to handle the feature’s events.

ReceiverClass

Optional text that defines the full class name of a receiver class to handle the feature’s events. SharePoint will search for the receiver class name in the ReceiverAssembly.

RequireResources

An optional Boolean attribute with a default value of False. It determines whether SharePoint requires that resources exist for the language of the current website or site collection to make the feature visible in the UI. This attribute does not affect the ability to activate and manage the feature from the command line or from the object model.

Scope

A required text attribute that defines the scope within which the feature can be activated. The possible values are Farm, WebApplication, Site, and Web.

SolutionId

Optional text that defines the ID of the solution to which the features belong.

Title

Optional text that defines the title of the feature and that is visible in the UI. It is limited to a maximum length of 255 characters. You can define it using a resource string, as described in the Description property.

UIVersion

Optional text that declares the UI version supported by the feature. The value can be specified in multiple ways:

  • =#: The site’s UIVersion must be equal to #.

  • <#: The site’s UIVersion must be less than #.

  • >#: The site’s UIVersion must be greater than #.

  • <=#: The site’s UIVersion must be less than or equal to #.

  • >=#: The site’s UIVersion must be greater than or equal to #.

  • #;#: The site’s UIVersion must be in the semicolon-delimited list of numbers.

Version

Optional text that defines the version of the feature. It can be made of up to four numbers, delimited by periods. For example, it might be 1.0.0.0, 1.0.0.1, and so on.

A Feature tag of a feature manifest can also contain child elements, such as the following:

  • ActivationDependencies Specifies a list of features on which activation of the current feature depends

  • ElementManifests References a set of element manifests or element files, both declaring the definition of the feature

  • Properties Provides a set of default values for the feature’s properties, represented as a tuple of keys and values

  • UpgradeActions Specifies any custom action to execute when the feature is upgraded

The most important children are those declaring one or more elements that make up the feature. These elements correspond to zero or more ElementManifest tags, which are defined through XML files, and zero or more ElementFile tags, which declare files supporting the feature. Both tags provide a Location attribute that references the target file as a path relative to the feature’s folder. A feature manifest file deploying a Web Part shows a feature manifest deploying a Web Part.

The example feature manifest defines only the Scope and the Id attributes for the feature, together with its Title and Description attributes; meanwhile, the Web Part is referenced by the element manifest file located in the relative folder SampleWebPartElements.xml. The Web Part deployment also requires a .webpart file, referenced by the ElementFile tag of the feature manifest.

Using the DefaultResourceFile and RequireResources attributes and the syntax illustrated in the Description and Title attributes (all shown in Table 4-1), your feature can support a multilanguage UI. Simply define a set of resource files for the feature using resource keys instead of text values. For example, A feature manifest supporting multiple languages replaces the explicit values of A feature manifest file deploying a Web Part with resource strings.

The feature manifest declares the Title and Description properties as resources. It also includes a couple of resource files for the default invariant culture (Resources.resx) and for the Italian culture (Resources.it-IT.resx) in the feature deployment. These files are standard .resx files that you can define manually or by using the tools in Visual Studio 2012.

Feature element types

As shown in A feature manifest file deploying a Web Part and A feature manifest supporting multiple languages, the key information in every feature manifest file is the list of one or more element manifest files. Those files are based on the same XML schema as the feature manifest (http://schemas.microsoft.com/sharepoint/). They make use of a predefined set of tags, each of which corresponds to a specific feature type. The full schema for these XML files is defined in the wss.xsd document, available in the SharePoint15_RootTEMPLATEXML folder. Table 4-2 provides a brief description of the main elements available in SharePoint 2013.

Table 4-2. The main feature elements

Feature element name

Description

ContentTypeBinding

Provisions a content type on a list defined in a site template (see onet.xml in Chapter 13). Can be scoped to Site.

ContentType

Defines a content type ready to be used in lists or libraries. Content types are discussed in Chapter 3. Can be scoped to Site.

Control

Customizes the configuration of an existing delegate control, or declares a new delegate control to override the standard SharePoint controls. Can be scoped to Farm, WebApplication, Site, and Web.

CustomAction

Defines an extension to the standard UI. For example, you can use CustomAction to define a new button on a ribbon bar, a new menu item on a standard menu, or a new link on a site settings page. Custom actions are discussed in Chapter 12 Can be scoped to Farm, WebApplication, Site, and Web.

CustomActionGroup

Groups custom actions. Can be scoped to Farm, WebApplication, Site, and Web.

DocumentConverter

Declares a document converter that can convert a document from a type X to a type Y. Requires custom development to implement the converter. Can be scoped to WebApplication.

FeatureSiteTemplate Association

Allows associating a feature to a specific site template definition for provisioning the feature with the site definition when you create a new site with that definition. Can be scoped to Farm, WebApplication, and Site.

Field

Declares a site column definition. Site columns are discussed in Chapter 3. Can be scoped to Site.

HideCustomAction

Hides an existing custom action defined by another custom action or implemented by default in SharePoint. Hiding custom actions are discussed in Chapter 12. Can be scoped to Farm, WebApplication, Site, and Web.

ListInstance

Provisions an instance of a list definition with a specific configuration. Can be scoped to Site and Web.

ListTemplate

Defines a list template for provisioning a custom list’s definitions. List templates are described in Chapter 3. Can be scoped to Web.

Module

Allows provisioning custom pages or files to a site. Module can also be used to deploy configured Web Parts, ListView Web Parts over existing or provisioned lists, NavBar links, and custom Master Pages, as well as to configure properties of the target feature. Modules are discussed in Chapter 12 and Chapter 13. Can be scoped to Site and Web.

PropertyBag

Assigns properties and metadata to items (File, Folder, ListItem, Web) through features. Can be scoped to Web.

Receivers

Defines a custom event receiver. Event receivers are discussed in Chapter 10 Can be scoped to Web.

WebTemplate

Allows deploying a website template, even through a sandboxed solution so that it can create site instances based on that template. Site templates are discussed in Chapter 13. Can be scoped to Site.

Workflow

Deploys a legacy workflow (SharePoint 2010) definition on a target site. Workflows will be covered in Part V Can be scoped to Site.

WorkflowActions

Defines custom workflow actions (SharePoint 2010) for SharePoint Designer 2013. Custom actions for SharePoint Designer 2013 are described in Chapter 17 and Chapter 18 Can be scoped to Farm.

WorkflowAssociation

Associates a legacy workflow (SharePoint 2010) with its target. Can be scoped to Site and Web.

The element manifest file in An element manifest file that defines the Web Part deployed by A feature manifest supporting multiple languages declares the Web Part referenced by the feature in A feature manifest supporting multiple languages.

Feature deployment

To deploy a feature, you need to copy the feature’s folder to the SharePoint15_RootTEMPLATEFEATURES path of every target server for the feature. When this is complete, you can use the STSADM.exe command-line tool (found in the SharePoint15_RootBIN folder) to install and later activate the feature. The following is the syntax to install and activate a feature via STSADM.exe:

STSADM.EXE -o installfeature
           {-filename <relative path to Feature.xml from system feature directory> |
            -name <feature folder>}
           [-force]
STSADM.EXE -o activatefeature
           {-filename <relative path to Feature.xml> |
            -name <feature folder> |
            -id <feature Id>}
           [-url <url>]
           [-force]

As an example, to forcibly install and activate the feature named SampleWebPart, you would use the following syntax from the command prompt:

STSADM.EXE -o installfeature -name SampleWebPart -force
STSADM.EXE -o activatefeature -name SampleWebPart -force -url http://server/site/subsite

Alternately, you can use Windows PowerShell to install and activate your feature. Specifically, you would use the Install-SPFeature and Enable-SPFeature PowerShell cmdlets, which are equivalent options to STSADM:

Install-SPFeature -Path <relative path to Feature.xml from system feature directory> -Force
Enable-SPFeature -Identity <identity of the target feature> -Force -Url <target URL>

For the SampleWebPart example, you would use PowerShell with the following syntax:

Install-SPFeature -Path SampleWebPart -Force
Enable-SPFeature -Identity "SampleWebPart" -Force -Url "http://server/site/subsite"

Meanwhile, to deactivate a previously activated feature, you can use the following syntax from the command prompt:

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

Here’s the syntax to deactivate the SampleWebPart feature from the command prompt:

STSADM.EXE -o deactivatefeature -name SampleWebPart -force -url http://server/site/subsite

Within PowerShell, you can use the following cmdlet for deactivation:

Disable-SPFeature -Identity <identity of the target feature> -Force -Url <target URL>

This is the syntax to deactivate SampleWebPart feature:

Disable-SPFeature -Identity "SampleWebPart" -Force -Url "http://server/site/subsite"

You can also uninstall an inactive feature by using the following STSADM.exe command:

STSADM.EXE -o uninstallfeature
           {-filename <relative path to Feature.xml> |
            -name <feature folder> |
            -id <feature Id>}
           [-force]

This is the specific command for the SampleWebPart feature:

STSADM.EXE -o uninstallfeature -name SampleWebPart -force

Or, you can use the following PowerShell cmdlet:

Uninstall-SPFeature -Identity <identity of the target feature> -Force

From within PowerShell, you uninstall the SampleWebPart feature with the following:

Uninstall-SPFeature -Identity "SampleWebPart" -Force

More Info

For a complete reference on all the available Windows PowerShell scripts for managing features and solutions, refer to the Microsoft TechNet page at http://technet.microsoft.com/en-us/library/ee906565.aspx.

All of these command prompt commands and PowerShell cmdlets offer and support a wide set of parameters; for the sake of simplicity, the examples are abridged. In real life, you should use PowerShell cmdlets because STSADM is provided only for backward compatibility. Moreover, by working with Microsoft Office 365, you will have the opportunity to use PowerShell cmdlets, but you will not be able to access the local command prompt of target servers.

To activate and deactivate a feature, you can use the web browser UI, especially if you like to manage features remotely or want to delegate feature management tasks to users who do not have access to the physical server farm. To manage features through the web browser interface, you need to go to the Site Settings page of the target site, select the Site Actions group, and then select Manage Site Features. Here, you can manage website-level features. If you need to manage site collection features, under the Site Collection Administration group, select Site Collection Features. Both of these menu items will lead you to a feature management page, from which you can activate or deactivate features.

Figure 4-1 shows the feature management page, which lists a site collection’s features. If your features provide multilanguage support, this page will give you the appropriate titles and descriptions, according to the languages configured for the current site and to the current user’s language.

A screen shot of the Site Collection Features page, which lists all the features available at the site collection level. The Status column on the far right of the page indicates which features are active. In addition, each feature listing is accompanied by an Activate or Deactivate button.

Figure 4-1. The Site Collection Features page.

Notice the Activate and Deactivate buttons next to the feature descriptions. You need to have the proper rights to execute these actions, regardless of whether you use the STSADM.exe tool, a PowerShell script, or the web UI. Users can activate/deactivate a feature at the website-level only if they are site owners or higher, and they should do that only with a valid reason. To manage a feature targeting a site collection, you need to have a site collection administrator account. To manage a WebApplication-scoped or Farm-scoped feature, you need to be a farm administrator.

Solution deployment

In the examples thus far, you have copied the features folders to each server by hand. Manually copying these folders is not the best practice, however, because of the high likelihood of errors. An easier and safer approach is to take advantage of a solution package, which is a cabinet file (a .cab compressed file) with a .wsp (Windows SharePoint Services Solution Package) extension provided to automate the process of installing features and customizations. Through a .wsp package, you can deploy a set of one or more features, automatically copying the files and folders to every front-end server from a centralized management console. A .wsp package contains a solution-specific manifest file called a solution manifest (yet another XML file, always with the name manifest.xml), which defines a set of information through attributes and child elements. The solution manifest file structure demonstrates the structure of the solution manifest.

The Solution element belongs to the same namespace as the feature element (see http://schemas.microsoft.com/sharepoint/). Table 4-3 gives a brief description of each attribute of the Solution element.

Table 4-3. Attributes supported by the Solution element

Attribute name

Description

Description

Optional text that briefly describes the solution.

DeploymentServerType

Describes whether the solution targets a front-end server or an application server. It can take the values ApplicationServer or WebFrontEnd.

ResetWebServer

An optional Boolean attribute with a default value of False. If the value is True and the package targets a front-end server, the web server will be reset during deployment of the solution.

ResetWebServerModeOnUpgrade

Specifies the type of reset for the web server. Values are Recycle, for a complete recycle of the application pool, and StartStop, for a stop and start process. ResetWebServerModeOnUpgrade applies only if ResetWebServer has a value of True.

SharePointProductVersion

Defines the version of SharePoint Foundation in target for the current solution.

SolutionId

Defines the ID of the solution.

Title

Defines the title of the solution.

In addition, a Solution tag of a solution manifest can contain child elements, such as the following:

  • ActivationDependencies Specifies a list of solutions on which the activation of the current solutions depend.

  • ApplicationResourceFiles Specifies the application resource files to include in the solution, referencing local or global resource files.

  • Assemblies References a set of .NET assemblies, declared with their strong name, to include in the solution deployment. The referenced assemblies will be copied to all the target servers when deploying the solution.

  • CodeAccessSecurity Specifies custom code access security policies.

  • DwpFiles Provides a list of Web Part deployment files (.dwp).

  • FeatureManifests Provides a list of feature manifests to include in the solution deployment.

  • Resources Specifies the resources to include in the solution.

  • SiteDefinitionManifests Includes site definitions in the solution. To learn more about this topic, see Chapter 13.

  • RootFiles Declares a list of files to include in the solution that will also be deployed on every server of the farm, in a path relative to the SharePoint15_Root folder.

  • TemplateFiles Declares a list of files to include in the solution that will also be deployed on every server on the farm in a path relative to the SharePoint15_RootTEMPLATE folder.

You can deploy a .wsp package using a PowerShell script with syntax such as this:

Add-SPSolution file.wsp

Otherwise, you can use the STSADM.exe command-line tool and the following syntax:

STSADM.EXE -o addsolution -filename filepath.wsp

After installing a solution, you need to deploy it to be able to activate and deactivate it and upgrade its features. Using PowerShell, the following is the minimal script needed to deploy a solution for all the web applications on the farm:

Install-SPSolution -Identity file.wsp -GACDeployment -AllWebApplications

While using the STSADM.exe command-line tool, you can invoke the following command:

STSADM.EXE -o deploysolution
           -name <Solution name>
          [-url <virtual server url>]
          [-allcontenturls]
          [-time <time to deploy at>]
          [-immediate]
          [-local]
          [-allowgacdeployment]
          [-allowcaspolicies]
          [-lcid <language>]
          [-force]

After you add a solution to the farm, however, with SPCA, you can also deploy it using a web browser. Go to the System Settings page, and then click Manage Farm Solutions in the Farm Management group.

Regardless of the interface that you use to deploy a solution, if your farm does not operating 24 hours a day, 7 days a week, you can schedule the deployment at night to avoid any issues or failures during peak daytime usage. If your farm does operate all day, every day, you should have a set of front-end servers configured for network load balancing so that you can deploy and upgrade solutions one server at a time without any service interruption.

Just as you can install and deploy a solution, you can also retract and remove one. To retract a solution, you can still use the SPCA interface. Alternately, you can use a PowerShell script or the STSADM.exe command-line tool. The PowerShell cmdlet takes the following form:

Uninstall-SPSolution -Identity <solution identity>
            [-Time <scheduled time to uninstall>]
            [-AllWebApplications]
            [-WebApplication]

Meanwhile, this is the STSADM.exe syntax for retracting a solution:

STSADM.EXE -o retractsolution
            -name <Solution name>
            [-url <virtual server url>]
            [-allcontenturls]
            [-time <time to remove at>]
            [-immediate]
            [-local]
            [-lcid <language>]

To completely remove an unused solution, you can use the following PowerShell cmdlet:

Remove-SPSolution -Identity <solution identity> [-Force]

If you prefer using STSADM.exe, you need the following syntax:

STSADM.EXE -o deletesolution
            -name <Solution name>
             [-override]
             [-lcid <language>]

Solutions also can help you with versioning issues. After deploying a solution, you can upgrade it through a standard and supported upgrade path, as you’ll learn in the “Upgrading solutions and features” section later in this chapter. Before deploying and upgrading a solution, however, you need to package it, as the next section illustrates.

Packaging with Visual Studio 2012

Visual Studio 2012 natively provides tools that support developers in releasing SharePoint solutions. Whenever you create a SharePoint 2013 project within Visual Studio 2012, you can choose to manage the project deployment through the Packaging Explorer and the Package Designer. These tools give you the ability to graphically define the content of the package that will be compiled while building your solution. Figure 4-2 depicts the interface of the Packaging Explorer and the Package Designer for a sample Web Part project.

The interface includes a tree view on the left, in which you can explore the package structure, as well as an editing interface in the body of Visual Studio. From the editing interface, you can configure the name of the package, the features that will be put inside it (chosen from the set of features available in the current Visual Studio solution), and the order of installation of those features. At the top of the editor, there are three tabs (Design, Advanced, and Manifest) that you can use to change the display of the Package Designer editing section. Figure 4-2 shows the editing section in Design view. In Advanced view, you can provide custom .NET assemblies (DLLs) that will be deployed by the current package. In Manifest view, you can see the autogenerated XML of the manifest, and you can customize the XML template that is used to generate it to provide any custom tag or attribute that’s not defined by default. You can also take full control of the XML manifest content, replacing the autogenerated code with a completely manual version.

A screen shot of the Packaging Explorer and the Package Designer available in Visual Studio 2012. The main items you can configure using these tools include the name of the solutions, the features to deploy, as well as advanced features of the target package.

Figure 4-2. The Visual Studio 2010 Packaging Explorer and Package Designer interface.

In addition to using the Packaging Explorer, you have the ability to manage the configuration of each feature included in the package. To configure a feature, double-click it in the Visual Studio Solution Explorer, or click the Edit command available for each feature in the Packaging Explorer. The feature editor is the place to provide descriptive information for the feature, such as its title and description; configuration and behavioral parameters, including the target scope of the feature; the set of items that make up the feature; and any feature activation dependencies. A feature activation dependency gives you the ability to define a sequence of deployment for features. For example, you can create a sequence that prevents you from deploying one specific feature before another specific feature has been deployed. As with the Packaging Explorer, you can switch to Manifest view so that you can see the XML that describes the current feature. You can also customize the XML using a model or from scratch.

Note

If you right-click a feature item in Solution Explorer, you can create custom resource files and add feature event receivers, which will be discussed in the upcoming “Feature receivers” section.

After you define a package, right-click the Visual Studio project that contains it, and then deploy the .wsp package by clicking Deploy. By default, Visual Studio will deploy the package on the farm that you chose when you created the project. In a development environment, you usually target the local server, which performs double-duty as the development machine and the SharePoint server for first testing your solutions. You can also simply create the package by clicking the Publish menu item, in which case you will be prompted to select the target file location. The publishing command is useful whenever you need to deploy the .wsp package into an external environment and you need to copy the .wsp file from your development environment to the target environment. Lastly, you can retract a solution from the SharePoint server where you previously deployed it by clicking the Retract menu item. If you deploy a solution on a server where you have already deployed it—for example, because you fixed some bugs and you want to repeat solution testing—the deploy process offered by Visual Studio 2012 will automatically retract the old version and release the new one, deactivating the features before retraction and activating them again during deployment. From the perspective of SharePoint, it would be better to upgrade the solutions, as you will see in the next section of this chapter. For the sake of simplicity, however, Visual Studio retracts it and deploys it again.

Upgrading solutions and features

During the course of a solution’s lifetime, you may eventually need to upgrade and customize your code. SharePoint 2013 provides a rich set of capabilities to support you while upgrading solutions and features. In fact, you can upgrade a solution to update a .wsp deployment from an older version to a current one. To upgrade a solution, you can use the following PowerShell cmdlet:

Update-SPSolution -Identity <solution identity> -LiteralPath <path of the updated WSP>
            [-CASPolicies]
            [-FullTrustBinDeployment]
            [-GACDeployment]
            [-Force]

For the SampleWebPart deployment package, use a PowerShell script like the following:

Update-SPSolution -Identity file.wsp -LiteralPath c:file_v2.wsp -GACDeployment

You can also use the STSADM.exe command:

STSADM.EXE -o upgradesolution
            -name <Solution name>
            [-filename <upgrade filename>]
            [-time <time to upgrade at>]
            [-immediate]
            [-local]
            [-allowgacdeployment]
            [-allowcaspolicies]
            [-lcid <language>]

Thus, for the SampleWebPart deployment package example, the syntax would be the following:

STSADM.EXE -o upgradesolution -name SampleWebPart.wsp -allowGacDeployment

No matter which method you use, SharePoint updates the .wsp package stored in the configuration database and synchronizes every target server in the farm with the content of the new package. For example, if your update includes new files (DLLs, ASPX pages, JS files, and so on), the upgrade process will copy them to all of the servers within the farm. At the same time, if your upgrade removes items that you will no longer use, the upgrade process will remove them from all the servers.

Important

Be careful designating files for removal. If files are shared with other solutions, the SharePoint update process will still remove them, potentially breaking functionalities of other solutions. For further details about upgrading solutions, read the document “Upgrading a Farm Solution in SharePoint 2010,” available on MSDN at http://msdn.microsoft.com/en-us/library/aa543659.aspx.

The feature’s manifest schema provides elements that you can use to upgrade custom features through versioning and declarative upgrade actions. The Server Object Model provides specific types and members for this purpose. These are useful for querying at various scopes (SPWebService, SPWebApplication, SPContentDatabase, and SPSite) and retrieving the features’ current versions. Using types to query for features that need to be upgraded illustrates how to query a site collection for all the features that need to be upgraded.

The QueryFeatures method of the SPSite class can search for features to upgrade while the Upgrade method on each SPFeature instance upgrades it effectively. The interesting part of the discussion is what happens during the feature upgrade process.

Every feature has a version number attribute specified in its manifest, so you can upgrade a feature by simply incrementing the version number; for example, you can use the Properties section of the Package Designer to release a new .wsp package to deploy the new version via an upgradesolution command. Beginning with SharePoint 2010, the feature manifest file has a section in which you can declare upgrade actions to execute during the Upgrade process. These upgrade actions are defined inside an UpgradeActions configuration element (see The SharePoint feature manifest file structure), where you can define custom actions to execute while upgrading a feature. You can use the AddContentTypeField element to define a field (for instance, a site column) that will be automatically added to a content type, eventually pushing the modification to inheriting content types and lists. You can also specify element manifests to apply during an upgrade by using the ApplyElementManifests tag with its child elements, ElementFile and ElementManifest. Using this last element, you can create new content, like list definitions, site columns, content types, list instances, custom pages, and so forth. Using the MapFile element, you can specify mapping between old and new files. Lastly, if you need to execute custom code during the upgrade process, you can configure the CustomUpgradeAction tag, which will reference a custom upgrade action defined in a feature receiver. You will learn more about feature receivers in the next section.

Occasionally, you might need to release a version upgrade in multiple environments that require different versions of the same feature. For example, imagine having a new feature with a current version of 2.0.0.0 that you want to update on a pair of customers’ farms, called Farm1 and Farm2. Farm1 is currently running version 1.0.0.0 of your feature and Farm2 is running version 1.5.0.0. In such a scenario, you should define a new package with a path to upgrade your feature from version 1.0.0.0 to version 2.0.0.0, and from version 1.5.0.0 to version 2.0.0.0, as well.

Luckily, the schema of the feature manifest supports declaration of version ranges via the VersionRange element—a child of the UpgradeActions element. Thus, you can define two different upgrade paths based on the initial version of the feature that you want to upgrade. A feature manifest that supports versioning with multiple upgrade paths shows an example of a feature manifest that satisfies this scenario.

The VersionRange element accepts two attributes: BeginVersion and EndVersion. The former is a lower inclusive limit and the latter is an upper exclusive limit. Thus, the first VersionRange defined in A feature manifest that supports versioning with multiple upgrade paths refers to features with a version greater than or equal to 0.0.0.0 and lower than 1.5.0.0, whereas the second VersionRange matches features with a version greater than or equal to 1.5.0.0 and lower than 2.0.0.0. In this example, the feature simply maps an old .aspx file to a newer one. Of course, during a feature’s upgrade process, you can do whatever you want because you can invoke custom SharePoint code using a feature receiver.

More Info

For further details, read the MSDN “Upgrading Features” page at http://msdn.microsoft.com/en-us/library/aa544511.aspx.

Feature receivers

A feature receiver is a class that executes custom code upon the occurrence of specific life cycle–related events, usually by making use of the SharePoint Server Object Model. Every feature receiver adheres to the architecture of the SharePoint event receivers, which are described in Chapter 10 A feature receiver can trap the following events:

  • Feature activation This occurs when a feature has been activated.

  • Feature deactivating This occurs while a feature is deactivating.

  • Feature installation This occurs when a feature has been installed.

  • Feature uninstalling This occurs while a feature is uninstalling.

  • Feature upgrading This occurs while a feature is upgrading.

To implement your own feature receivers, you need to define a new class that inherits from the base abstract class, SPFeatureReceiver, which is defined in the Microsoft.SharePoint namespace. The definition of the SPFeatureReceiver base abstract class presents the definition of the SPFeatureReceiver abstract class.

Each of the virtual methods accepts an argument of type SPFeatureReceiverProperties, which allows access to information about the target feature, its definition, and the current site. The definition of the SPFeatureReceiverProperties class declares the SPFeatureReceiverProperties class.

Through the properties of this class, you can do practically anything that you want, writing custom code to implement everything that is not already available through standard feature elements.

Important

Although the SPFeatureReceiverProperties class implements the IDisposable interface, you should not dispose of it directly; the infrastructure code of SharePoint Foundation already handles the disposal of instances of this type.

To create a feature receiver, you need to implement the receiver class, build its assembly, put it into the GAC, and declare the ReceiverAssembly and ReceiverClass attributes in a feature manifest XML file. The manifest of a feature with a custom feature receiver illustrates an example of a feature manifest with a receiver declaration.

Note

The values of the ReceiverAssembly and the ReceiverClass attributes in The manifest of a feature with a custom feature receiver need to be defined on a single of code.

A sample feature receiver that handles FeatureActivated and FeatureDeactivating events shows a sample feature receiver, creating a list instance when the feature is activated and deleting the list instance while the feature is deactivating.

A sample feature receiver that handles FeatureActivated and FeatureDeactivating events illustrates that you should access the context of your feature through the Feature.Parent property of the current SPFeatureReceiverProperties argument. Depending on the scope of your feature, the Parent property could be the whole farm (SPFarm), a single web application (SPWebApplication), a site collection (SPSite), or a single website (SPWeb). It is up to you to know the target scope of your feature, and consequently determine the appropriate type to be hosted by the Parent property. In A sample feature receiver that handles FeatureActivated and FeatureDeactivating events , the scope of the feature is a site collection; thus, the SPSite type is used. If you are implementing a feature receiver that creates content during activation, it’s a good habit to delete that content while deactivating. Sometimes, however, it’s a good idea to leave data upon deactivation of a feature so that you don’t dispose of data critical to end users. For example, if your feature created custom list instances or libraries, simply deleting them would be a bad idea. In fact, users may have used those lists and libraries to store custom data, which would be lost in a silent removal. Additionally, if your feature is activated and deactivated many times during the life cycle of your solutions, it’s possible that you could activate it on a site where the contents created by the FeatureActivated event already exist. To prevent this, the code in A sample feature receiver that handles FeatureActivated and FeatureDeactivating events checks for any previously existing list instance, prior to creating it.

Visual Studio 2012 provides a shortcut for creating feature event receivers. To access it, go to Solution Explorer and right-click a feature item within the Features folder of your SharePoint project to open the shortcut menu. There, you can select the Add Event Receiver menu item, which will create all the plumbing code for you. You will only need to write the code of the receiver’s methods. Figure 4-3 shows the shortcut menu of a feature in Solution Explorer.

A screen shot of the shortcut menu that results from right-clicking a feature name in Visual Studio 2012. The Add Event Receiver and Add Feature Resource options are highlighted.

Figure 4-3. The Add Event Receiver menu item in a feature in Visual Studio 2012.

Important

Be very careful when you define error handling code while implementing custom feature receivers. Any unhandled exception could lead to instability in your solution and block your feature deployment or removal.

Handling FeatureUpgrading events

One feature receiver event that deserves a dedicated section is FeatureUpgrading. Introduced in SharePoint 2010 for handling feature upgrades, this method targets all situations in which you need to upgrade a feature executing custom code. If you override the FeatureUpgrading method, you will receive an instance of the SPFeatureReceiverProperties type, as you do with all the other methods of the feature receivers. You will also receive an argument of type String with name upgradeActionName and an argument of type IDictionary<String, String> with name parameters. The values for these arguments can be defined in the feature manifest file, within the UpgradeActions section of the file schema (see A feature manifest that supports versioning with multiple upgrade paths ).

How would you use this method in practice? Suppose that you deployed the SampleWebPart feature version 1.0.0.0 in your environment. Later, you decide to upgrade it to version 2.0.0.0. This new version of your Web Part needs to change (by code) the configuration of the list instance that you created in the FeatureActivated event in A sample feature receiver that handles FeatureActivated and FeatureDeactivating events. Assume that your upgrade method changes the OnQuickLaunch status of the Sample List and configures the ContentTypesEnabled property. The feature manifest file with the configuration of the custom upgrade action shows the feature manifest with the configuration of the custom upgrade action.

Note

The values of the ReceiverAssembly and the ReceiverClass attributes in The feature manifest file with the configuration of the custom upgrade action need to be defined on a single line of code

The custom upgrade action is defined using a Name attribute and a set of Parameter elements. Meanwhile, Using the FeatureUpgrading method implementation to handle the custom upgrade action demonstrates the implementation of the FeatureUpgrading method, which uses the custom upgrade action configuration.

The method invocation receives the Name attribute of the CustomUpgradeAction element inside the upgradeActionName argument, as well as the set of Parameter elements through the parameters dictionary. Based on these arguments, the upgrade code can now do whatever is necessary to upgrade the feature.

Summary

This chapter discussed how to take advantage of features and solutions to deploy customization and custom code. Specifically, it described how to package features in .wsp packages and how to deploy them, as well as how to upgrade features using the capabilities provided with SharePoint 2013. In future chapters, especially those in Part IV you will dig deeper into implementing some of the main features that are useful when developing and customizing SharePoint solutions.

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

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