Tuesday, November 1, 2016

Use FetchXML to Retrieve Data from MS CRM 2016 using Web API

With Web API in MS CRM, we are retrieve data using FetchXML.
Easy way to construct FetchXML queries are using advanced find in CRM, you can create query in advanced find, add columns, define sorting and then download FetchXML.
Once your FetchXML is ready, you can use this FetchXML in web API to retrieve data from CRM.
Here is sample code for how to execute FetXML and get values from FetchXML result set

ExecuteFetchXML: function () {      
        var accountFetchXML = ['< fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">' +
            '< entity name="account">' +
            '< attribute name="name" />' +
            '< attribute name="accountid" />' +
            '< attribute name="numberofemployees" />' +
            '< attribute name="processid" />' +
            '< attribute name="donotpostalmail" />' +
            '< attribute name="statuscode" />' +
            '< attribute name="statecode" />' +
            '< attribute name="telephone1" />' +
            '< attribute name="ownerid" />' +
            '< attribute name="description" />' +
            '< attribute name="primarycontactid" />' +
            '< attribute name="address1_longitude" />' +
            '< attribute name="exchangerate" />' +
            '< attribute name="createdon" />' +
            '< attribute name="openrevenue" />' +
            '< attribute name="industrycode" />' +
            '< attribute name="shippingmethodcode" />' +
            '< order attribute="name" descending="false" />' +
            '< filter type="and">' +
               '< condition attribute="industrycode" operator="not-null" />' +
            '</ filter>' +
            '< link-entity name="contact" from="contactid" to="primarycontactid" visible="false" link-type="outer" alias="prmContact">' +
               '< attribute name="telephone3" />' +
               '< attribute name="spousesname" />' +
               '< attribute name="ownerid" />' +
               '< attribute name="gendercode" />' +
               '< attribute name="description" />' +
               '< attribute name="createdby" />' +
               '< attribute name="address1_latitude" />' +
               '< attribute name="exchangerate" />' +
               '< attribute name="createdon" />' +
               '< attribute name="annualincome" />' +
             '</ link-entity>' +
           '</ entity>' +
         '</ fetch>'].join('');

        var encodedFetchXML = encodeURIComponent(accountFetchXML);

        var req = new XMLHttpRequest();
        req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.0/accounts?fetchXml=" + encodedFetchXML, true);
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Prefer", "odata.include-annotations=\"OData.Community.Display.V1.FormattedValue\"");
        req.onreadystatechange = function () {
          if (this.readyState === 4) {
            req.onreadystatechange = null;
          if (this.status === 200) {

            var results = JSON.parse(this.response);
              for (var i = 0; i < results.value.length; i++) {                        
               var accountDetails = results.value[i];

               //Single Line Text
               var nameValue = accountDetails['name'];
               var telephone1Value = accountDetails['telephone1'];

               //UniqueIdentifier
               var accountidValue = accountDetails['accountid'];
               var processidValue = accountDetails['processid'];


               //Whole Number
               var numberofemployeesValue = accountDetails['numberofemployees'];

               //Two Option
               var donotpostalmailValue = accountDetails['donotpostalmail'];
               var donotpostalmailTextValue = accountDetails['donotpostalmail@OData.Community.Display.V1.FormattedValue'];

               //Status Reason
               var statuscodeValue = accountDetails['statuscode'];
               var statuscodeTextValue = accountDetails['statuscode@OData.Community.Display.V1.FormattedValue'];

               //Status
               var statecodeValue = accountDetails['statecode']; //Status
               var statecodeTextValue = accountDetails['statecode@OData.Community.Display.V1.FormattedValue'];

               //Owner
               var owneridValue = accountDetails['_ownerid_value'];
               var OwnerName = accountDetails["_ownerid_value@OData.Community.Display.V1.FormattedValue"]

               //Multiple Line
               var descriptionValue = accountDetails['description'];

               //Lookup
               var primarycontactidValue= accountDetails['_primarycontactid_value'];
               var primarycontactidName = accountDetails['_primarycontactid_value@OData.Community.Display.V1.FormattedValue'];

                  //Floating Point Number
                  var address1_longitudeValue= accountDetails['address1_longitude'];

                  //Decimal
                  var exchangerateValue = accountDetails['exchangerate'];

                  //Date Time
                  var createdonValue = accountDetails['createdon'];

                  //Currency
                  var openrevenueValue = accountDetails['openrevenue'];

                  //Option set
                  var industrycodeValue = accountDetails['industrycode'];
                  var industrycodeTextValue = accountDetails['industrycode@OData.Community.Display.V1.FormattedValue'];

                 //Contact - Linked entity data
                 //Single Line Text
                 var prmContact_telephone3Value = accountDetails['prmContact_x002e_telephone3'];
                 var prmContact_spousesnameValue = accountDetails['prmContact_x002e_spousesname'];

                 //Owner
                 var prmContact_owneridValue = accountDetails['prmContact_x002e_ownerid'];

                 //Option set
                 var prmContact_gendercodeValue = accountDetails['prmContact_x002e_gendercode'];
                 var prmContact_gendercodeTextValue = accountDetails['prmContact_x002e_gendercode@OData.Community.Display.V1.FormattedValue'];

                 //Multiple Line
                 var prmContact_descriptionValue = accountDetails['prmContact_x002e_description'];

                 //Lookup
                 var prmContact_createdbyValue = accountDetails['prmContact_x002e_createdby'];

                 //Floating Point Number
                 var prmContact_address1_latitudeValue = accountDetails['prmContact_x002e_address1_latitude'];

                 //Decimal
                 var prmContact_exchangerateValue = accountDetails['prmContact_x002e_exchangerate'];

                 //Date Time
                 var prmContact_createdonValue = accountDetails['prmContact_x002e_createdon'];

                 //Currency
                 var prmContact_annualincomeValue = accountDetails['prmContact_x002e_annualincome'];

                    }
                }
                else {
                    alert(this.statusText);
                }
            }
        };
        req.send();
    },

