Set Values of all Data Types using Web API in Dynamics CRM

By | February 10, 2016

In CRM 2016, Microsoft Introduced a new concept called “Web API” (OData v4) to perform CRUD operations as well as other special messages supported in Dynamics CRM. Stepping towards the new enhancement OData v2 is deprecated from the CRM 2016.

Though WEB API too requires the object to be sent in JSON form, it differs a little in the way the values for fields that support complex data type are set. The aim of this blog was to take up most of the common data types used and provide a sample code around how the values need to be set of each of these

Sample code to create an Account Entity Record with all Data Types

///----------- Create with all Data Type (Account) --------
function createAccountWithAllDT() {
    try {
        //declare variables
        var uri = null;
        var stringJSONAcc = null;
        var entityIdWithLink = null;
        var getEntityId = null;

        //create JSON object 
        var JSONAcc = {};

        //set fields using JSON object
        //Single line of text
        JSONAcc.name = "CompanyName Pvt. Ltd."; //Account Name
        
        //Option Set
        JSONAcc.accountcategorycode = "2" //Category : 1--> Preferred Customer, 2--> Standard

        //Two Options
        JSONAcc.donotsendmm = false;//Marketing Materials : 0-->False/Send, 1-->True/Do Not Send
        //Whole Number
        JSONAcc.numberofemployees = 151; //Number of Employees

        //Decimal Number
        JSONAcc.new_decimalnumber = 345.12; //Decimal Number (Custom Field) 

        //Lookup
        JSONAcc["transactioncurrencyid@odata.bind"] = "/transactioncurrencies(4e950855-9eb3-e511-80de-6c3be5a8ad10)"; //Currency

        JSONAcc["primarycontactid@odata.bind"] = "/contacts(DFE54660-37CD-E511-80DE-6C3BE5A831DC)" //Primary Contact

        //Currency
        JSONAcc.creditlimit = 15000; //Currency Limit

        //Date 
        JSONAcc.new_dateonly = new Date();//Date Only (Custom Field)

        //convert JSON object to string
        stringJSONAcc = JSON.stringify(JSONAcc);

        //url for ajax request to create account
        uri = Xrm.Page.context.getClientUrl() + "/api/data/v8.0/accounts";

        //ajax request to create account
        $.ajax({
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            url: uri,
            data: stringJSONAcc,
            beforeSend: function (XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("Accept", "application/json");
                XMLHttpRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8");
                XMLHttpRequest.setRequestHeader("Prefer", "odata.include-annotations=*");
            },
            //Success Callback Function
            success: function (data, textStatus, XMLHttpRequest) {
                //get Response from Created Record
                entityIdWithLink = XMLHttpRequest.getResponseHeader("OData-EntityId");

                //get EntityId from ResponseHeader of Created Record  
                getEntityId = entityIdWithLink.split(/[()]/);
                getEntityId = getEntityId[1];

                //Display Enttity ID of Created Record
                Xrm.Utility.alertDialog("Entity ID : " + getEntityId);
            },
            //Error Callback Function
            error: function () {
                Xrm.Utility.alertDialog("Something Wrong in Script POST...:(");
            }
        });
    } catch (e) {
        Xrm.Utility.alertDialog(e.message + "\n" + e.description);
    }
}

Sample code to create an Activity & set Activity Party

///------------ Create Phone Call Activity ----------

