Archive for EventHandler

SharePoint Object Model: ListItem Reference in ItemAdding Event Handler


public
override
void ItemAdding(SPItemEventProperties properties)

{


SPSite spSite = new
SPSite(properties.SiteId);


SPWeb webSite = spSite.OpenWeb();


SPList spList = webSite.Lists[properties.ListId];


SPListItem listItem = spList.Items[spList.Items.Count – 1];

 

}

Advertisements

Leave a Comment

Event Handler to Synchronize (Populate Data) List / Document Library Columns Form Other Document Library / List Columns

We have created a solution for one of our clients. The solution is based on uploading documents and attaching workflows with the documents.

Uploaded documents have different columns describing the document’s meta data. Our clients’ wants that these column in the task list.

We decide to write two event handlers. One was against the list and other was against the document library.

The event handler against list runs when a task is created in the task list. It fetches the information from the desired columns in the document library and populates the columns in the task list row.

The code is:

 public class MyClass : SPItemEventReceiver    {       

public override void ItemAdded(SPItemEventProperties properties)        {           

SPListItem item = properties.ListItem;                       

SPFieldUrlValue MyURL = null;           

SPView DefaultView = null;           

SPQuery SelectQuery = null;           

SPListItemCollection SelectedDoc = null;            

string URLText = null;           

string URL = null;                        

SPWeb site = (SPWeb)properties.OpenWeb();           

SPList DocLib = site.Lists[“Document Library Name”];                

MyURL = new SPFieldUrlValue((string)item[“Link”]);           

URL = MyURL.Url; URLText = URL.Substring(URL.LastIndexOf(‘/’) + 1);         

DefaultView = DocLib.DefaultView;            

SelectQuery = new SPQuery(DefaultView);            

SelectQuery.Query = “<Where><Eq><FieldRef Name=’FileLeafRef’/><Value Type=’Text’>” + URLText + “</Value></Eq></Where>”           

SelectedDoc = DocLib.GetItems(SelectQuery);  

foreach (SPListItem doc in SelectedDoc) // run for once            {                  

item[“Col 1”] = doc[“Col 1”];                 

item[“Col 2”] = doc[“Col 2”];                 

item[“Col 3”] = doc[“Col 3”];                 

item.Update();           

}              

site.Dispose();                     

}

}

The second event handler was written against the document library for synchronization purpose. If user changes / update the data in the document library column, these changes must be reflected in the task list column. The event handler capture and runs against the update vent.

The code is:

 public class MYClass1 : SPItemEventReceiver    {       

public override void ItemUpdated(SPItemEventProperties properties)        {            

string DocName = null;           

string DocTitle = null;            

SPView DefaultView = null;           

SPQuery SelectQuery = null;           

SPListItemCollection SelectedDoc = null;                       

SPListItem doc = properties.ListItem;           

SPWeb site = properties.OpenWeb();           

SPList TaskList = site.Lists[“Task List Name”];            

DocName = doc[“Name”].ToString();                       

DocTitle = DocName.Substring(0,DocName.LastIndexOf(‘.’));            

DefaultView = TaskList.DefaultView;            

SelectQuery = new SPQuery(DefaultView);             

SelectQuery.Query = “<Where><Eq><FieldRef Name=’LinkTitle’/><Value Type=’Text’>Please approve “ + DocTitle + “</Value></Eq></Where>”           

SelectedDoc = TaskList.GetItems(SelectQuery);            

foreach (SPListItem task in SelectedDoc)             {               

task[“Col 1”] = doc[“Col 1”];               

task[“Col 2”] = doc[“Col 2”];               

task[“Col 3”] = doc[“Col 3”];               

task.Update();           

}           

site.Dispose();       

}

}

In this way, changes in the columns of document library will be immediately visible in the columns of task list as well.  

In case you don’t know how to create and deploy event handler, follow this link.

Comments (8)

Adding an Event Handler to a Feature in MOSS

We will try to provide as much detail as possible while trying to explain how to write an event handler, but if you find difficulty in understanding event handler concepts, explore the this link . We will use the feature added in the previous post 

Open the project “HelloWorldFea” and rename Class1.cs to “FeatureReceiver.cs”. Add the reference of Micrososoft.SharePoint.dll. (if you don’t know how to add, click here). Write the following code in “FeatureReceiver.cs” file. 

using Microsoft.SharePoint; 

