Monday, November 3, 2008

Set item readonly programmatically

In my custom workflow, I had an requirement to set list item to be read only once workflow steps complete. Here is the code I have written to accomplished that.

public SPWorkflowActivationProperties WorkflowProperties = new Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties();

private void SetItemReadOnly(object sender, EventArgs e)
{
string rolename = "View Only";
SPListItem item = WorkflowProperties.Item;
item.BreakRoleInheritance(true);
SPRoleDefinition roldef = WorkflowProperties.Web.RoleDefinitions[rolename];
foreach (SPRoleAssignment roleAssignment in item.RoleAssignments)
{
roleAssignment.RoleDefinitionBindings.RemoveAll();
roleAssignment.RoleDefinitionBindings.Add(roldef);
roleAssignment.Update();
item.Update();
}
}


I have taken OOB role "View only". You can creat custom role and add to roleassignment.
For non workflow, I would suggest to replace below line with
SPListItem item = WorkflowProperties.Item;

-- replaced line
SPSite portalSite = new SPSite("http://litwareserver");
SPWeb web = portalSite.OpenWeb();

SPList splst = web.Lists[""];
SPListItem item = splst.Items[0]; // this code for first item, you can select for other item of list.

and replace this also
SPRoleDefinition roldef = WorkflowProperties.Web.RoleDefinitions[rolename];

-- replaced line
SPRoleDefinition roldef = web.RoleDefinitions[rolename]; // "web" instance already defined in aboove code.

Let me know if need more clarification on this.
bibhuti.nilesh@gmail.com