Tuesday, October 18, 2011

Create event receiver in Sandboxed solution is SharePoint

We can create an event receiver using visual studio 2010 in SharePoint 2010 in Sandboxed solution. That event receiver can do something like, your event receiver can add items to a list when the feature is activated.
Steps:
For this first open visual studio 2010 then go to File -> New Project then select an Empty SharePoint Project, give a proper name and click on OK. Then in the SharePoint customization wizard give the local debugging url and choose the option Deploy as a Sandboxed solution then click on Finish.

Now our empty sharepoint project is ready and we need to add a Feature. For this right click in the Features folder in the solution and Add Feature, your Feature.feature is successfully created as shown in the figure below.

Now in the next step we will add the event receiver. For this right click on Feature1 then Add Event Receiver
as shown in the figure below.

Now our event receiver class is ready and we can uncomment the FeatureActivated event and write our own code that will add items to a list.


 public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
using (SPweb web=(SPweb)properties.Feature.Parent )
{
SPList ourList=web.List["ListNameOfTheList"];
SPListItem newItem=ourList.Items.Add();
newItem["Name"]="Our Name for the list item name field";
newItem["Description"]="This is the description";
newItem.update();
}
}

Now our event receiver is ready. Now press F5. It will do everything for us like deploy, activate feature etc. Now open the site and check list. A new item must be added to the list with the name and description given above.

Now we can package the whole item. For this right click on the empty project and click on the project. It will create the .wsp package for us. Now we can add the wsp file to the sharepoint site collection and activate the feature.

Now click on the Site settings in the browser in the top level site and click on Site Settings. Then in the Galleries click on Solutions and in the solutions page, from the ribbon click on Upload solution and in the upload solution dialog, browse to the .wsp file and click on OK. Then activate it. Now the feature is deployed.

Then go to the site settings page -> Go to the Site Actions part and click on Manage site features. Then in the Manage Feature page  locate your feature that you have deployed and then click on the Activate button. Now go to list ListNameOfTheList, you will see a item has been added with the Title and Description given above in the FeatureActivated method.

No comments:

Post a Comment