Archive
Complete a transaction and throw exception in CRM Plug-in
Recently I was asked a question in my blog on how to achieve below scenario in plug-in.
- User try to save Account record by providing data in multiple fields.
- Create Plug-in should check whether any other Account already exists in CRM with provided data.
- If match found, update the existing record and display “Cannot save the Account as Account with data already exists”
- If no match found, create an Account.
Challenge:
- If ‘Account’ match found, system should update matched Account and at the same time throw message “Cannot save the Account as Account with data already exists”.
- To display message Plugin must throw Execution with message which would roll back the update operation.
Proposed Design:
- Register a Plug-in on “PreCreateAccount” with following logic, if matching ‘Account’ already exists with input data.
- To complete update operation,
- Use “ExecuteMultipleRequest” with option “ContinueOnError = true” which completes transaction.
- Instantiate ‘UpdateRequest’ and execute using “ExecuteMultipleRequest”
- In next line, throw exception with message
Plug-in Code:
// Get the matched Account
Entity matchedAccount = new Entity(“account”);
UpdateRequest reqUpdate = new UpdateRequest();
reqUpdate.Target = matchedAccount;// Use this to complete the update operation even on an exception
ExecuteMultipleRequest reqMultiple = new ExecuteMultipleRequest(){
Requests = new OrganizationRequestCollection(),
Settings = new ExecuteMultipleSettings(){
ContinueOnError = true,
ReturnResponses = false
}
};// Add Update Request to Multiple Request.
reqMultiple.Requests.Add(reqUpdate);// Trigger the Execute Multiple.
crmOrgService.Execute(reqMultiple);// Use this to display message to user
throw InvalidPluginExecutionException(“Cannot save the Account as Account with data already exists”);
🙂