namespace HelloWorldFea{   

public class FeatureReceiver : SPFeatureReceiver    { 

public override void FeatureActivated(SPFeatureReceiverProperties properties)       

{           

SPWeb site = (SPWeb)properties.Feature.Parent;           

site.Properties[“OriginalTitle”] = site.Title;           

site.Properties.Update();            

site.Title = “HELLO WORLD”;           

site.Update();               

}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)       

{           

SPWeb site = (SPWeb)properties.Feature.Parent;           

site.Title = site.Properties[“OriginalTitle”];           

site.Update();       

} 

public override void FeatureInstalled(SPFeatureReceiverProperties properties)       

{

} 

public override void FeatureUninstalling(SPFeatureReceiverProperties properties)        

{                   

}   

}

} 

We have inherited form the class SPFeatureReceiver and override four methods which are FeatureActivated, FeatureDeactivating, FeatureInstalled and FeatureUninstalling. FeatureActivated will fire after a feature is activated and FeatureDeactivating will fire before a feature is deactivated. 

In FeatureActivated method, we did a simple trick. We store site name using persistent property bag and replace it with “HELLO WORLD” title. When the feature is deactivated, the original title of the site is restored. 

Now it’s time to deploy the assembly. First we sign the assembly. (if you don’t know how to sign, click here). The next step is to deploy the assembly into GAC. We can do that by moving to the properties of the project and then to “Build Events” tab. “Post build event command line window:” text box will already have following lines: 

cd $(ProjectDir)

Install.bat 

(For details, check this post) 

Add the following lines in the beginning. 

“%programfiles%\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe” /if $ “(TargetPath)” 

The last step is to add the reference in the “feature.xml” file. The updated look of the file is: 

<Feature 

Id=“” 

Title=HELLO WORLD FEATURE 

Description=This is my very first custom feature 

Version=1.0.0.0  

Scope=Web 

Hidden=FALSE 

ImageUrl=menuprofile.gif 

ReceiverAssembly=HelloWorldFea, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9136ecc8446e96dc  ReceiverClass=HelloWorldFea.FeatureReceiver  

xmlns=http://schemas.microsoft.com/sharepoint/>   

<ElementManifests>   

<ElementManifest Location=elements.xml /> 

</ElementManifests>

</Feature> 

If you don’t have the idea about the ReceiverAssembly / ReceiverClass element, click here).  Activate and deactivate the feature to test the working of the event handler. If not working, try doing the things manually.

 

Comments (2)

Creating & Adding an Event Handler

In this document, we will create an event handler that captures the events of the document library and add an entry in the cell of the document added. We can add an event handler using code or as a feature. In order to write an event handler, we will first create a sharepoint site and create a document library. We will, then, capture the events of the document library.   

b1-1

1         Writing an Event Handler

We will start from the Visual Studio 2005 new project window. In the new project window, select C# Window application, then, class library as encircled in the figure below and name the project “DocLibEventHandler”.

2.jpg

1.1    Adding Reference

The first thing we will do in the class library is to add reference of the name space Microsoft.SharePoint. This is done by right clicking on the References link in the solution explorer and then clicking on “Add Reference…” as encircled in the following figure:  

3.jpg

Clicking on add reference will generate a new pop up window Add Reference. We will select the Windows® SharePoint® Services namespace, as encircled in the figure below, and click on OK. It will add the Windows® SharePoint® Services namespace in our project.

  

4.jpg

We will add the names spaces, encircled red in the figure below, in our project so that we can directly use the classes in that namespace without specifying the complete path.

5.jpg

 

1.2   Changing Class Name

We will again go to the solution explorer and change the name our class from “Class1” to “DocLibEventHandlerClass”. This can be done by clicking on the class name in the solution explorer and right click on the class name. This will open a new window from which we will select Rename and change the class name from “Class1” to “DocLibEventHandlerClass”. As you change the name of the class, a prompt will appear, shown in the figure below, and ask would you like to rename all references to the code element “Class1”? Click on “Yes”

6.jpg

1.3   Inheriting Class

We will inherit our class from the class SPItemEventReceiver. The path to the class SPItemEventReceiver is Microsoft.SharePoint.SPItemeventReceiver. We have already added the namespace Microsoft.SharePoint, therefore, we just writet the name of the class SPItemEventReceiver for inheritance as shown in the figure below:    

5.jpg  

1.4   Capturing Events

 MOSS provides two types of events namely, synchronous and asynchronous. The “…ing” event occurs before the action starts and the “…ed” occurs after the actions ends. “…ing” events occur synchronously while the “…ed” events occur asynchronously.   

8.jpg 

Synchronous events

  • Occur before the event.
  • Block the flow of code execution until your event handler completes.
  • Provide you with the ability to cancel the events resulting in no after event (“…ed”) being fired.

Asynchronous events:

  • Occur after the event.
  • Do not block the flow of code execution in SharePoint

 To capture these events, class SPItemEventReceiver provides different methods, as shown in the right side of the above figure, which can be seen through Object Browser by pressing Alt+Ctrl+j to see the list of the methods by browsing through Microsoft.SharePoint to SPItemEventReceiver.  We will create a simple program for demonstration purpose. The code will override methods ItemAdding, ItemAdded, ItemUpdated and ItemUpdating in the class SPItemEventReceiver.  

1.5   The Code

 The code will run when a new file is added in the document library and also when an existing document is updated. It will add an entry in the list “CEO Docs Access Log” describing the nature of the event and date on which event occurred. The code is as under: 

namespace DocLibEventHandler

{   

public class DocLibEventHandlerClass : SPItemEventReceiver   

{

public override void ItemAdded(SPItemEventProperties properties)       

{           

SPListItem doc = properties.ListItem;

doc[“Comments”] = “Document has been added”;

doc.Update();

}

//you can use following methods as well        

public override void ItemAdding(SPItemEventProperties properties)        {        }        

public override void ItemUpdated(SPItemEventProperties properties)        {        }        

public override void ItemUpdating(SPItemEventProperties properties)        {        } 

} 

1.6   Signing the Assembly

 The next step is of signing the assembly. To do this, you have to move to the properties window of the project. To do this, right click on the project name “DocLibEventHandler” in the solution explorer and click on the properties in the popup menu. This will open the properties window, select the Signing Pane of the properties window and check the “Sign the Assembly” option. Select <New…> from the “Choose a strong name key file:” and give the name that you desired. In our case, we named it “DocLibeventAssembly” as shown in the figure below:  

9.jpg

1.6   Build Project

 We will build by pressing F6 or clicking on Build in the tolls menu and then clicking on Build Solution. Build will generate the file “DocLibEventHandler.dll” in the debug directory.  

1.7   Copying into GAC

 The file DocLibeventHandler.dll can be found in the debug folder whose path is C:\…..\Visual Studio 2005\DocLibEventHandler\DocLibEventHandler\bin\Debug. Depending upon your installation, you can find the file in the debug folder. Copy the file “DocLibeventHandler.dll” from this folder and paste it in the GAC folder which is normally found at C:\WINDOWS\assembly. After copying the file in the GAC, copy the public token key as encircled in the figure below:  

10.jpg

There are many other ways of adding assembly in GAC. 

1.8   Registering the Event Handler

 In order to register the event handler, add a new console project in the solution by right clicking on the solution “DocLibEventHandler” in the solution explorer as shown in the figure below:  

11.jpg

Select a console project in the “Add New Project” window and name it “DocLibRegApp” as shown in the figure below:  

2.jpg

 Add the following code in the main method. 

namespace DocLinRegApp{   

class Program    {       

static void Main(string[] args)        {           

SPSite sp = new SPSite(http://servername&#8221;);           

SPWeb website = sp.OpenWeb();           

SPList DocLib = website.Lists[“DLOne”];            

string assm = “DocLibEventHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1d6b41a3ed9a92cb”;           

string class = “DocLibEventHandler.DocLibEventHandlerClass”;            

DocLib.EventReceivers.Add(SPEventReceiverType.ItemAdded, assm, class);           

DocLib.EventReceivers.Add(SPEventReceiverType.ItemAdding, assm, class);           

DocLib.EventReceivers.Add(SPEventReceiverType.ItemUpdating, assm, class);            DocLib.EventReceivers.Add(SPEventReceiverType.ItemUpdated, assm, class);       

}   

}

} 

The string assm describes the assembly details that we have added in the GAC and class is the name of our class. Press F5 to run the project. 

1.9   Changes in the Document Library

Open the site and add document in the document library. Comments column will have the value “Document has been added” as shown in the figure below:

13.jpg

Comments (78)