Sunday, June 5, 2016

Event Receivers

Definition of Event Receiver?
A class with method respond to events. They are two types of event receivers.

Types of Events
Synchronous events occurs before an action has taken place. Example: Item Adding
These events can be can canceled.
Before = Synchronous

Asynchronous events occurs after an action has taken place. Example: Item Added.
These events cant be can canceled.
After =  Asychronous

Event receivers can be created for 
  • List items
  • Lists
  • Webs
  • Sites
  • Workflows
Event Receiver Classes
  • SPItemEventReceiver
  • SPListEventReceiver
  • SPWebEventReceiver
  • SPWorkflowEventReceiver
Creating Event Receiver with Visual Studio:
  • Fire-up the visual studio and crate an SharePoint empty project.
  • For the new project I will be adding Event Receiver by right clicking on the project and add new item.
  • In the new dialog window select the event receiver item and name it appropriately.
  •  In the SharePoint customization wizard. In the first drop down for the type of event receiver I am selecting list item events. In the 2nd drop down you need to select the list. In the 3rd drop down you need to select the what kind of events you are going to associate. for example Item adding & itemupdated.
  • Optionally you can rename the feature name and description in VS solution.
  • In below example I had three event receivers, item added, item updating, item  updated.
 [code]]using System;  
 using System.Security.Permissions;  
 using Microsoft.SharePoint;  
 using Microsoft.SharePoint.Security;  
 using Microsoft.SharePoint.Utilities;  
 using Microsoft.SharePoint.Workflow;  
 using System.Diagnostics;  
 namespace ComplianceCalendar.CalendarEventReceiver  
 {  
   /// <summary>  
   /// List Item Events  
   /// </summary>  
   public class CalendarEventReceiver : SPItemEventReceiver  
   {  
     int numberOfOccurences = 0;  
     string recurrence = string.Empty;  
     string filingType = string.Empty;  
     int lastOccurence;  
     #region ItemAdded  
     /// <summary>  
     /// When a new filing is added  
     /// </summary>  
     public override void ItemAdded(SPItemEventProperties properties)  
     {  
       SPSecurity.RunWithElevatedPrivileges(delegate()  
       {  
         //base.ItemAdded(properties);  
         try  
         {  
           using (SPWeb web = properties.OpenWeb())  
           {  
             SPListItem itm = properties.ListItem;  
             recurrence = itm["Recurrence"].ToString();  
             filingType = itm["Filing_x0020_Type"].ToString();             
             if (itm["Number_x0020_of_x0020_Occurences"]!=null)numberOfOccurences = int.Parse(itm["Number_x0020_of_x0020_Occurences"].ToString());  
             //setting last occurence to 1 if number of occurences was set to 1 as this will be the final item of series  
             if (numberOfOccurences == 1)  
             {  
               this.EventFiringEnabled = false;  
               itm["LastOccurrence"] = 1;  
               itm["Number_x0020_of_x0020_Occurences"] = 0;  
               itm.SystemUpdate(false);  
               this.EventFiringEnabled = true;  
             }  
             SPList list = web.Lists.TryGetList("Regulatory Filings Calendar");  
             if (list != null)  
             {  
               if (recurrence == "True" && filingType!= "Ad Hoc" && filingType!=string.Empty)  
               {  
                 this.EventFiringEnabled = false;  
                 for (int i = 1; i <= numberOfOccurences - 1; i++)  
                 {  
                   SPListItem NewItem = list.Items.Add();  
                   {                                        
                     NewItem["Title"] = itm["Title"];  
                     if (itm["TypeField"] != null) NewItem["TypeField"] = itm["TypeField"];  
                     if (itm["Regulatory_x0020_Entity"] != null) NewItem["Regulatory_x0020_Entity"] = itm["Regulatory_x0020_Entity"];  
                     if (itm["Regulatory_x0020_Filing"] != null) NewItem["Regulatory_x0020_Filing"] = itm["Regulatory_x0020_Filing"];                                         
                     if (itm["Description"] != null) NewItem["Description"] = itm["Description"];  
                     if (itm["Recurrence"] != null) NewItem["Recurrence"] = itm["Recurrence"];  
                     if (itm["Filing_x0020_Type"] != null) NewItem["Filing_x0020_Type"] = itm["Filing_x0020_Type"];                     
                     if (itm["Due_x0020_Date_x0020_Description"] != null) NewItem["Due_x0020_Date_x0020_Description"] = itm["Due_x0020_Date_x0020_Description"];  
                     if (itm["FilingLocationsInstructions"] != null) NewItem["FilingLocationsInstructions"] = itm["FilingLocationsInstructions"];  
                     if (itm["Status"] != null) NewItem["Status"] = itm["Status"];  
                     if (itm["Number_x0020_of_x0020_Occurences"] != null) NewItem["Number_x0020_of_x0020_Occurences"] = itm["Number_x0020_of_x0020_Occurences"];  
                     if (itm["Responsible_x0020_Parties"] != null) NewItem["Responsible_x0020_Parties"] = itm["Responsible_x0020_Parties"];  
                     if (itm["ResponsiblePartiesManager"] != null) NewItem["ResponsiblePartiesManager"] = itm["ResponsiblePartiesManager"];                     
                     if (itm["ComplianceManager"] != null) NewItem["ComplianceManager"] = itm["ComplianceManager"];  
                     if (itm["Submitter"] != null) NewItem["Submitter"] = itm["Submitter"];  
                     if (itm["CorrespondingProcedures"] != null) NewItem["CorrespondingProcedures"] = itm["CorrespondingProcedures"];  
                     if (itm["Name_x0020_of_x0020_Procedures"] != null) NewItem["Name_x0020_of_x0020_Procedures"] = itm["Name_x0020_of_x0020_Procedures"];  
                     if (itm["Evidence"] != null) NewItem["Evidence"] = itm["Evidence"];  
                     if (itm["Comments"] != null) NewItem["Comments"] = itm["Comments"];  
                     //check of last occurence and update the field  
                     if (i == numberOfOccurences - 1)  
                     {  
                       NewItem["LastOccurrence"] = 1;  
                       NewItem["Number_x0020_of_x0020_Occurences"] = 0;  
                     }  
                     else  
                     {  
                       NewItem["LastOccurrence"] = 0;  
                     }  
                     DateTime _dttm = Convert.ToDateTime(itm["Filing Due Date"].ToString());                     
                     if (filingType == "Monthly")  
                     {  
                       NewItem["Filing_x0020_Due_x0020_Date"] = _dttm.AddMonths(i);  
                     }  
                     else if (filingType == "Quarterly")  
                     {  
                       NewItem["Filing_x0020_Due_x0020_Date"] = _dttm.AddMonths(3 * i);  
                     }  
                     if (filingType == "Semi-annual")  
                     {  
                       NewItem["Filing_x0020_Due_x0020_Date"] = _dttm.AddMonths(6 * i);  
                     }  
                     else if (filingType == "Yearly")  
                     {  
                       NewItem["Filing_x0020_Due_x0020_Date"] = _dttm.AddYears(i);  
                     }  
                     NewItem.Update();                     
                   }  
                 }  
               }  
             }  
           }  
         }  
         catch (Exception ex)  
         {  
           EventLog.WriteEntry("Regulatory Calendar Error", "ItemAdded\r\n" + ex.Message, EventLogEntryType.Error);  
         }  
         finally  
         {  
           this.EventFiringEnabled = true;            
         }  
       });  
     }  
     #endregion  
     #region ItemUpdated  
     /// <summary>  
     /// An item was updated  
     /// </summary>  
     public override void ItemUpdated(SPItemEventProperties properties)  
     {  
       SPSecurity.RunWithElevatedPrivileges(delegate()  
       {  
         //base.ItemUpdated(properties);        
         try  
         {  
           using (SPWeb web = properties.OpenWeb())  
           {  
             SPListItem itm = properties.ListItem;  
             recurrence = itm["Recurrence"].ToString();  
             filingType = itm["Filing_x0020_Type"].ToString();  
             lastOccurence = Convert.ToInt32(itm["LastOccurrence"]);  
             numberOfOccurences = int.Parse(itm["Number_x0020_of_x0020_Occurences"].ToString());  
             SPList list = web.Lists.TryGetList("Regulatory Filings Calendar");  
             if (list != null && lastOccurence == 1)  
             {                
               if (recurrence == "True" && numberOfOccurences > 0)  
               {  
                 //Make the current item Last Occurence to 0  
                 this.EventFiringEnabled = false;  
                 itm["LastOccurrence"] = 0;  
                 itm.SystemUpdate(false);  
                 for (int i = 1; i <= numberOfOccurences; i++)  
                 {  
                   SPListItem NewItem = list.Items.Add();  
                   {                  
                     NewItem["Title"] = itm["Title"];  
                     if (itm["TypeField"] != null) NewItem["TypeField"] = itm["TypeField"];  
                     if (itm["Regulatory_x0020_Entity"] != null) NewItem["Regulatory_x0020_Entity"] = itm["Regulatory_x0020_Entity"];  
                     if (itm["Regulatory_x0020_Filing"] != null) NewItem["Regulatory_x0020_Filing"] = itm["Regulatory_x0020_Filing"];  
                     if (itm["Description"] != null) NewItem["Description"] = itm["Description"];  
                     if (itm["Recurrence"] != null) NewItem["Recurrence"] = itm["Recurrence"];  
                     if (itm["Filing_x0020_Type"] != null) NewItem["Filing_x0020_Type"] = itm["Filing_x0020_Type"];  
                     if (itm["Due_x0020_Date_x0020_Description"] != null) NewItem["Due_x0020_Date_x0020_Description"] = itm["Due_x0020_Date_x0020_Description"];  
                     if (itm["FilingLocationsInstructions"] != null) NewItem["FilingLocationsInstructions"] = itm["FilingLocationsInstructions"];                      
                     if (itm["Number_x0020_of_x0020_Occurences"] != null) NewItem["Number_x0020_of_x0020_Occurences"] = itm["Number_x0020_of_x0020_Occurences"];  
                     if (itm["Responsible_x0020_Parties"] != null) NewItem["Responsible_x0020_Parties"] = itm["Responsible_x0020_Parties"];  
                     if (itm["ResponsiblePartiesManager"] != null) NewItem["ResponsiblePartiesManager"] = itm["ResponsiblePartiesManager"];  
                     if (itm["ComplianceManager"] != null) NewItem["ComplianceManager"] = itm["ComplianceManager"];  
                     if (itm["Submitter"] != null) NewItem["Submitter"] = itm["Submitter"];  
                     if (itm["CorrespondingProcedures"] != null) NewItem["CorrespondingProcedures"] = itm["CorrespondingProcedures"];  
                     if (itm["Name_x0020_of_x0020_Procedures"] != null) NewItem["Name_x0020_of_x0020_Procedures"] = itm["Name_x0020_of_x0020_Procedures"];  
                     if (itm["Evidence"] != null) NewItem["Evidence"] = itm["Evidence"];  
                     if (itm["Comments"] != null) NewItem["Comments"] = itm["Comments"];  
                     //check of last occurence and update the field  
                     if (i == numberOfOccurences)  
                     {  
                       NewItem["LastOccurrence"] = 1;  
                       NewItem["Number_x0020_of_x0020_Occurences"] = 0;  
                     }  
                     else  
                     {  
                       NewItem["LastOccurrence"] = 0;  
                     }  
                     DateTime _dttm = Convert.ToDateTime(itm["Filing Due Date"].ToString());                      
                     if (filingType == "Monthly")  
                     {  
                       NewItem["Filing_x0020_Due_x0020_Date"] = _dttm.AddMonths(i);  
                     }  
                     else if (filingType == "Quarterly")  
                     {  
                       NewItem["Filing_x0020_Due_x0020_Date"] = _dttm.AddMonths(3 * i);  
                     }  
                     if (filingType == "Semi-annual")  
                     {  
                       NewItem["Filing_x0020_Due_x0020_Date"] = _dttm.AddMonths(6 * i);  
                     }  
                     else if (filingType == "Yearly")  
                     {  
                       NewItem["Filing_x0020_Due_x0020_Date"] = _dttm.AddYears(i);  
                     }  
                     NewItem.Update();                      
                   }  
                 }                  
               }  
             }  
           }  
         }  
         catch (Exception ex)  
         {  
           EventLog.WriteEntry("Regulatory Calendar Error", "ItemUpdated\r\n" + ex.Message, EventLogEntryType.Error);  
         }  
         finally  
         {  
           this.EventFiringEnabled = true;  
         }  
       });  
     }  
     #endregion  
     #region ItemUpdating  
     //Commented code ignore  
     /// <summary>  
     /// An item is being updated  
     /// </summary>  
     //public override void ItemUpdating(SPItemEventProperties properties)  
     //{  
     //  //base.ItemUpdating(properties);  
     //  try  
     //  {  
     //    //SPListItem itm = properties.ListItem;  
     //    //recurrence = itm["Recurrence"].ToString();  
     //    //filingType = itm["Filing_x0020_Type"].ToString();  
     //    //beforeNoOfOccurences = Convert.ToInt32(properties.ListItem["Number_x0020_of_x0020_Occurences"]);  
     //    //afterNoOfOccurences = Convert.ToInt32(properties.AfterProperties["Number_x0020_of_x0020_Occurences"]);  
     //    //properties.AfterProperties["hdnOccurences"] = beforeNoOfOccurences;  
     //    //properties.AfterProperties["LastOccurrence"] = 0;  
     //  }  
     //  catch (Exception ex)  
     //  {  
     //    EventLog.WriteEntry("Regulatory Calendar Error", "ItemUpdating\r\n" + ex.Message, EventLogEntryType.Error);  
     //  }  
     //  finally  
     //  {  
     //    this.EnableEventFiring();  
     //  }  
     //}  
     #endregion  
   }  
 }[/code]  

No comments:

Post a Comment