Tuesday, September 1, 2009

MOSS 2007: Event handler code to add item to a list

I wanted to update a list called "Ann Log" when a new item is added to a "Announcement" list.
So, I used to ItemAdded method of the event handler.
The simple steps are as follows:

  • I use the WSPBuilder project to create and deploy custom code on my portal since WSP builder makes my life really simple.You can download WSPBuilder add in to Visual Studio from here:http://wspbuilder.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=30858
  • Now create a new project of type WSPBuilder .
  • I named it "ListItemFetcher".
  • Add a new item of the type "EventHandler". Keep the scope as "Web".It will automatically create a folder structure with feature.xml and element.xml.
  • In the elements.xml make the receiver type as "ItemAdded" and for Announcements list make the template id as "104"
  • Next open the EventHandler1.cs file and write the code for ItemAdded.
  • Here is my code snippet.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Diagnostics;
namespace ListItemFetcher
{
public class EventHandler1 : SPItemEventReceiver
{
public override void ItemAdded(SPItemEventProperties properties)
{
try
{ //Initializing my site collection url
string sUrl = "
http://sm-cala-csx01:5318/sites/HRDep";
//Always use the "using" statement to ensure proper disposal of the SPWeb and SPSite objects.
using (SPSite siteCollectionOuter = new SPSite(sUrl))

{
//Initializing my web app url since my lists are in a subsite called Docs
using (SPWeb webapp = siteCollectionOuter.AllWebs["/sites/HRDep/Docs"])
{
//The list Ann Log to which I want to add data after Item is added to list Announcements
SPList annLog = webapp.Lists["Ann Log"];
//Adding the Title field of the new item to my Ann Log list
string item = properties.AfterProperties["Title"].ToString();
SPListItem annLogNewItem = annLog.Items.Add();
annLogNewItem["Title"] = item;
annLogNewItem.Update();
} } }
catch (Exception ex)
{
//Writing any exceptions to the event viewer under a source called SharePoint Features
if (!EventLog.SourceExists("SharePoint Features"))
EventLog.CreateEventSource("SharePoint Features", "Application");
EventLog.WriteEntry("SharePoint Features", ex.ToString());
} } }}
  • Now build and deploy the WSPBuilder project.If deploying to another machine use stsadm to deploy the WSP package.
  • Go onto SharePoint Central Admin -->Operations-->Solution Management and check if your ListItemFetcher.WSP is visible.
  • If yes bingo ! your solution has been deployed.
  • Go onto your Site Actions menu of your site -->Site Settings-->Site Features.
  • Activate the ListItemFetcher feature there and check by adding a new item to Announcements List it should add the same Title to Ann Log List.

  • No comments: