Tuesday, March 20, 2012

Create Event Handler to Force Unique in MOSS 2007 with WSP Builder

Long back, I did an Event handler to prevent duplicates in a SharePoint list. There is a another requirement of same kind now. This time, Let me do it with WSP builder. Requirement is simple - Prevent duplicate titles from a List. Hmm.., But in SharePoint 2010 this is an instinct feature, we don't need to do any event handlers.

Lets get started.

Create an Event handler for SharePoint 2007 with WSP Builder - Step by step:

Step 1:  Open the Visual studio, Create a New Project, Choose WSP Builder Project type

Create Event Handler for MOSS 2007 with WSP Builder

Step 2: Add a new item to the Project
create event handler moss 2007

Step 3: Choose Event Handler under WSP Builder node, Name it and click "Add"
sharepoint 2007 wspbuilder event handler

Step 4: In the Event Handler code, place this code:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

namespace PreventDuplicateEventHandler
{
    class PreventDuplicates : SPItemEventReceiver
    {
        public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);
              try
                {
                    using(SPSite oSPSite= new SPSite(properties.WebUrl))
                    {
                        SPWeb oSPWeb = oSPSite.OpenWeb();
                        SPList oSPList = oSPWeb.Lists[properties.ListId];

                        SPQuery oSPquery = new SPQuery();
                        oSPquery.Query = @"<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + properties.AfterProperties["Title"] + "</Value></Eq></Where>";
                        SPListItemCollection oListItemColl = oSPList.GetItems(oSPquery);
                        if (oListItemColl.Count > 0)
                        {
                            properties.Cancel = true;
                   properties.ErrorMessage = "There is already an item with the title " + properties.AfterProperties["Title"] + " in this list";
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.EventLog.WriteEntry("Error encountered in Event Handler", ex.Message);
            }

        }

    }
}

Step 5: Build the project, Build the WSP, Deploy the WSP.

Step 6: Navigate to the site, go to Site settings >> Site features >> and then activate "Prevent Duplicate" feature.

Activate Feature in Site Features

Step 7: Now, we have feature ready. We have to associate the event handler with our List. To do that there are lot of tools available. Here is one of them: SharePoint Event Explorer. Download and run the executable. (By the way, You can write your own  code to register the event handler)

Step 8: Register the event handler to the desired list.
Event Handler Manager to Regiter Unregister Event Handler with SharePoint List or Library
Update:
Found a bug in the above tool! use http://speventreceiverman.codeplex.com/ instead!!!

That's all. We are done, See it in action!!
Force Unique in MOSS 2007 with event handler



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Check out these SharePoint products:

6 comments :

  1. Thanks for the walthrough. Could you please fix the link given in step# 7

    ReplyDelete
    Replies
    1. Thank you for your real quick response buddy!

      Delete
    2. thanks fo helping me out

      Delete
  2. Really nice article!!

    But remember that SPQuery only works with up to 2000 items limit.
    Helpful links:

    http://msdn.microsoft.com/en-us/library/bb687949(v=office.12).aspx#UsingSPQueryObjs
    http://blogs.msdn.com/b/sowmyancs/archive/2008/10/26/best-practices-sharepoint-object-model-for-performance-tuning.aspx

    Thanks!

    ReplyDelete
  3. I set properties.Cancel = true and properties.ErrorMessage = "Custom Validation Error Message" in the itemUpdating synchronous event receiver method. Instead of seeing the SharePoint error page, I am getting the IIS server error page with the full stack trace, etc. What am I missing?

    ReplyDelete

Please Login and comment to get your questions answered!

You might also like:

Related Posts Plugin for WordPress, Blogger...