Sunday, December 2, 2012

Programmatically how to create custom role and assign the role to a group

Create Custom Role with Custom permissions and assign role to group:

In this example i wanna create custom role with custom permission and assign that role to a group.

            using (SPSite site = new SPSite("http://UKREDDY:6969/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPRoleDefinition network_role = new SPRoleDefinition();
                    network_role.BasePermissions = SPBasePermissions.AddListItems |
                        SPBasePermissions.BrowseDirectories |
                        SPBasePermissions.EditListItems |
                        SPBasePermissions.DeleteListItems;
                    network_role.Name = "CustomRole";
                    network_role.Description = "Provides permissions required for a member of a project.";

                    web.RoleDefinitions.Add(network_role);
                    // you can't just return definition because SharePoint gives you
                    //    "You cannot grant a user a permission level that is not
                    //    attached to a web" when you attempt to use it, so
                    //    you need to return it again
                    SPRoleDefinition newlyaddedef = web.RoleDefinitions["CustomRole"];
                    SPRoleAssignment assign = new SPRoleAssignment(web.SiteGroups["UdayGroup"]);
                    assign.RoleDefinitionBindings.Add(newlyaddedef);
                    web.RoleAssignments.Add(assign);
                    web.Update();
                }
            }





Delete custom role definition:


            using (SPSite site = new SPSite("http://UKREDDY:6969/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.RoleDefinitions.Delete("CustomRole");
                }
            }

2 comments: