Wednesday 13 September 2017

Changing systemuser status and associating a role

Aim: To change the systemuser status from active to inactive and associate a role with a systemuser.

The following two C# methods demonstrate how to change the systemuser state from active to inactive and vice versa. The second method shows how to associate a role with a systemuser.


For changeUserStatus method you will also need to include the Microsoft.CRM.SDK DLL as well since the SetStateRequest message is present here.


The changeUserStatus method shows how to change to user state from active to inactive or from inactive to active. You need to pass the systemuser GUID whose state needs to be changed, the organization service and the state you want to change the user to. State takes a int parameter (1 is for inactive and 0 is for active)


In CRM changing the system user state is done through the SetStateRequest. SetStateSystemUserRequest was used in earlier versions of CRM and is deprecated now.




 private void changeUserStatus(Guid userId, IOrganizationService service,int state)

 {         
      SetStateRequest setStateRequest = new SetStateRequest{
                  EntityMoniker = new EntityReference("systemuser", userId),
                   State = new OptionSetValue(state),//1=disabled, 0=enabled
                   Status = new OptionSetValue(-1),
                   };
       service.Execute(setStateRequest);
               
 }



The associateRoleWithUser method associates a role with a user. You need to pass the system user GUID and role GUID between for which the association needs to be created. The relationship name also needs to be passed. This is the name by which the relationship will be displayed in the Customizations in CRM UI.


 private void associateRoleWithUser(Guid userId, IOrganizationService serviceGuid role, string relationshipName)

 {
                    
 //Create the associate request
 AssociateRequest associate = new AssociateRequest();

 //This is the systemuser that is being associated to a role  

 associate.RelatedEntities = new EntityReferenceCollection();
 associate.RelatedEntities.Add(new EntityReference("systemuser", userId));

 //Target is the entity to which we are associating the systemuser i.e. role and its GUID.

 associate.Target = new EntityReference("role", role);           

//This is the schema name in CRM that is used while associating entities.                

associate.Relationship = new Relationship(relationshipName);

service.Execute(associate);


}

Hide New... button on lookup controls in model-driven apps

  The 'New ...' button is shown upon opening the lookup search dialog whenever the logged in user has at least user create privileg...