Friday, May 16, 2008

Attaching event handlers to List and document library dynamically

Many times in code we requires to attach event handlers to list or to document library.

Here is the way we can accomplish this.

Method is same for both Document Library as well as List, just for safety point of view, i have caste List into Document Library to indicate that its a document library which is in tern actually a list.

Assuming i have SummaryReport as Document Lib and objClientsWeb is Web in which i have this Document Lib.

SPDocumentLibrary lstDataSummaryReport =
(SPDocumentLibrary)objClientsWeb.Lists["summaryReport"];


Check if same event handler is attached to it, just for precausion we check if there is no event handler is attached to it or not.

if (lstDataSummaryReport.EventReceivers.Count == 0)
{

objClientsWeb.AllowUnsafeUpdates = true;

string strAssembly = "{Project Assembly Name}, Version=1.0.0.0, Culture=neutral, PublicKeyToken={public key token of that project}";;

lstDataSummaryReport.EventReceivers.Add(SPEventReceiverType.ItemAdded, strAssembly,
"{classname}");

lstDataSummaryReport.Update();

objClientsWeb.AllowUnsafeUpdates = false;
}

Make sure of allowunsafeupdate on web is properly managed. Also make sure that User under which code is running must have rights to update this list. otherwise run the code in
SPSecurity.RunWithElevatedPrivileges(
delegate()
{
//Code

});

Which will run under System Account which is having all rights on web

No comments:




Share your SharePoint Experiences with us...
As good as the SharePointKings is, we want to make it even better. One of our most valuable sources of input for our Blog Posts comes from ever enthusiastic Visitors/Readers. We welcome every Visitor/Reader to contribute their experiences with SharePoint. It may be in the form of a code stub, snippet, any tips and trick or any crazy thing you have tried with SharePoint.
Send your Articles to sharepointkings@gmail.com with your Profile Summary. We will Post them. The idea is to act as a bridge between you Readers!!!

If anyone would like to have their advertisement posted on this blog, please send us the requirement details to sharepointkings@gmail.com