Let’s suppose we have a Web API making some calls to the Dynamics CRM, in order to retrieve some entity records, and there are plugins running against the Retrieve Multiple message in post-operation stage. The business logic which is implemented in the retrieve multiple plugin should only be executed if the retrieve multiple is made from the Web API, and when is triggered from other sources other than the Web API, the logic should not be executed. This is a challenge I have faced recently.
The first thing I thought, would be, somehow, trying to pass a parameter into the plugin in order to signal when the retrieve multiple is made from the Web API.
The idea I came up with was:
- Web API: Add a filter condition in the query expression being performed (I was using query expression, the same is valid for Fetch Expression where the custom parameter could be passed in the fetch xml header) which contained the key and its value to pass into the plugin;
- Pre-operation (Retrieve Multiple): In order to avoid the query expression to fault, due to the condition previously added, it is necessary to remove that condition in the pre-operation stage of the retrieve multiple. Therefore in this stage, the filter condition is accessed, obtained the key and the value, and remove the filter condition from the query expression. As the parameter is needed in the post-operation stage, then it is added to the shared variables;
- Post-operation (Retrieve Multiple): The parameter is obtained from the shared variables.
This same principle may be applied to other messages, like create or update where the custom parameters can be passed into the plugin through the target attributes collection (like next figure), being removed in the pre-operation.