{Dynamics CRM} Programatically Assign privilege to security role for an entity in MSCRM

Recently in my project, I had a requirement where I needed to assign security privilege to all the roles in the system to a custom entity Programatically. Let’s see how we can achieve the same.

Whenever a custom entity is added in CRM, CRM internally created eight privilige records for the entity for the privileges – Read, Create, Write, Assign, Delete, Append, AppendTo and Share

The name of the privilege records create would be in the format of prv<privilege><entitylogicalname>. So if the logical name of the entity is crmtr_testentity1  then for create privilege, the privilege name in CRM for Create would be prvCreatecrmtr_testentity1. The code below would fetch all the privileges for the entity crmtr_testentity1.

var orgService = GetOrganizationService();
var query = new QueryExpression(“privilege”);
query.ColumnSet = new ColumnSet(true);
query.Criteria.AddCondition(new ConditionExpression(“name”, ConditionOperator.Like, “%crmtr_testentity1%”));
var collection = orgService.RetrieveMultiple(query);

You need to implement the method GetOrganizationService() which would return the OrganizationServiceProxy instance.

Lets see what is returns. In the screenshot below, I have attached the results that I can view in debugger

Image1

As you could see, all the eight privileges for this record has been returned.

Now for demo purpose let us give Marketing Manager security role User level create and business unit level for Write privilege. The code below does the same.

foreach (var prv in collection.Entities)
{
switch ((string)prv[“name”])
{
case “prvCreatecrmtr_testentity1”:
{
AddPrivilegesRoleRequest req = new AddPrivilegesRoleRequest
{
RoleId = new Guid(“1A7F9E89-8283-E311-8E04-463500000031”),
Privileges = new[]
{
new RolePrivilege
{
Depth = PrivilegeDepth.Basic,
PrivilegeId = prv.Id
}
}
};
break;
}

case “prvWritecrmtr_testentity1”:
{
AddPrivilegesRoleRequest req = new AddPrivilegesRoleRequest
{
RoleId = new Guid(“1A7F9E89-8283-E311-8E04-463500000031”),
Privileges = new[]
{
new RolePrivilege
{
Depth = PrivilegeDepth.Local,
PrivilegeId = prv.Id
}
}
};
break;
}
}

}

1A7F9E89-8283-E311-8E04-463500000031 is the Guid of the marketing manager role. Looking at the code we find that we are using the AddPrivilegesRoleRequest to do the same. The code is pretty simple and self expalnatory. The access level is provided by the PrivilegeDepth enumeration.

Once the code oi executed we now have User level create and Business Unit level write on the Test Entity 1 for the Marketing Manager security role.

Image2

Hope this helps!

Advertisements