Wednesday, June 1, 2011

Adding Events and EventHandlers in SharePoint Website

There are two type of event handlers in SharePoint.
1.Synchronous
2.Asynchronous
Synchronous are those who before the action is committed. E.g. Deleting, updating
Asynchronous are those which performed after the action completed. Deleted , Updated
 Creating Events for SharePoint website is done after doing various steps, first create event
and second attach them to you website. Both are different process;  now I am describing
the first step:
Create a class library Project. Reference the C:\Program Files\Common Files\Microsoft
Shared\web server extensions\12\ISAPI\SharePoint.dll from the 12 hives.

 Inherit SPItemEventRecevier in the class as: 

namespace B1.Events
{
    public class ListReceiver:SPItemEventReceiver
    {
    }
}

Now  override the  ItemAdded method of SPItemEventReceiver Class and write your code
 for the Event. Here I am going to creating an event for my custom list of website name Demo List.
public override void ItemAdded(SPItemEventProperties properties)
        {
          // base.ItemAdded(properties);
        }
now write the code in this method that fire after adding an item in the list.
My Website's custom List have columns as in the Figure:
Figure 1

public override void ItemAdded(SPItemEventProperties properties)
        {
            //base.ItemAdded(properties);
            SPListItem item = properties.ListItem;
            String title = item.GetFormattedValue("Title");
            String desc = item.GetFormattedValue("Desc");

            //read Title and Desc and write in the Result when Item
            // is added to list
            item["Result"] = "Title is : " + title + " and desc is : " + desc;
            item.Update();
        }
        public override void ItemDeleting(SPItemEventProperties properties)
        {
            //base.ItemDeleting(properties);
            SPListItem item = properties.ListItem;
            String status = item.GetFormattedValue("Status");
            if (status.ToLower() == "in progress")
            {
                properties.Cancel = true;
                properties.ErrorMessage = "You can not deleted "+
                   this item, the status is in progress!!";
}
}
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            //base.ItemUpdated(properties);
           
// this.DisableEventFiring() revoke to Update event firing Loop
           
// if you are adding an item then it will call update event
           
// again and again.

            this.DisableEventFiring();
            SPListItem item = properties.ListItem;
            item["Result"] = "Updated...";
            item.Update();
            //
            this.EnableEventFiring();
        }
Build the solution.
Now Sign in the class library to publish it to the GAC (Global Assembly Cache) using these steps:

Right click on the project in Solution Explorer and select properties.
Select Signing in left side list
Click the check box 'Sign the assembly'
Create New Key and give key file name as in the Figure

Figure 2

Again Build the solution.
Now use the GACUTIL utility to put this dll to the GAC as:
gacutil –i B1.Events.dll
Figure 3


To test/ Debug the event and the solution select Attach to Process from the Debug Menu and select the
process as in the Figure:

Figure 4


and now add some item in list of your website. That will not add  test in the Result column now. You have to attach these to the your website using some Program. To do so create a Console Application and start writing the following statements to attach these events to SharePoint website:

Create new console Application named AttachListEvents and add reference to Microsoft.Sharepoint from 12 hives.
Now open your website and get the reference of you list in as SpList variable as:

SPSite spSite = new SPSite("http://temple:44/");
               SPWeb spWeb = spSite.OpenWeb();
                SPList list = spWeb.Lists["Demo List"];

to add these events you need to get the assembly information of your created events class library (DLL) that you have to placed in the GAC. You need the PublicKeyToken of that assembly. To get this go run in the start menu and type assembly and find your placed library. Open properties of this dll by double clicking it or selecting properties after right click it. Now you will get the all information that you need to attach with your website. You should know the class name of your DLL. You have specify this also.
Figure 5
Here you will get the Version information , Public Key Token etc.
Use the following statement to attact the event with your list.
list.EventReceivers.Add(SPEventReceiverType.ItemAdded,
"B1.Events, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=eb5915b1dbd1037d"
,
                    "B1.Events.ListReceiver"); 
the comlete code file of attaching these events is as:
namespace AttachListEvents
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Starting .....");
                SPSite spSite = new SPSite("http://temple:44/");
 
               SPWeb spWeb = spSite.OpenWeb();
                SPList list = spWeb.Lists["Demo List"];
                list.EventReceivers.Add(SPEventReceiverType.ItemAdded,
                            "B1.Events, Version=1.0.0.0, Culture=neutral,
                                            PublicKeyToken= eb5915b1dbd1037d "
,
                               
                        "B1.Events.ListReceiver");

                list.EventReceivers.Add(SPEventReceiverType.ItemUpdated,
                                "B1.Events, Version=1.0.0.0, Culture=neutral,
                                          PublicKeyToken= eb5915b1dbd1037d "
,
                                                         "B1.Events.ListReceiver");
                Console.WriteLine("Successfully done!!!");
                Console.Read();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.Read();
            }
        }
    }
}

Run this Code and you will see this out screen if everything is correct.
Figure 6
restart the IIS and then check your list for the changes:
to restart IIS use the iisreset command.
Now check this and add a new row in the list.

Figure 7


and the result is:
Figure 8.



you add your event and remove these event using this program. You need not to run this code to attach events
to the website. It is only one time work. Once done no need to repeat again.

Hope this will be helpful to you..  Happy Programming!!

No comments :

Post a Comment