CRM Crate

Perform asynchronous operations during an OnSave event of Dynamics 365.

In this course, we will will learn to perform asynchronous operations during an OnSave event of Dynamics 365 CRM.

What is an OnSave event of Dynamics 365 CRM?

The OnSave event occurs for the below given list of operations –

  1. The user selects the “Save” icon in the lower right corner of the form (Even when there is no changed data to be saved).
  2. Code executes the formContext.data.entity.save method (Even when there is no changed data to be saved).
  3. The user navigates away from the record form and there is un-saved data in the form.
  4. The auto-save option is enabled, 30 seconds after data has changed and there is un-saved data in the form.
  5. Code executes the formContext.data.save method and there is un-saved data in the form.
  6. Code executes the formContext.data.refresh method passing a true value as the first parameter and there is un-saved data in the form.

The nature of OnSave event is synchronous. Considering the application interactiveness and performance, it is not advisible to call an asynchronous code because it does wait for it and we may see unsaved changes. If we make synchronous network request in OnSave event, it can cause slow experience and unresponsive page.

A new Asynchronous OnSave event

Microsoft has introduced an asynchronous OnSave event.This event is called after the completion of Save event and it supports after the Save actions when the save event is executed successfully or failed. To improve the application performance, the OnSave event will be blocked if the operation exceeds above 10 seconds.

Enable Async OnSave event for Dynamics 365 App –

To enable an async OnSave event handlers for a specific app, add the below XML in the customization.xml file. This should be added in the existing AppModule node in your customization.xml file.

<appsettings>
   <appsetting uniquename="CRMCrate_AsyncOnSave">
      <iscustomizable>1</iscustomizable>
      <settingdefinitionid>
         <uniquename>AsyncOnSave</uniquename>
      </settingdefinitionid>
      <value>true</value>
   </appsetting>
</appsettings>

You can also verify the configuration installation status using the below given request:

GET https://org00000000.crm0.dynamics.com/api/data/v9.2/appsettings?$filter=(uniquename eq 'MyAppName_AsyncOnSave')
Accept: application/json
Authorization: Bearer ey...

JavaScript snippet code for OnSave event-

We will call a custom action during the OnSave event of an entity. Since calling a custom action (Web Service) is an aynschronous process, we will use the promise for awaiting the action response. Click here to learn more Promise in JavaScript.

Due to an asynchronous OnSave event, the CRM form will be in loading state until the below given JavaScript snippet yields result.

//CRM Crate - Promise Implementation.
function ExecutionMethod(executionContext) {

    //Input Parameter For Our Web Service
    var parameters = {
        InputParam: "Which is the best CRM?"
    };
    var webserviceData = new actionProcessingMethod(parameters.InputParam);

    try {

        //Step 1 - Call The Promise Method.
        var PromiseReturn = ImplementPromise(webserviceData, executionContext);

        //Step 2 - Bind The Promise Function.
        PromiseReturn.then(function (response) {
            if (response != null) {

                //Display The Promise Output From Async Web Service.
                console.log("Webservice Output Parameter : " + response);
            }
        });
    }
    catch (e) {
        console.log("Error Occured in while calling process : " + JSON.stringify(e));
    }
};

var ImplementPromise = function (actionData, executionContext) {

    //Step 3 - Initiate The Promise Function.
    return new Promise(function (resolve) {

        //Step 4 - Call The Async Web Service.
        Xrm.WebApi.online.execute(actionData).then(
            function (data) {
                if (data.ok) {
                    data.json().then(function (response) {

                        //Step 5 - Resolve The Promise On Valid Webservice Response.
                        if (response.OutputParam != null) {
                            PromiseOutput = response.OutputParam;
                            resolve(PromiseOutput);
                        }
                        else {
                            resolve(false);
                            console.log("Error Occured While Calling Web Service : " + response.SuccessCallBack);
                        }
                    });
                }
            },
            function (error) { alert(error.message || error.description); }
        );
    });
};

//Method To Process Our Web Service.
var actionProcessingMethod = function (InputParam) {
    this.InputParam = InputParam;

    this.getMetadata = function () {
        return {
            boundParameter: null,
            parameterTypes: {
                "InputParam": {
                    "typeName": "Edm.String",
                    "structuralProperty": 1
                }
            },
            operationType: 0,
            operationName: "cc_DemoAction"
        };
    };
};

Thus we learned to perform an asynchronous operation during OnSave event of Dynamics 365 CRM form.

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.