Category Archives: Workflow

Things to look for when setting Item Level Permission with List Event Handler

One of the key benefits of using SharePoint list as primary means of data storage is the OOB feature to be able to set Item Level Permission. Setting Item Level Permissions or can either be done with the GUI or with some custom code. In case of Custom Code, it can be either done with List Event Handler or with a Workflow. What this article is focusing on is use of Event Handler to Set/Update Item Level Permission.

  1. First thing to be remembered is that the SPListItem you get from SPItemEventProperties object which received with the Event Hander argument is initialized to the user context of whom the event originated. This is especially important if you are having few custom permission levels or user roles, so that user who is originating list event may not always have required rights to perform some of the actions such as add/update item level permission.  So it is recommended that you reinitialize the SPListItem on which you are going to work on for Item Level Permission with an Elevated Privileged context.
    public override void ItemAdded(SPItemEventProperties properties){
     EventFiringEnabled = false;
     SPListItem currentItem = properties.ListItem;
     SPSecurity.RunWithElevatedPrivileges(delegate {
    using (SPSite elevatedSite = new SPSite(properties.ListItem.Web.Site.ID))
           using (SPWeb elevatedWeb = levatedSite.OpenWeb(properties.ListItem.Web.ID))
             SPList elevatedList = elevatedWeb.Lists[currentItem.ParentList.ID];
             SPListItem elevatedListItem = elevatedList.GetItemById(currentItem.ID);

    If you don’t do that it is more likely that you may experience following errors.

    UnauthorizedAccessException: <nativehr>0x80070005</nativehr><nativestack></nativestack>  
    at Microsoft.SharePoint.Library.SPRequest.AddOrUpdateItem(String bstrUrl, String bstrListName, Boolean bAdd, Boolean bSystemUpdate, Boolean bPreserveItemVersion, Boolean bUpdateNoVersion, Int32& plID, String& pbstrGuid, Guid pbstrNewDocId, Boolean bHasNewDocId, String bstrVersion, Object& pvarAttachmentNames, Object& pvarAttachmentContents, Object& pvarProperties, Boolean bCheckOut, Boolean bCheckin, Boolean bMigration, Boolean bPublish, String bstrFileName, ISP2DSafeArrayWriter pListDataValidationCallback, ISP2DSafeArrayWriter pRestrictInsertCallback, ISP2DSafeArrayWriter pUniqueFieldCallback)
  2. Then let us take a look some of the common steps we follow to set Item Level Permission.
    1. Break Role Assignment Inheritance
    2. Remove all the role assignments
    3. Add any User/Group Assignments

    First two steps of the above can written as follow,

    foreach (SPRoleAssignment assignment in listItem.RoleAssignments)

    In this case I am using “listItem.BreakRoleInheritance(false)” so that the collection of role assignments contain only 1 role assignment containing the current user after the operation. Some thing to remember with this is that this is very resource intensive operation as it will break all role assignments and delete user/group security assignment one by one.  This will take considerable time if the number of security assignment(either of groups or users) of the parent sharepoint object( in this case the Site).  In my case I had about 2000 users associated with the site, which made considerable delays.

    Then the other segment to remove all the RoleDefinitions assigned to the Item.

    One of the interesting scenario that I observed is that if you use this piece of code in high volumes, there is high chance of you code getting failed.  In my case I even had try/catch block wrapping the code segment, but I hardly had any exceptions caught by the catch statement, but the ULS log had following stack

    at Microsoft.SharePoint.Utilities.SqlSession.OnPostExecuteCommand(SqlCommand command, SqlQueryData monitoringData) 
    at Microsoft.SharePoint.Utilities.SqlSession.ExecuteReader(SqlCommand command, CommandBehavior behavior, SqlQueryData monitoringData, Boolean retryForDeadLock) 
    at Microsoft.SharePoint.SPSqlClient.ExecuteQueryInternal(Boolean retryfordeadlock) at Microsoft.SharePoint.SPSqlClient.ExecuteQuery(Boolean retryfordeadlock) 
    at Microsoft.SharePoint.Library.SPRequestInternalClass.UpdateMembers(String bstrUrl, UInt32 dwObjectType, String bstrObjId, Guid& pguidScopeId, Int32 lGroupID, Int32 lGroupOwnerId, Object& pvarArrayAdd, Object& pvarArrayAddIds, Object& pvarArrayLoginsRemove, Object& pvarArrayIdsRemove, Boolean bRemoveFromCurrentScopeOnly, Boolean bSendEmail) at Microsoft.SharePoint.Library.SPRequest.UpdateMembers(String bstrUrl, UInt32 dwObjectType, String bstrObjId, Guid& pguidScopeId, Int32 lGroupID, Int32 lGroupOwnerId, Object& pvarArrayAdd, Object& pvarArrayAddIds, Object& pvarArrayLoginsRemove, Object& pvarArrayIdsRemove, Boolean bRemoveFromCurrentScopeOnly, Boolean bSendEmail) 
    at Microsoft.SharePoint.SPRoleAssignmentCollection.RemoveMembers(Int32[] IdsToRemove, Int32 roleId, Boolean removeFromCurrentScopeOnly) at Microsoft.SharePoint.SPRoleAssignmentCollection.Remove(Int32 index)

    What I realized from that stack trace is the operation have being aborted from the SQL Server operation it self.  So few hours of googling made me aware this is happening because of an XACT abort resulting from the stored procedure. And this is happening since multiple threads trying this operation. I saw some are suggesting to run a command to ignore abort. However since MS is not recommending to touch SQL db, I went the other option of solution to have a lock on the code segment. In that way I ensure the code segment is owned by single thread and have an exclusive lock until it completes. That solved my issue. so my looked like,

    lock (removePermissionLock)
          foreach (SPRoleAssignment assignment in listItem.RoleAssignments)
  3. Use of same SPListItem initialized with the Elevated Privileges to Break Inheritance and Add new user/group assignments. If you happen to associate/or start Workflow, use the same SPListItem object to avoid any Save Conflicts. In my case I had three different SPListItem initialized for Break Inheretance, Add new user/group assignements and Start the Workflow. That made my workflow code to fail stating the Save Conflict. Weirdly the workflow produced the Conflict error after some operations on the workflow code on immediately at the time of start of workflow on the Event Handler it self. The error logged in was happen to be,
     Save Conflict. Your changes conflict with those made concurrently by another user. If you want your changes to be applied, click Back in your Web browser, refresh the page, and resubmit your changes.0x81020015

Getting SP Custom Workflow TaskProperties.SendEmailNotification to send Emails

If you want SharePoint Custom workflow to send emails on task creation, what you need is set SendEmailNotification  to true on the task creation activity.

However if you are using out-of-the-box “Workflow Task” list for workflow tasks, this may not work right away as you expect.  The tick to get this to work is set  “Send e-mail when ownership is assigned” to “Yes” on the Task list properties.

That can be by,

  1. Navigate to Workflow Task List Settings.
  2. Access the  “Advanced Settings”
  3. Set “Send e-mail when ownership is assigned” to “Yes”
If you are using a custom list  for workflow tasks set  EmailAssignTo=”TRUE” on the schema.xml.
<List xmlns:ows=”Microsoft SharePoint”
      Title="Workflow Tasks"
      Type="107" BaseType="