Monday, July 19, 2010

A Simple Feature and Feature Receiver (Event handler to a Feature)

Creating Feature:

Let's start off by creating a new Class Library DLL project named HelloWorld. We are going to create a C# project in our example. Eventually, we will add code that will be compiled into the output DLL for the feature's event handlers. 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


 

Given the requirements of feature deployment, it makes sense to create a parallel hierarchy of folders within a Visual Studio project used to develop a WSS feature. This will make it easier to copy the feature files to the correct location and test them as we do our development work. Start by adding a folder named TEMPLATE to the root directory of the current project. Once you have created the TEMPLATE directory, create another directory inside that named FEATURES. Finally, create another directory inside the FEATURES directory using the same name as the name of the feature project. In this case the name of this directory is HelloWorld. Next, create an XML file named feature.xml inside the HelloWorld directory. Add the following XML to the feature.xml file to add a top-level Feature element along with attributes that define the feature itself.


 

<Feature

Id="B2CB42E2-4F0A-4380-AABA-1EF9CD526F20"

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>


 

You see that a feature is defined using a Feature element containing attributes such as Id, Title, Description, Version, Scope, Hidden and ImageUrl. You must create a new GUID for the Id attribute so that your feature can be uniquely identified. You create the feature's Title and Description attributes using user-friendly text. These attributes will be shown directly to the users on the WSS administrative pages used to activate and deactivate 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. As you can see, the Hidden attribute has a value of FALSE. This means that, once installed within the farm, our feature can be seen by users who might want to activate it. You can also create a feature where the Hidden attribute has a value of TRUE. This has the effect of hiding the feature in the list of available features shown to users. Hidden features must be activated from the command line, through custom code, or through an activation dependency with another feature. You will also notice that the ImageUrl attribute has a value that points to one of the graphic images that is part of the basic WSS installation. This image will be shown next to the feature in the user interface. 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.


 

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>


 

This CustomActions element has been designed to add a menu command to the Site Actions menu. It provides a user-friendly Title and Description as well as a URL that will be used to redirect the user when the Menu command is selected. While this example of a feature with a single element does not go very far into what can be done with features, it provides us with a simple starting point for going through the steps of installing and testing a feature. 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


 

Actually, you can also automate the final step of activating the feature within a specific site by running the ActivateFeature operation with the STSADM utility. Once you have added the install.bat file, you can configure Visual Studio to run it each time you rebuild the HelloWorld project by going to the Build Events tab within the Project Properties and adding the following post-build event command line instructions.


 

cd $(ProjectDir)

Install.bat


 

The first line with cd $(ProjectDir)
is required to change the current directory to that of the project directory. The second line runs the batch file to copy the feature files to the correct location and install the feature with the InstallFeature operation of the command-line STSADM.EXE utility. Once the feature has been properly installed, you should be able to activate it within the context of a site. Within the top-level site of the site collection you created earlier this chapter.


 

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 Hello- World.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="B2CB42E2-4F0A-4380-AABA-1EF9CD526F20"

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 namespacequalified 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 Hello- World.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.


 

….. HaPpY CoDiNg

Partha(Aurum)

No comments:

Post a Comment