Wednesday, March 13, 2013

How to Create a Feature in SharePoint 2010


In this article, I'm going to show How to create a simple Feature to change the site title for SharePoint 2010 using Visual Studio 2010 in 10 easy steps:
Step 1: Create a new project in Visual Studio 2010, Choose SharePoint 2010 - Empty SharePoint Project Template, Name the project. Here I've named it as: Crescent.TitleChanger.Feature


 Step 2: Enter the existing SharePoint 2010 site's URL for debugging, Choose the solution type as "Deploy as a farm solution" 

On clicking Finish button, Visual Studio will create a project structure as below.
 Step 3: Right click the Features node, Choose "Add Feature"
Step 4: This will add a feature with name "Feature1" to the project. Rename "Feature1", it give it some meaning . I've named it as "Crescent.TitleChanger"
 Step 5: Change the Title, Descriptions of the feature accordingly. Set the Scope of the project to "Web"
Step 6: Add a Event Receiver to the project by right clicking "Crescent.TitleChanger" and choose "Add Event Receiver"
 Now, we'll get the Feature code(Crescent.EventReceiver.CS) added to our project. 

Step 7: Open the Feature's event receiver code, Un-comment These two methods:
  • FeatureActivated  - We'll place the code to change the Site title to "Feature Activated" inside.
  • FeatureDeactivating  - To change the Site title to "Feature De-Activated"

Step 8. Update the code for Feature receiver as:


public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    using(SPWeb web = (SPWeb)properties.Feature.Parent)
        {
          //Change the Web's Title Property and update
            web.Title = "Feature Activated";
            web.Update();
        }
}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
    using (SPWeb web = (SPWeb)properties.Feature.Parent)
    {
        //Set the Title from Property
        web.Title = "Feature De-Activated";
        web.Update();
    }
}


Step 9: Build and deploy the Project
Step 10: Activate the feature by going to Site Actions >> Site Settings >> Manage Site Features
Click on "Activate" next to our feature "Crescent - Title Changer"

 See it in action! Site title has been changed to "Feature Activated"That's all!


No comments:

Post a Comment