CRM Crate

We will learn to execute messages like create & update within a single database transaction using ExecuteTransactionRequest class. Before we start, make sure to subscribe to CRM Crate so that you can stay up to date in the field of Power Platform.

How to execute messages within a single database transaction using  ExecuteTransactionRequest?

It is important to understand that within Dataverse, all data operations are denoted as messages, and the definitions for these messages are stored within the Dataverse system. Every message has a unique name, a collection of input parameters & a collection of output parameters.

Three distinct methods for utilizing a message with the SDK for .NET are elaborated in the below given sections

MethodDescription
OrganizationRequest and OrganizationResponse classesUse these classes in situations where SDK Request and Response classes are unavailable. Opting for this approach might be preferable over generating SDK Request and Response classes, especially when you are already familiar with the message name and the specifics of input and output parameters.
SDK Request and Response classesThe utilization of these classes represents the most prevalent method for working with messages. Numerous messages already come with predefined classes in the SDK for .NET. In the case of custom actions, you have the option to generate classes.
IOrganizationService methodsThe IOrganizationService offers a set of methods designed for common data operations. These methods stand out as the swiftest and simplest means to execute a majority of common data operations.

Executing messages in a single database transaction with help of ExecuteTransactionRequest

In business applications, it’s often necessary to synchronize modifications across multiple table / entity rows in a system, ensuring that either all data changes (Row attribute changes) succeed or none of them do. In database terminology, this involves executing multiple operations within a single database transaction, allowing for the rollback or cancelling modification of all data changes if any individual operation fails.

The ExecuteTransactionRequest message request allows you to perform two or more requests within a single database transaction. In order to utilize this message, populate the Requests collection with at least two organization requests that need to be executed within the transaction.
If you want to receive a collection of responses, with each response corresponding to a executed message request, set ReturnResponses to ‘true’ in order to populate the Responses collection. The message requests within the Requests collection are executed sequentially based on their order in the collection, with the element at index 0 being executed first. This exact order is maintained in the Responses collection.

If any of the requests encounter a failure leading to a transaction rollback, any data modifications made during the transaction are reverted. Furthermore, an ExecuteTransactionFault is returned, indicating the index within the request collection of the message request responsible for the fault.
Important Note – An ExecuteMultipleRequest can include one or more instances of ExecuteTransactionRequest. However, an ExecuteTransactionRequest instance cannot contain an ExecuteMultipleRequest or another ExecuteTransactionRequest.

The below code demonstrates the usage of ExecuteTransactionRequest for creating new rows in Dataverse within a single database transaction.

/// <summary>
/// CRM Crate Demonstrates ExecuteTransaction
/// </summary>
/// <param name="service">Authenticated IOrganizationService instance</param>
static void CRMCrateDemo_ExecuteTransaction(IOrganizationService service)
{

    // A collection of three create requests in Dataverse
    OrganizationRequestCollection requests = new() {
         {
            new CreateRequest(){
                  Target = new Entity("crmcrateaccount"){
                     Attributes = {
                           { "name","Prashant Tirlotkar"},                       
                           { "usertype", new OptionSetValue(1) //Owner}

                     }
                  }
            }
         },
         {
            new CreateRequest(){
                  Target = new Entity("crmcrateaccount"){
                     Attributes = {
                           { "name","Pooja Tirlotkar"},
                           { "usertype", new OptionSetValue(2) //Co-Owner}
                     }
                  }
            }
         }
            new CreateRequest(){
                  Target = new Entity("crmcrateaccount"){
                     Attributes = {
                           { "name","Trupti Basvankar"},
                           { "usertype", new OptionSetValue(3) //Consumer}
                     }
                  }
            }
         }
      };

    // Prepare the ExecuteTransactionRequest request
    ExecuteTransactionRequest request = new()
    {
        Requests = requests,
        ReturnResponses = true
    };

    try
    {
        // Send the request
        var response = (ExecuteTransactionResponse)service.Execute(request);

        // Process the successful responses
        response.Responses.ToList().ForEach(x => {
            var createResponse = (CreateResponse)x;
            Console.WriteLine($"Created CRM Crate Account with ID:{createResponse.id}");
        });

    }
    catch (FaultException<OrganizationServiceFault> ex)
    {
        int index = ((ExecuteTransactionFault)ex.Detail).FaultedRequestIndex + 1;
        string message = ex.Detail.Message;

        Console.WriteLine($"Create request failed for the CRM Crate Account {index} because: {message}");
    }
}

Output of above code

Created CRM Crate Account with ID:8662fc13-fd71-ee11-9ae7-000d3a993550
Created CRM Crate Account with ID:8b62fc13-fd71-ee11-9ae7-000d3a993550

Now let us purposefully fail once of the create request by passing invalid optionset “usertype” value ‘4’ because the value ‘4’ does not exists in the optionset attribute.

// Invalid Optionset value
{ "usertype", new OptionSetValue(4)}

Output of above code

Create request failed for the CRM Crate Acccount 2 because: A validation error occurred.
The value 4 of ‘usertype’ on record of type ‘account’ is outside the valid range.
Accepted Values: 3,2,1

Thus we learned to execute messages within a single database transaction ExecuteTransactionRequest class.


5 1 vote
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
error: CRM Crate Security Engine - Disabled Right Click & Selection!

Congratulations!

Well Done,
Welcome to CRM Crate

Stay tuned with us and get all latest updates and learning in Microsoft CRM and related techonologes.