Remember when using fetchXML query in WEB API
1.      You need to URL encoded FetchXML
2.      With FetchXML you can apply paging by setting page and count attribute of the fetch element.


Friday, October 28, 2016

Set PartyList or Regarding Lookup when using Xrm.Utility object

When using Xrm.Utility object to open entity form or quick Create form, we cannot set PartyList or Regarding Lookup with default field parameters. But there is workaround for this, we can use custom query string parameters and using custom query string parameters we can set PartyList or regarding lookup.
Suppose we want to open email entity form from contact entity and want to set To and 
Regarding lookup when email entity form opened using either
 Xrm.Utility.openEntityForm or Xrm.Utility.openQuickCreate
  
·         Open Email Form or quick create form
·         In Form properties, select Parameter tab.
·         Add 3 parameters, to set To partylist.
Name: new_ToType
Type: SafeString
Name: new_ToName
Type: SafeString
Name: new_ToId
Type: UniqueId
·         Add 3 parameters, to set Regarding lookup
Name: new_RegardingIdName
Type: SafeString
Name: new_RegardingIdType
Type: SafeString
Name: new_RegardingId
Type: UniqueId



·         In Email form load event add JavaScript, which will get query string parameters and will set To party and Regarding lookup.
var emailScript =
{
    setPartyListnRegarding: function () {
        if (Xrm.Page.ui.getFormType() == 1) {

            /*To Party list*/
            var ToPartyList = [];
            ToPartyList[0] = {};

            if (Xrm.Page.context.getQueryStringParameters().new_ToType != null && Xrm.Page.context.getQueryStringParameters().new_ToType != 'undefined') {
                ToPartyList[0].entityType = Xrm.Page.context.getQueryStringParameters().new_ToType;
            }

            if (Xrm.Page.context.getQueryStringParameters().new_ToId != null && Xrm.Page.context.getQueryStringParameters().new_ToId != 'undefined') {
                ToPartyList[0].id = Xrm.Page.context.getQueryStringParameters().new_ToId;
            }
            if (Xrm.Page.context.getQueryStringParameters().new_ToName != null && Xrm.Page.context.getQueryStringParameters().new_ToName != 'undefined') {
                ToPartyList[0].name = Xrm.Page.context.getQueryStringParameters().new_ToName;
            }

            /*Set To Partylist*/
            if (ToPartyList[0] != null && ToPartyList[0].id != null && ToPartyList[0].id != 'undefined')
                Xrm.Page.getAttribute("to").setValue(ToPartyList);

            /*Regarding Object Id*/
            var regarding = [];
            regarding[0] = {};

            if (Xrm.Page.context.getQueryStringParameters().new_RegardingIdName != null && Xrm.Page.context.getQueryStringParameters().new_RegardingIdName != 'undefined') {
                regarding[0].name = Xrm.Page.context.getQueryStringParameters().new_RegardingIdName;
            }
            if (Xrm.Page.context.getQueryStringParameters().new_RegardingId != null && Xrm.Page.context.getQueryStringParameters().new_RegardingId != 'undefined') {
                regarding[0].id = Xrm.Page.context.getQueryStringParameters().new_RegardingId;
            }
            if (Xrm.Page.context.getQueryStringParameters().new_RegardingIdType != null && Xrm.Page.context.getQueryStringParameters().new_RegardingIdType != 'undefined') {
                regarding[0].entityType = Xrm.Page.context.getQueryStringParameters().new_RegardingIdType;
            }
            if (regarding[0] != null && regarding[0].id != null && regarding[0].id != 'undefined')
                Xrm.Page.getAttribute("regardingobjectid").setValue(regarding);
        }
    },

};
·         In Contact form event when want to open email form, we need to pass these query string parameters which are defined above
var contactScript = {
    openEmail: function () {
       
        var parameters = {};
        /*Custom querystring parameter*/

        parameters["new_ToType"] = Xrm.Page.data.entity.getEntityName();
        parameters["new_ToName"] = Xrm.Page.getAttribute("fullname").getValue();
        parameters["new_ToId"] = Xrm.Page.data.entity.getId(); // current contact Id

        parameters["new_RegardingIdType"] = Xrm.Page.context.getQueryStringParameters().etc;
        parameters["new_RegardingIdName"] = Xrm.Page.getAttribute("fullname").getValue();
        parameters["new_RegardingId"] = Xrm.Page.data.entity.getId(); // current contact Id

        var windowsOptions = {};
        windowsOptions["openInNewWindow"] = true;

        Xrm.Utility.openEntityForm("email",null, parameters,  windowsOptions);
    },
   
};


