Sample code to set permission using EventHandler when ItemAdded.
1: using System;
2: using System.Collections.Generic;
3: using System.Text;
4: using Microsoft.SharePoint;
5:
6: namespace EventHandler
7: {
8: public class SetPermissionItemEventReceiver : SPItemEventReceiver
9: {
10: public override void ItemAdded(SPItemEventProperties properties)
11: {
12: SetPermission(properties);
13: }
14:
15: private void SetPermission(SPItemEventProperties properties)
16: {
17: string LoginName = properties.UserLoginName;
18: SPSecurity.RunWithElevatedPrivileges(delegate()
19: {
20: using (SPSite site = new SPSite(properties.SiteId))
21: {
22: using (SPWeb web = site.OpenWeb(properties.RelativeWebUrl))
23: {
24: this.DisableEventFiring();
25:
26: SPListItem item = web.Lists[properties.ListId].GetItemById(properties.ListItemId);
27:
28: string ListName = item.ListItems.List.RootFolder.Name;
29:
30: if (!item.HasUniqueRoleAssignments)
31: item.BreakRoleInheritance(false);
32:
33: SPRoleDefinition ContributeRoleDefinition =
item.Web.RoleDefinitions["Contribute"];
34: SPRoleDefinition ApproveRoleDefinition =
item.Web.RoleDefinitions["Approve"];
35: SPRoleDefinition FullControlRoleDefinition =
item.Web.RoleDefinitions["Full Control"];
36:
37: SPRoleAssignment UserRoleAssignment = new SPRoleAssignment(LoginName,
string.Empty, string.Empty, string.Empty);
38: UserRoleAssignment.RoleDefinitionBindings.Add(ContributeRoleDefinition);
39: item.RoleAssignments.Add(UserRoleAssignment);
40:
41: SPGroup OwnerGroup = item.Web.SiteGroups["Owners"];
42: SPRoleAssignment OwnerRoleAssignment = new SPRoleAssignment(OwnerGroup);
43: OwnerRoleAssignment.RoleDefinitionBindings.Add(FullControlRoleDefinition);
44: item.RoleAssignments.Add(OwnerRoleAssignment);
45:
46: SPGroup ApproversGroup = item.Web.SiteGroups[
string.Format("{0}_Approvers", ListName)];
47: SPRoleAssignment ApproversRoleAssignment = new SPRoleAssignment(ApproversGroup);
48: ApproversRoleAssignment.RoleDefinitionBindings.Add(ApproveRoleDefinition);
49: item.RoleAssignments.Add(ApproversRoleAssignment);
50:
51: this.EnableEventFiring();
52: }
53: }
54: });
55: }
56: }
57: }