Scenario 3

This scenario deals with how we can implement impersonation in a plugin. By default, when a plugin is executed, all the calls and actions made inside the plugin are done under the security context of the calling user. However, in many cases, inside a plugin, we may have to make certain calls that would require some elevated privileges.

For example, in the first scenario that we discussed in this chapter, we wrote code that reads regions and bus region roaster records present in the Dynamics CRM system. However, the user who is entering the student details in the system may not have access of these two entity records. Therefore, as per the code, if the user will try to enter the student details in the system, they will get a security exception while executing the retrieve command.

Due to this, we will need to impersonate the plugin calls whenever we encounter such scenarios. We can implement an impersonation in a plugin in two ways:

    1. Right-click on the plugin class and select Register New Step:
    1. Refer to the dropdown Run in User's Context. Click that dropdown and select the user in the context of which you want the plugin to be executed:
      using System; 
      using System.Collections.Generic; 
      using System.Linq; 
      using System.Text; 
      using Microsoft.Xrm.Sdk; 
      using Microsoft.Crm.Sdk.Messages; 
      using Microsoft.Xrm.Sdk.Query; 
 
      namespace SamplePluginProject 
      { 
        public class PreCreateUpdateStudent : IPlugin 
        { 
          public void Execute(IServiceProvider serviceProvider) 
          { 
            // Plugin Context object 
            Microsoft.Xrm.Sdk.IPluginExecutionContext context = 
(Microsoft.Xrm.Sdk.IPluginExecutionContext) serviceProvider.GetService(typeof
(Microsoft.Xrm.Sdk.IPluginExecutionContext)); // Retrieving Organisation service context object IOrganizationServiceFactory serviceFactory =
(IOrganizationServiceFactory)serviceProvider.GetService
(typeof(IOrganizationServiceFactory)); IOrganizationService service =
serviceFactory.CreateOrganizationService(new Guid
("8240cddf-fb54-4d96-90db-0ff926be0c14")); } } }

Now we can use this service object for executing all Dynamics CRM-side operations such as create, update, and so on.