·         Save all changes and publish.

·         Now when Email Form opened from Contact entity, using Xrm.Utiltiy, we will see To, and Regarding lookup is already set. 




Thursday, October 27, 2016

Get / Set Query string parameters to CRM form.


When using Xrm.Utitliy object to open entity form or Quick create form, sometimes we need to pass query string parameters.
In MS CRM you can enable CRM forms to accept query strings, and you can retrieve those query string parameters in form events.

Set Query string parameters

a.      Go to Entity customization
b.      Open form, where you want to add query strings parameters
c.       Click on Form Properties
d.     In form properties window you will see Parameters tabs.
e.      Add Parameters, which you want to get it, when using openEntityForm or openQuickCreate
f.        When adding parameter need to specify name and data type.



NOTE: In Each parameter name MUST contains at least one underscore (‘_’) character. And name cannot be started with underscore or “crm_”.  Microsoft recommends that you should use solution publisher prefix when defining parameter name, e.g abc_queryString_contactId

g.      We can pass Boolean, Datetime, double, entitytype, Integer, long, PositiveInteger, SafeString, UniqueId, UnsignedInt types of parameters.

Pass Query String parameters to form using openEntityForm or openQuickCreate

openContactForm: function () {
       
        var parameters = {};
        /*Custom querystring parameter*/

        parameters["qryParam_boolean"] = 0; // Boolean value - 0,1, true, false
        var startDate = new Date();
        parameters["qryParam_datetime"] = startDate.format("MM/dd/yyyy"); // date time
        parameters["qryParam_double"] = 1.0; //double
        parameters["qryParam_eType"] = 2; // Entity Type Code
parameters["qryParam_eType"] = Xrm.Page.context.getQueryStringParameters().etc; // Another way to get Entity Type Code
        parameters["qryParam_integer"] = 100;  //Integer
        parameters["qryParam_long"] = 100000; // Long
        parameters["qryParam_positiveinteger"] = 1; // Positive Integer including 0
        parameters["qryParam_safestring"] = "safestring"; //string
        parameters["qryParam_uniqueId"] = Xrm.Page.data.entity.getId(); //GUID
        parameters["qryParam_unsignedInt"] = 1; //unsigned integer


        var windowsOptions = {};
        windowsOptions["openInNewWindow"] = true;

        Xrm.Utility.openEntityForm("new_manufacture",null, parameters,  windowsOptions);
    },