function createPhoneCall() {
    try {
        //declare variables
        var phonecallId = null;
        var stringJSONPhone = null;
        var urlPhone = null;

        //create activity party collection
        var parties = [];

        //create JSON object 
        var JSONPhone = {};

        //set fields using JSON object
        //Single line of text
        JSONPhone["subject"] = "Test Phone Call"; //Subject

        //Single line of text & format of phone 
        JSONPhone["phonenumber"] = "9876543210"; //Phone Number

        //Multiple Line of Text
        JSONPhone["description"] = "Phone Call Activity for Testing Purpose only...!"; //Description

        //Date and Time
        JSONPhone["scheduledend"] = new Date(); //Due

        //Lookup
        JSONPhone["regardingobjectid_account@odata.bind"] = "/accounts(B386D403-F7AD-E511-80DC-A45D36FC4F90)"; //Regarding is an account

        //ActivityParty (From)
        var sender = {};
        sender["partyid_systemuser@odata.bind"] = "/systemusers(D949B11D-9240-4037-8379-F31C7A36680E)";
        sender["participationtypemask"] = 1; //From

        //ActivityParty (To)
        var receiver1 = {};
        receiver1["partyid_account@odata.bind"] = "/accounts(B386D403-F7AD-E511-80DC-A45D36FC4F90)";
        receiver1["participationtypemask"] = 2; //To
        //receiver["addressused"] = "roohi@dyn20161.onmicrosoft.com";

        var receiver2 = {};
        receiver2["partyid_contact@odata.bind"] = "/contacts(DFE54660-37CD-E511-80DE-6C3BE5A831DC)";
        receiver2["participationtypemask"] = 2; //To

        var receiver3 = {};
        receiver3["partyid_lead@odata.bind"] = "/leads(ED81F0D9-37CD-E511-80DE-6C3BE5A831DC)";
        receiver3["participationtypemask"] = 2; //To

        //add this to collection
        parties.push(sender);
        parties.push(receiver1);
        parties.push(receiver2);
        parties.push(receiver3);

        //pass parties[] to phonecall_activity_parties
        JSONPhone["phonecall_activity_parties"] = parties;

        //Whole Number
        JSONPhone["actualdurationminutes"] = 25; //Duration

        //Two Options
        JSONPhone["directioncode"] = true;//Direction : 0-->False/Incomming, 1-->True/Outgoing

        //convert JSON object to string
        stringJSONPhone = JSON.stringify(JSONPhone);

        //url for ajax request to create phonecall activity
        urlPhone = Xrm.Page.context.getClientUrl() + "/api/data/v8.0/phonecalls";

        //ajax request to create phonecall activity
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            url: urlPhone,
            data: stringJSONPhone,
            beforeSend: function (CreatePhoneCallActivityRequest) {
                CreatePhoneCallActivityRequest.setRequestHeader("Accept", "application/json");
                CreatePhoneCallActivityRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8");
                CreatePhoneCallActivityRequest.setRequestHeader("Prefer", "odata.include-annotations=*");
                CreatePhoneCallActivityRequest.setRequestHeader("OData-MaxVersion", "4.0");
                CreatePhoneCallActivityRequest.setRequestHeader("OData-Version", "4.0");
            },
            //Success Callback Function
            success: function (data, taxtStatus, getPhoneCallActivityResponse) {
                //get Response from Created Record
                phonecallId = getPhoneCallActivityResponse.getResponseHeader("OData-EntityId");

                //get EntityId from ResponseHeader of Created Record 
                phonecallId = phonecallId.split(/[()]/);
                phonecallId = phonecallId[1];

                //Display Enttity ID of Created Record
                Xrm.Utility.alertDialog("Entity ID : " + phonecallId);

            },
            //Error Callback Function
            error: function (CreatePhoneCallActivityRequest, textStatus, errorThrown) {
                Xrm.Utility.alertDialog("Something Wrong in Script...:(");
            }
        });
    } catch (e) {
        Xrm.Utility.alertDialog(e.message + "\n" + e.description);
    }
}

Conclusion:

Lookup, Regarding and Activity parties being special complex field need to be set by providing a reference to the entity type that you intend to set. The field name also includes a reference to the entity as can be seen in the sample code above. This differs from the way it used to be done earlier where entity type used to be provided as a property of the Lookup object instead of in the field name itself.

We would like to take a moment to introduce our new product Alerts4Dynamics to you. Alerts4Dynamics lets you schedule and manage alerts in Dynamics 365 CRM to notify users about the updates in CRM, due invoices, reminder to send quotes, etc. You can define target audience and send them priority based alerts via pop-ups, form notifications and emails. You can also view the log of read/dismissed alerts by users and also create alerts for multiple records by defining rules.

2 thoughts on “Set Values of all Data Types using Web API in Dynamics CRM

  1. jedom

    I’m facing an error using your code to populate a lookup, on a custom entity


    JSONAcc[“new_qualifiedleadid@odata.bind”] = “/opportunities(“+ QualLeadId + “)”; //Currency

    //url for ajax request to create account
    uri = Xrm.Page.context.getClientUrl() + “/api/data/v8.0/new_opportunities”;

    When I download the new_opportunities.json file, I can find a reference to this field:
    “_new_qualifiedleadid_value”

    Nevertheless, send of JSON request returns with following error :

    {
    “error”:{
    “code”:””,”message”:”An undeclared property ‘new_qualifiedleadid’ which only has property annotations in the payload but no property value was found in the payload. In OData, only declared navigation properties and declared named streams can be represented as properties without values.”,”innererror”:{
    “message”:”An undeclared property ‘new_qualifiedleadid’ which only has property annotations in the payload but no property value was found in the payload. In OData, only declared navigation properties and declared named streams can be represented as properties without values.”,”type”:”Microsoft.Crm.CrmHttpException”,”stacktrace”:” at Microsoft.Crm.Extensibility.OData.CrmODataUtilities.ValidateInputParameters(ModelStateDictionary controllerModelState)\r\n at Microsoft.Crm.Extensibility.OData.EntityController.PostEntitySet(String entitySetName, EdmEntityObject entityObject)\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.c__DisplayClass10.b__9(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n— End of stack trace from previous location where exception was thrown —\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()\r\n— End of stack trace from previous location where exception was thrown —\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext()\r\n— End of stack trace from previous location where exception was thrown —\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()”
    }
    }
    }

    Do you have any idea to solve this issue ?
    Thanks.

    Reply
    1. inogic Post author

      Hi,

      Please follow the steps listed below :

      Step 1 : Goto Cutomization  Developer Resource.

      Step 2 : Click to “Download Odata Metadata” link and Download the same.

      Step 3 : Once Download, open it and find out name of lookup attribute ( i.e. “new_qualifiedleadid”) and check its casing.

      Step 4 : Verify it with the value which you are setting in the code it should be same.

      Hope it helps!

      Thanks

      Reply

Leave a Reply to inogic Cancel reply

Your email address will not be published. Required fields are marked *