Loading...

Assign Privileges to a Security Role by code C#

Assign Privileges to a Security Role by code C#
Assign Privileges to a Security Role by code C# Lloyd Sebag Mon, 03/11/2024 - 15:55
Body

If for any reason you need to assign a specific Privileges to a Security Role, you can use this code : 

// The ID of the role without the privileges
Guid RoleId = new Guid("7ad78e66-a4df-ee11-904c-000d3a8312b6");

// The privileges to add to the role
string[] privileges = { "prvAllowTDSAccess" };

// Retrieve the privileges
var query = new QueryExpression
{
    EntityName = "privilege",
    ColumnSet = new ColumnSet("privilegeid", "name")
};
query.Criteria.AddCondition("name", ConditionOperator.In, privileges);

DataCollection privilegeRecords =
   service.RetrieveMultiple(query).Entities;

// Define a list to hold the RolePrivileges we'll need to add
List rolePrivileges = new List();

//Populate the RolePrivileges parameter
foreach (Entity privilege in privilegeRecords)
{
    RolePrivilege rolePrivilege = new RolePrivilege(
       (int)PrivilegeDepth.Global,
       privilege.GetAttributeValue("privilegeid"));

    rolePrivileges.Add(rolePrivilege);
}

// Prepart the request
AddPrivilegesRoleRequest request = new AddPrivilegesRoleRequest()
{
    Privileges = rolePrivileges.ToArray(),
    RoleId = RoleId
};
// Send the request
service.Execute(request);

 

Published on:

Learn more
Featured Articles | Dynamics Chronicles
Featured Articles | Dynamics Chronicles

Welcome to our blog, the content is entirely dedicated to Microsoft Dynamics 365, CRM, Power Platform, Common Data Service (CDS) but also Azure. Follow us !

Share post:

Related posts

Newsletter

Get the latest Dynamics 365 and Power Platform content in your inbox

A curated digest of community blogs, product news, videos, and podcasts — delivered without the noise.

Weekly updates Unsubscribe anytime Fresh community picks
We use your email only for the newsletter and you can unsubscribe at any time.
By subscribing, you agree to the privacy policy.