Tuesday, 12 April 2016

C# Code for Assigning Security Role to a User - CRM 2011/2013/2015/2016

Hi,

Today we got a requirement to assign Security Role to a user. We all know that Security Roles are associated with User via N:N relationship and relationship name is systemuserroles_association.

We can use AssociateRequest to assign the security roles to the user programmatically.

Here is the C# code for assigning a security role to a user.

public void AssignSecurityRole(Guid guidSystemUserId, Guid guidSecurityRoleId, IOrganizationService crmService)
{
        // Create new Associate Request object for creating a N:N relationsip between User and Security
        AssociateRequest objAssociateRequest = new AssociateRequest();
        // Create related entity reference object for associating relationship
        // In this case we SystemUser entity reference  
        objAssociateRequest.RelatedEntities = new EntityReferenceCollection();
        objAssociateRequest.RelatedEntities.Add(new EntityReference("systemuser", guidSystemUserId));
        // Create new Relationship object for System User & Security Role entity schema and assigning it 
        // to request relationship property
        objAssociateRequest.Relationship = new Relationship("systemuserroles_association");
        // Create target entity reference object for associating relationship
        objAssociateRequest.Target = new EntityReference("role", guidSecurityRoleId);
        // Passing AssosiateRequest object to Crm Service Execute method for assigning Security Role to User
        crmService.Execute(objAssociateRequest);
}

Hope this helps.

--
Happy CRM'ing

Gopinath

No comments:

Post a Comment