Retrieve Parameters value, when entity form is opened.

To get parameter value, we need to use Xrm.Page.context.getQueryStringParameters()

getQueryStringParamters: function () {
        var booleanParam;
        var datetimeParam;
        var doubleParam;
        var entitytypeParam;
        var integerParam;
        var longParam;
        var positiveintegerParam;
        var safestringParam;
        var uniqueIdParam;
        var unsignedIntParam;


        if (Xrm.Page.context.getQueryStringParameters().qryParam_boolean != null && Xrm.Page.context.getQueryStringParameters().qryParam_boolean != 'undefined') {
            booleanParam = Xrm.Page.context.getQueryStringParameters().qryParam_boolean;
        }
        if (Xrm.Page.context.getQueryStringParameters().qryParam_datetime != null && Xrm.Page.context.getQueryStringParameters().qryParam_datetime != 'undefined') {
            datetimeParam = Xrm.Page.context.getQueryStringParameters().qryParam_datetime;
        }
        if (Xrm.Page.context.getQueryStringParameters().qryParam_double != null && Xrm.Page.context.getQueryStringParameters().qryParam_double != 'undefined') {
            doubleParam = Xrm.Page.context.getQueryStringParameters().qryParam_double;
        }
        if (Xrm.Page.context.getQueryStringParameters().qryParam_eType != null && Xrm.Page.context.getQueryStringParameters().qryParam_eType != 'undefined') {
            entitytypeParam = Xrm.Page.context.getQueryStringParameters().qryParam_eType;
        }
        if (Xrm.Page.context.getQueryStringParameters().qryParam_integer != null && Xrm.Page.context.getQueryStringParameters().qryParam_integer != 'undefined') {
            integerParam = Xrm.Page.context.getQueryStringParameters().qryParam_integer;
        }
        if (Xrm.Page.context.getQueryStringParameters().qryParam_long != null && Xrm.Page.context.getQueryStringParameters().qryParam_long != 'undefined') {
            longParam = Xrm.Page.context.getQueryStringParameters().qryParam_long;
        }
        if (Xrm.Page.context.getQueryStringParameters().qryParam_positiveinteger != null && Xrm.Page.context.getQueryStringParameters().qryParam_positiveinteger != 'undefined') {
            positiveintegerParam = Xrm.Page.context.getQueryStringParameters().qryParam_positiveinteger;
        }
        if (Xrm.Page.context.getQueryStringParameters().qryParam_safestring != null && Xrm.Page.context.getQueryStringParameters().qryParam_safestring != 'undefined') {
            safestringParam = Xrm.Page.context.getQueryStringParameters().qryParam_safestring;
        }
        if (Xrm.Page.context.getQueryStringParameters().qryParam_uniqueId != null && Xrm.Page.context.getQueryStringParameters().qryParam_uniqueId != 'undefined') {
            uniqueIdParam = Xrm.Page.context.getQueryStringParameters().qryParam_uniqueId;
        }
        if (Xrm.Page.context.getQueryStringParameters().qryParam_unsignedInt != null && Xrm.Page.context.getQueryStringParameters().qryParam_unsignedInt != 'undefined') {
            unsignedIntParam = Xrm.Page.context.getQueryStringParameters().qryParam_unsignedInt;
        }
      
    },
Now you can set value to form or add any logic based on passed parameters.