{Advanced Code Tip}Creating Atomicity of a Transaction in Dynamics CRM 2015

Sending
User Review
0 (0 votes)

Consider how many times you have been around in the scenario that you are doing some integration or

a batch job with Dynamics CRM and in the interim there is an exception, so you need to design rollback for your job/integrations.

With Dynamics CRM 2015, designs can be simplified way further. There was a new request type introduced with Dynamics CRM 2015: ExecuteTransactionRequest.

In the example below I have intentionally left an error and I am trying to either create a contact and account together or none.

Exception scenario:

using (var service = new OrganizationService(connection))

            {

                ExecuteTransactionRequest request = new ExecuteTransactionRequest();

                Entity account = new Entity(“account”);

                account.Attributes[“name”] = “Transaction Test”;    

                Entity contact = new Entity(“contact”);

                contact.Attributes[“name”] = “Transaction Test Contact”;         

                CreateRequest create1 = new CreateRequest();

                create1.Target = account;

                CreateRequest create2 = new CreateRequest();

                create2.Target = contact;

                request.Requests = new OrganizationRequestCollection { create1, create2 };

                ExecuteTransactionResponse response =  (ExecuteTransactionResponse)service.Execute(request);

            }

Exception:

clip_image002

In this case, Even account was not created:

clip_image004

After Correction:

   using (var service = new OrganizationService(connection))

            {

                ExecuteTransactionRequest request = new ExecuteTransactionRequest();

                Entity account = new Entity(“account”);

                account.Attributes[“name”] = “Transaction Test”;    

                Entity contact = new Entity(“contact”);

                contact.Attributes[“lastname”] = “Transaction Test Contact”;         

                CreateRequest create1 = new CreateRequest();

                create1.Target = account;

                CreateRequest create2 = new CreateRequest();

                create2.Target = contact;

                request.Requests = new OrganizationRequestCollection { create1, create2 };

                ExecuteTransactionResponse response =  (ExecuteTransactionResponse)service.Execute(request);

            }

Created two of them together:

clip_image002[6]

clip_image004[5]

Hope it helps and Happy CRMing!