How to get current user record in CRM plugin?

15,644

Solution 1

The information is available in the PluginExecutionContext. The code below is from the Execute method your plugin must implement.

public void Execute(IServiceProvider serviceProvider)
{
    IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
        IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
    Guid userId = context.InitiatingUserId;
}

FYI, the context also has a "UserId" property that may or may not be the same as the InitiatingUserId. If your plugin step registration "Run in Users's Context" field has the value "Calling User", then they will be the same. If you have specified a user in the "Run in User's Context" field, then the UserId field will contain the user ID of the person you specify and the InitiatingUserId will be the actual CRM user whose action triggered the plugin. Sounds like you're looking for the InitiatingUserId.

Solution 2

The above answer is correct. Also keep in mind that if you do not want to run the plugin in the user context you can also get the modifying user from the InputEntity that is passed into the plugin from whatever field is getting updated.

In the scenario where you are not running in user context you can then do a service.Retrieve call to get the full record for the modifying user.

Share:
15,644
user1000258
Author by

user1000258

Updated on June 22, 2022

Comments

  • user1000258
    user1000258 almost 2 years

    I am developing a plugin . Whenever a plugin gets invoked, I need to get current user information ? Is there any way to retrieve that?