How to run Code with elevated privileges

I had to create 2 calendars , first one is shared and located on the Root site and the other is personnal and located on the mySite.
The content type contains one field  AssignedTo . when the event is inserted in the Shared Calendar , it must also be add to the personal calendar of the User in the AssignedTo field.
The user who added the event has no rights on the Personal Calendar of the User in the AssignedTo field.
So the solution was to run the code with elevated privileges.

To do such a thing just user the SPSecurity.RunWithElevatedPrivilges

SPSecurity.RunWithElevatedPrivileges(delegate()
  {


you need to open the site,web and list inside the RunWithElevatedPrivileges. 


SPListItem newitem = list.Items.Add();
                                                                             newitem["ContentTypeId"] =
                                                                                 properties.ListItem["ContentTypeId"];
newitem["Title"] = properties.ListItem["Title"];
newitem["Location"] = properties.ListItem["Location"]; 
newitem["EventDate"] =properties.ListItem["EventDate"];
newitem["EndDate"] = properties.ListItem["EndDate"];  
newitem.Update();
} );


Enregistrer un commentaire