Pages

Showing posts with label Sharepoint Event Handler Example. Show all posts
Showing posts with label Sharepoint Event Handler Example. Show all posts

Wednesday, September 15, 2010

Sharepoint List Event Handler Types and Example

Hello Friends,
  • Business Case:
    In client organizations there are more than one intranet applications where are related like master- child. So when parent item is deleted at that time all its related child items must be deleted. If not then they are like orphan entries. No use of those entries they just eat up performance when query on that list is executed and also it takes space.
  • Solution:So now delete child entries when its parent entries are deleted we have to use EventHandler in SharePoint.
That’s solution.

Let us go for EventHandler in share point

There are always two types of events attached for every type of event.

1>     Asynchronous – After event occurred
2>     Synchronus –     Before event that occurs

Differences between Sync & Async event handlers are:

1) Synch Event Handler occurs before the event is completed while Asynch occurs after the event is completed.
2) Synch Event Handler is mostly used to stop the event from completion in order to validate few things. It means you can cancel the event using Synch Event Handler while it is not possible to cancel the event from Asynch Event Handler.
3) Synch Event Handler methods has their method names ending with -ing while Asynch Event Handler method names will end with -ed. e.g. ItemAdding, ItemUpdating are Synch Event Handler while ItemAdded, ItemUpdated are Asynch Event Handler methods.
4) Synch Event Handler can be used to Add/Modify the values of list fields while using Asynch Event Handler its not possible as it fires after the completion of event.

Let us look at List Event Handler Solution.
Let me  give you example, I have lists like Program, SubProgram.

So when end user is going to delete Program ,all related its subprogram must be deleted.
Like Parent à Child Relationship. Once parent is deleted we have to delete all its children.
So I created one ListEventhandler.

For any listeventhandler first we have to Implements a related Interface depends on requirement .I have to write Eventhandler for ListItem so I implemented  SPItemEventReceiver.

I added Method is ItemDeleting(Synchronous Event) So after parent list item is deleted this list event handler calls and checkreferencefuntion check whether child list has items with ParentID which we are needed  to be deleted.

I write function because I have more than one child tables for same parent.

So rather than write deleting code for finding child data with same id and deleting data I write code and pass  List and ParentId to that function.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
namespace DeleteData
{
    public class DeleteRefrence : SPItemEventReceiver
    {
        public override void ItemDeleting(SPItemEventProperties properties)
        {
            CheckReferencedata("SubProgram", properties.ListItem["ProgramID"]);
            CheckReferencedata("Department", properties.ListItem["ProgramID"]);
             properties.ErrorMessage = "Parent and Child Items are deleted";
        }
        void CheckReferencedata(String Listname, Object Value)
        {
            SPSite site = new SPSite("SiteURL");
            SPWeb web = site.AllWebs["WebnameWhenthelistsarethere"];
            web.AllowUnsafeUpdates = true;
            SPList list = web.Lists[Listname];
            SPQuery Query = new SPQuery();
            Query.Query = "<Where><Eq><FieldRef Name='ProgramId'/><Value Type='Text'>" + Value + "</Value></Eq></Where>";
            SPListItemCollection AnswerItems = list.GetItems(Query);
            int Count = AnswerItems.Count;
            if (Count > 0)
            {
                for (int index = 0; index < Count; index++)
                {
                    SPListItem item = AnswerItems[index];
                    AnswerItems.Delete(index);
                }
            }
            list.Update();
       }
    }
}

Now we have to register that Eventhandler with that list so when user is delete item we can delete Childitems which are related with that ParentID.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
namespace RegisterEventHandler
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.ReadKey();
            SPSite collection = new SPSite(http://sitename/);
            SPUser user = new SPUser();
            SPWeb site = collection.RootWeb;
            SPList list = site.Lists["Program"];
            string asmName = "DeleteData, Version=1.0.0.0, Culture=neutral, PublicKeyToken=21ce19119994750e";
            string className = " DeleteData.DeleteRefrence";
            // Register the events with the list
            list.EventReceivers.Add(SPEventReceiverType. ItemDeleting, asmName, className);
          // Clean up the code
            site.Dispose();
            collection.Dispose();
            Console.WriteLine("Sucessfully Registered");
            // Return to calling environment : Success
            Environment.Exit(0);
        }
    }
}

Disha Shah

Monday, June 22, 2009

How to access fields of List Item in ItemAdding and ItemUpdating event handlers into SharePoint

When we need to validate something or put restriction before adding or modifying data, at that time we need to use ItemAdding or ItemUpdating Event Handler, here I’ll demonstrate how to access fields of List into event handlers.

Example:

As per my requirements, I don’t want to add duplicate Name into List. For this I need to check that condition before I add and update item to List, I need to use “ItemAdding” and “ItemUpdating” event handlers

public override void ItemAdding(SPItemEventProperties properties)
{
string strName = string.Empty;

foreach (DictionaryEntry entry in properties.AfterProperties)
{
if (entry.Key.Equals("Name"))
{
strName = entry.Value.ToString();
}
}

SPList list = properties.OpenWeb().Lists[properties.ListId];
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='" + list.Fields["Name"].InternalName + "' /><Value Type='Text'>" + strName + "</Value></Eq></Where>";
if (list.GetItems(query).Count > 0)
{
properties.Cancel = true;
properties.ErrorMessage ="Name already exists!";
}
}
public override void ItemUpdating(SPItemEventProperties properties)
{
string strName = string.Empty;
foreach (DictionaryEntry entry in properties.AfterProperties)
{
if (entry.Key.Equals("Name"))
{
strName = entry.Value.ToString();
}
}
SPList list = properties.OpenWeb().Lists[properties.ListId];
SPQuery query = new SPQuery();
query.Query=  "<Where><And><Neq><FieldRef Name='"+ list.Fields["ID"].InternalName+ "' /><Value Type='Number'>"+ properties.ListItemId+  "</Value></Neq><Eq><FieldRef Name='"+ list.Fields["Name"].InternalName+ "' /><Value Type='Text'>"+ strName+ "</Value></Eq></And></Where>" ;
if (list.GetItems(query).Count > 0)
{
properties.Cancel=true;
properties.ErrorMessage ="Name already exists!";
}
}