Create Role Permission Dynamically

First Create SPSite and  SPWeb (web Object), assuming it is already created…

Now creating Permission Object
Assuming you have comma separated Permission for which you want to
create Role

string Perm = “AddListItems,EditListItems,ManageLists”;

Next thing is to convert the permissions in the form of string to SPBasePermissions

SPBasePermissions BP = (SPBasePermissions)Enum.Parse(typeof(SPBasePermissions),Perm.TrimEnd(‘,’), true);

SPRoleDefinition def = new SPRoleDefinition();
def.Description = “MKS Role for ” + roleName;
def.BasePermissions =  BP;
def.Name = roleName;
web.FirstUniqueRoleDefinitionWeb.RoleDefinitions.Add(def);
web.FirstUniqueRoleDefinitionWeb.Update();
web.FirstUniqueRoleDefinitionWeb.Dispose();
web = web.Site.OpenWeb();

In order to update RoleDefinition

SPRoleDefinition def = web.RoleDefinitions[roleName];
def.BasePermissions = BP;
def.Description = “MKS Roles for  ” + roleName;
def.Update();
web.Update();


To Check duplicate Role

//XML of the roledefinitions
XmlDocument doc = new XmlDocument();
doc.LoadXml(web.RoleDefinitions.Xml);

XmlNode node = doc.SelectSingleNode(“//Role[@Name='” + roleName + “‘]”);
//if the search returned null, the role does not exist
if (node == null)
return false;
else
return true;

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s