Using Upsert in Microsoft Dynamic CRM 2015/2016

Standard

From 2015 version, Microsoft has been introduced the new message UpsertRequest, it is very useful for data integration from external system. It is very useful for scenarios which you cannot know when you need to create or update data. You can look for the C# sample at this link. This article will show you how can we do Upsert in client script.

This sample just use to demonstrate about using Upsert in client script only.

Step 1: Create 1 js library, I will use lidCrm.js in this sample.

Note: Your web api will be look like:  

your CRM Url” + “/api/data/v8.0/”

Step 2: Create 1 method CreateRecord as following

function createRecord(entityObject,

enityName, async, successCallback, errorCallback, callerId)

{

    /// <summary>Create entity record</summary>

    /// <paramname=”entityObject” type=”Object”>MS CRM object</param>

    /// <paramname=”enityName” type=”String”>The name of Entity that we want to create in MS CRM</param>

    /// <paramname=”async” type=”Boolean” optional=”true”>The value that you want to set Async or Sync. The default is Async</param>       

    /// <paramname=”successCallback” type=”Function”>The function to call if process is successful.</param>

    /// <paramname=”errorCallback” type=”Function”>The function to call when there is an error.</param>

    /// <paramname=”callerId” type=”String” optional=”true”>The systemuserid value of the user to
impersonate</param>

    this._stringParameterCheck(enityName, “CrmSdk.createRecord requires the type parameter is a string.”);

    //this._callbackParameterCheck(this.successCallback, “CrmSdk.createRecord requires the successCallback is a function.”);

    // this._callbackParameterCheck(this.errorCallback, “CrmSdk.createRecord requires the errorCallback is a function.”);

    if (!this.isBoolean(async))
{

        throw new Error(“CrmSdk.createRecord requires async parameter is boolead”);

    } ;

    if (this.is)

        if (enityName.slice(-1) != “s”) { enityName = enityName + “s”;

        }

    var req = new XMLHttpRequest();

    if(async) { req.open(“POST”, encodeURI(this._WebAPIPath() + enityName), async);

    }

    else{

              //You should replace this._WebAPIPath by your web api

       req.open(“POST”,encodeURI(this._WebAPIPath() + enityName), true);

       req.setRequestHeader(“Accept”, “application/json”);

       if(callerId) {req.setRequestHeader(“MSCRMCallerID”,callerId);

    }

    req.setRequestHeader(“Content-Type”, “application/json;charset=utf-8”);

    req.setRequestHeader(“OData-MaxVersion”, “4.0”);

    req.setRequestHeader(“OData-Version”, “4.0”);

    req.onreadystatechange = function () {

        if (this.readyState == 4 /* complete */) {

            req.onreadystatechange = null;

            if (this.status == 204) {

                var entityUri = this.getResponseHeader(“OData-EntityId”);

                successCallback(entityUri);

            }

            else {

                errorCallback(this.errorHandler(this));

            }

        }

    };

    req.send(JSON.stringify(entityObject));

}

Step 2: Create new Method call upSert

function upsert (uri, entity, preventCreate, preventUpdate, successCallback, errorCallback, callerId) {

/// <summary>Upsert an entity</summary>

/// <param name=”uri” type=”String”>The Uri for the entity you want to create orupdate</param>

/// <param name=”entity” type=”Object”>An object that contains updated properties for the entity.</param>

/// <param name=”preventCreate” type=”Boolean”>Whether you want to prevent creating a new entity.</param>

/// <param name=”preventUpdate” type=”Boolean”>Whether you want to prevent updating an existing entity.</param>

/// <param name=”successCallback” type=”Function”>The function to call when the operation is
performed</param>

/// <param name=”errorCallback” type=”Function”>The function to call when there is an error. The
error will be passed to this function.</param>

/// <param name=”callerId” type=”String” optional=”true” optional=”true”>The systemuserid value of the user to impersonate</param>

if (!(preventCreate && preventUpdate)) {

    var req = new XMLHttpRequest();

    req.open(“PATCH”, encodeURI(uri), true);

    req.setRequestHeader(“Accept”, “application/json”);

    if (callerId) {

        req.setRequestHeader(“MSCRMCallerID”, callerId);

    }

    req.setRequestHeader(“Content-Type”, “application/json;charset=utf-8”);

    if(preventCreate) {

        req.setRequestHeader(“If-Match”, “*”);

    }

    if (preventUpdate) {

        req.setRequestHeader(“If-None-Match”, “*”);

    }

    req.setRequestHeader(“OData-MaxVersion”, “4.0”);

    req.setRequestHeader(“OData-Version”, “4.0”);

    req.onreadystatechange = function () {

        if (this.readyState == 4 /* complete */) {

            req.onreadystatechange = null;

            switch (this.status)
{

                case 204:

                    if(successCallback)

                        successCallback(this.getResponseHeader(“OData-EntityId”));

                    break;

                case 412:

                    if(preventUpdate) {

                        if(successCallback)

                            successCallback(); //Updateprevented

                    }

                    else {

                        if(errorCallback)

                            errorCallback(Sdk.WebApiOperation.errorHandler(this));

                    }

                    break;

                case 404:

                    if(preventCreate) {

                        if(successCallback)

                            successCallback(); //Createprevented

                    }

                    else {

                        if(errorCallback)
errorCallback(Sdk.WebApiOperation.errorHandler(
this));

                    }

                    break;

                default:

                    if(errorCallback)
errorCallback(Sdk.WebApiOperation.errorHandler(
this));

                    break; 

            }

        }

    };

    req.send(JSON.stringify(entity));

}

else {console.log(“Sdk.WebApiOperation.upsert performed no action because both preventCreate and preventUpdate parameters were true.”);

}

}

Step 3: To test these method, just create 1 HTML Web resource (WebAPIOperation.html), and create 1 js web resource libCRM. You can name any name you want.

UpSert

Step 4: Open your HTML web resource and add

UpSert

Step 5: Continue to add these code in your body tag

<input title=”Create” id=”btnUpSert” type=”button” value=”Using Upsert” onclick=”UpSert()” style=”width:120px;height:30px” />

Step 5: Add script tag and create method Upsert in your HTML web resource.

Step 6: Add the following method:

        function UpSert() {

            var accountUri = null;

            var account = new Object();

            var account1 = new Object();

            account.name = “Account Name”;           

 

           libCRM.createRecord(account, “accounts”, true, function (uri) {

                accountUri = uri;

                alert(“Created account:” + ‘&amp;nbsp’ +account.name);

 

                //Preparing for upsert- Do not agree for Creating, Updating

                account1.name = “Account Name 1”; 

                libCRM.upsert(accountUri, account1, false, true, function () {

                 //You can remove this line code
libCRM.parseJsonFromUri(accountUri,
function (result) {

                        alert(result.name)

                    }, function (error) {

                        alert(error);

                    })

 

                }, function () {

                })

            }, function(error) {

                alert(error);

            })

        }

Step 7: Run to text, you just open your solution, open your HTML web resource and open as preview mode as following image.

UpSert

Result: This sample first will create 1 account which first name: “Account Name”, then Upsert will create 1 account  “Account Name 1”, because we set the preventUpdate equal to “true” & preventCreate equal to “false”.

Hope it will be useful for someone.

Leave a comment