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 tackle Concurrent Business Process flows

Dynamics 365 has introduced the new feature of Concurrent Business Process Flows. Here is a couple of good articles on that: http://dev...