Please help me with this code. I am trying to create a plugin for Dynamics 365 portal to check the logged in user's web roles (adx_webrole) and if the user has role named "administrator", then update of the field "permissions" should be allowed, otherwise it should throw an error.
I am trying the following code. Even if I have the administrator web role, it throws error. So I believe my code is not fetching any web roles. Please help.
private bool UserHasWebRole(Guid userId, string webRoleName, IOrganizationService service)
{
// Query to check if the user has the specified web role
QueryExpression query = new QueryExpression("contact");
query.ColumnSet = new ColumnSet("contactid");
query.Criteria.AddCondition("contactid", ConditionOperator.Equal, userId);
query.LinkEntities.Add(new LinkEntity("adx_webrole", "adx_webrole_contact", "adx_webroleid", "contactid", JoinOperator.Inner));
query.LinkEntities[0].LinkCriteria.AddCondition("role", ConditionOperator.Equal, GetWebRoleId(webRoleName, service));
EntityCollection result = service.RetrieveMultiple(query);
// If there are records, the user has the web role
return result.Entities.Count > 0;
}
private Guid GetWebRoleId(string webRoleName, IOrganizationService service)
{
// Retrieve the web role ID based on its name
QueryExpression query = new QueryExpression("adx_webrole");
query.ColumnSet = new ColumnSet("adx_webroleid");
query.Criteria.AddCondition("adx_name", ConditionOperator.Equal, webRoleName);
EntityCollection result = service.RetrieveMultiple(query);
// Check if the web role exists
if (result.Entities.Count > 0)
{
return result.Entities[0].Id;
}
else
{
throw new InvalidPluginExecutionException($"Web role '{webRoleName}' not found.");
}
}