When you design Plugins for Microsoft Dynamics CRM, you sometime need to have them run as a different user in order to perform operations that a non admin user cannot normally do. This is usually done by using the Plugin Registration tool and setting the value of the “Run in User’s Context” drop down field to a specific value (see screenshot below).
Today I want to show a way to do this programmatically. Our design is fairly simple and the overall goal is to have the appropriate impersonation user being assigned to all required plugin steps automatically without manual processing post-solution import.
- Create Plugins and steps with the Plugin Registration Tool as usual
- The name of each plugin that requires to run as an admin user must contain a pre-defined text (in our case [Admin])
- After each solution is imported to CRM, a plugin fires and look for all plugin steps where the name contains [Admin]
- Updated the Run In User’s Context field with an admin user defined as per configuration
That’s easy enough. For step 4, where you store the configuration is up to you, it could be registry, XML web resource, custom entity etc.
Here is the code to do it: