How to get current user record in CRM plugin?

user1000258 picture user1000258 · Apr 11, 2012 · Viewed 14.4k times · Source

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

Answer

Jeff picture Jeff · May 16, 2012

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.