Associate a Security Role on User Creation in CRM 2011 using Async Plugin

Below is the sample code to associate a security role on user creation in CRM 2011. Register the plugin on Post Create of systemuser entity and select execution mode as Asynchronous

 

public void Execute(IServiceProvider serviceProvider)

        {

            // Obtain the execution context from the service provider.

            IPluginExecutionContext context =

                (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

 

            // Get a reference to the organization service.

            IOrganizationServiceFactory factory =

                (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

            IOrganizationService service = factory.CreateOrganizationService(context.UserId);

 

 

// The InputParameters collection contains all the data passed in the message request.

            if (context.InputParameters.Contains(“Target”) &&

                context.InputParameters[“Target”] is Entity)

            {

                // Obtain the target entity from the input parameters.

                Entity entity = (Entity)context.InputParameters[“Target”];

 

                // Verify that the target entity represents a systemuser.

                // If not, this plug-in was not registered correctly.

                if (entity.LogicalName != “systemuser”)

                    return;

 

            try

            {

// get user entity record id

Guid userId=(Guid)context.OutputParameters[“id”];

 

//Get Id of Security Role

Guid securityRoleId=new Guid(“<enter guid here>”)

                // Create the request object

// systemusersroles_association relationship.

AssociateRequest addRolesToUser = new AssociateRequest

{

    Target = new EntityReference(“systemuser”, userId),

    RelatedEntities = new EntityReferenceCollection

    {

        new EntityReference(“role”, securityRoleId)

    },

    Relationship = new Relationship(“systemuserroles_association”)

};

 

// Execute the request.

service.Execute(addRolesToUser);

            }

            catch (FaultException<OrganizationServiceFault> ex)

            {

                // Handle the exception.

            }

        }

}

 hope it will help u !

Author: Arvind Singh

Microsoft Dynamics CRM Consultant

Leave a Reply

Please log in using one of these methods to post your comment:

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