Creating Your First Feature


There’s no better way to end the first chapter than to dive in and create a simple Hello World feature from the ground up. This exercise will step you through the fundamental aspects of creating, deploying, and testing a feature. To make things more interesting, at the end of this exercise, we will also add event handlers that will fire whenever the feature is activated and deactivated. The code inside these event handlers will use the WSS object model to change some characteristics of the target site.

In this walk-through, we are going to use Microsoft Visual Studio 2005 to create a new development project for the feature. Using Visual Studio 2005 will provide color coding of XML and ASP.NET tags. Visual Studio 2005 will also provide the convenience of IntelliSense when working with the XML files required to define a 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, but you can create a Visual Basic .NET project instead if you prefer. Eventually, we will add code that will be compiled into the output DLL for the feature’s event handlers. However, first we will get started by creating the feature.xml file.

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 you do your 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, as shown in Figure 1-12.

image from book
Figure 1-12: A Visual Studio project for developing a WSS feature

Next, create an XML file named feature.xml inside the HelloWorld directory. This is where you will added the XML-based information that defines the high-level attributes of the feature itself. 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=""   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. Activation dependencies will be discussed in more detail later in Chapter 9.

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.

image from book
Enabling IntelliSense in Visual Studio

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

image from book

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          Group     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. However, we have avoided this in our example because we want you to go through the process of explicitly activating the feature as users will do through the WSS user interface.

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, navigate to the Site Settings page. In the Site Administration section, click the link with the title Site Features. This should take you to a page like the one shown in Figure 1-13. Note that if you are working within a farm that has MOSS installed, you will see many more features than if you are working within a farm with just WSS.

image from book
Figure 1-13: Once a feature is installed, it can be activated and deactivated by users.

You should be able to locate the HelloWorld feature on the Site Features page. You can then go through the act of clicking the button to activate the feature. Once you have done this, you should be able to drop down the Site Actions menu and see the custom menu item, as shown in Figure 1-14. If you select this custom menu item, you will be redirected to the URL that was defined by the Url attribute of the UrlAction element within the elements.xml file.

image from book
Figure 1-14: A CustomAction element can be used to add custom menu commands to the site actions menu.

After you have successfully activated the feature and tested the custom menu command, you should also experiment by returning to the Site Features page and deactivating the feature. Once you have deactivated the HelloWorld feature, you should be able to verify that the custom menu has been removed from the Site Actions menu.

You have now witnessed the fundamental principle behind features. Developers create various types of site elements that can be added or removed from a site through the process of activation and deactivation.

Adding an Event Handler to a Feature

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

 using System; using Microsoft.SharePoint; namespace HelloWorld{   public class FeatureReceiver : SPFeatureReceiver {     public override void FeatureInstalled(                             SPFeatureReceiverProperties properties){}     public override void FeatureUninstalling(                             SPFeatureReceiverProperties properties) { }     public override void FeatureActivated(                             SPFeatureReceiverProperties properties){       SPWeb site = (SPWeb)properties.Feature.Parent;       // track original site Title using SPWeb property bag       site.Properties["OriginalTitle"] = site.Title;       site.Properties.Update();       // update site title       site.Title = "Hello World";       site.Update();     }     public override void FeatureDeactivating(                             SPFeatureReceiverProperties properties) {       // reset site Title back to its original value       SPWeb site = (SPWeb)properties.Feature.Parent;       site.Title = site.Properties["OriginalTitle"];       site.Update();     }   } }

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

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

Also note that this feature has been designed to store the original value of the site Title so that it can be restored whenever the feature is deactivated. This is accomplished by using a persistent property bag scoped to the site that is accessible through an SPWeb object’s Properties collection. Note that many of the objects in the WSS object model have a similar Properties property, which can be used to track name-value pairs using a persistent property bag. WSS handles persisting these named value pairs to the content database and retrieving them on demand.

Now that we have written the code for the feature’s two event handlers, it’s time to think about what’s required to deploy the HelloWorld.dll assembly. The first thing to consider is that this assembly DLL must be deployed in the Global Assembly Cache (GAC), which means you must add a key file to the project in order to sign the resulting output DLL during compilation with a strong name.

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

 "%programfiles%\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe" -if $(TargetPath) cd $(ProjectDir) Install.bat

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

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

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

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

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

If you have successfully completed these steps, you are well on your way to becoming an accomplished WSS developer. That’s because creating features and programming against the WSS object model are the two most basic skills you need to acquire.




Inside Microsoft Windows Sharepoint Services Version 3
Inside Microsoft Windows Sharepoint Services Version 3
ISBN: 735623201
EAN: N/A
Year: 2007
Pages: 92

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net