Tuesday, 21 February 2017

How to execute a plugin as the logged in user?

Quite often I have seen people asking this question and they complain they have used the right piece of code but still CRM is using the system account instead of the logged in user to execute the plugin.
This is what they had used in their plugin code:

IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
service = serviceFactory.CreateOrganizationService(context.UserId);

Correct code should have been used InitiatingUserId rather than the UserId. So it should be
service = serviceFactory.CreateOrganizationService(context.InitiatingUserId);
 instead of

service = serviceFactory.CreateOrganizationService(context.UserId);

No comments:

Post a Comment

How to assign a record to the current user via JavaScript

Recently I got a requirement from the customer to create a ribbon button on a custom entity so that a user can click on that button and get...