Sunday, June 5, 2011

Microsoft Dynamics CRM 2011 : Retrieve Entiy Record Data by Entity Id


While extending Dynamics CRM, retrieving entity information is a very common programming requirement whether we are working with Forms, SDK Plugins or Workflow Custom Assemblies or ASP.Net extensions. In the following sample code we will retrieve entity information by Entity Id via Jscript (can be used in Entity Forms, CRM HTML web resource etc.) and C # code (can be used with in SDK Plugins, Workflow Custom Assemblies, Asp.Net etc.)
Updated Code for Retrieving Lookup Attribute Values
[Jscript Code]

// Only make changes to this function; you may add this function to Form Onload Event,
// Field OnChange events etc.
function GetDetails() {

    var EntityName, EntityId, AccountNumber, AccountEmailAddress, LookupFieldObject;
    var PrimaryContactLookupId, PrimaryContactLookupName, PrimaryContactLookupType;
    var resultXml;

    LookupFieldObject = Xrm.Page.data.entity.attributes.get('parentcustomerid');

    // If lookup field has value then the code will only run
    if (LookupFieldObject.getValue() != null) {

        //Fetch and place Entity Id (GUID) and Name (String) form lookup field into local variables
        EntityId = LookupFieldObject.getValue()[0].id;
        EntityName = LookupFieldObject.getValue()[0].entityType;

        // Paramter explaination for function call
        // RetrieveEntityById('account', AccountId, 'accountnumber,emailaddress1');

        // 1st paramter requires entity name (not display or schema name) just pass it in a string
        // i.e. for Account entity use 'account' for opportunity entity use 'opportunity'

        // 2nd paramter requires entity Id (GUID Type) field which we have retrieved and stored in
        // AccountId local variable

        // 3rd paramter requires attributes to be retrieved schema name, if thrid attributed is
        // required to be retrieved then use like: i.e. 'accountnumber,emailaddress1,telephone2'

        resultXml = RetrieveEntityById(EntityName, EntityId, 'accountnumber,emailaddress1,primarycontactid');

        // In retrieved XML document check if it has accountnumber attribute
        if (resultXml != null && resultXml.selectSingleNode('//q1:accountnumber') != null) {

            // If XML document has account number attribute then assign to local variable AccountNumber
            AccountNumber = resultXml.selectSingleNode('//q1:accountnumber').nodeTypedValue;

            //Display Account Number Value in a Message Box
            alert("Account Number :" + AccountNumber);

            //If required then use the below code line to set value in field on form
            //Xrm.Page.data.entity.attributes.get('new_myaccountnumber').setValue(AccountNumber);
        }

        // In retrieved XML document check if it has emailaddress1 attribute
        if (resultXml != null && resultXml.selectSingleNode('//q1:emailaddress1') != null) {

            // If XML document has account number attribute then assign to local variable AccountEmailAddress
            AccountEmailAddress = resultXml.selectSingleNode('//q1:emailaddress1').nodeTypedValue;

            alert("Email Address :" + AccountEmailAddress);

            //If required then use the below code line to set value in field on form
            //Xrm.Page.data.entity.attributes.get('new_myemailaddress').setValue(AccountEmailAddress);
        }

          // In retrieved XML document check if it has primarycontactid lookup attribute
        if (resultXml != null && resultXml.selectSingleNode('//q1:primarycontactid') != null) {

            // If XML document has primarycontactid lookup attribute then assign to local variable
            PrimaryContactLookupId = resultXml.selectSingleNode('//q1:primarycontactid').nodeTypedValue;

            // If XML document has primarycontactid lookup attribute then assign to local variable
            PrimaryContactLookupName = resultXml.selectSingleNode('//q1:primarycontactid').getAttribute("name");

            // If XML document has primarycontactid lookup attribute then assign to local variable
            PrimaryContactLookupType = resultXml.selectSingleNode('//q1:primarycontactid').getAttribute("type") ;

            alert("Primary Contact Lookup Id :" + PrimaryContactLookupId);

            alert("Primary Contact Lookup Name :" + PrimaryContactLookupName);

            alert("Primary Contact Lookup Type :" + PrimaryContactLookupType);
           
        }      

    }
}

// Do not make any changes to this function
function RetrieveEntityById(prmEntityName, prmEntityId, prmEntityColumns) {

    var resultXml, errorCount, msg, xmlHttpRequest, arrayEntityColumns, xmlEntityColumns;

    arrayEntityColumns = prmEntityColumns.split(",");

    for (var i = 0; i < arrayEntityColumns.length; i++) {
        xmlEntityColumns += "<q1:Attribute>" + arrayEntityColumns[i] + "</q1:Attribute>";
    }

    var authenticationHeader = Xrm.Page.context.getAuthenticationHeader();

    //Prepare the SOAP message.
    var xml = "<?xml version='1.0' encoding='utf-8'?>" +
    "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'" +
    " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" +
    " xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
    authenticationHeader +
    "<soap:Body>" +
    "<Retrieve xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
    "<entityName>" + prmEntityName + "</entityName>" +
    "<id>" + prmEntityId + "</id>" +
    "<columnSet xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' xsi:type='q1:ColumnSet'>" +
    "<q1:Attributes>" +
    xmlEntityColumns +
   "</q1:Attributes>" +
    "</columnSet>" +
    "</Retrieve></soap:Body></soap:Envelope>";

    //call function to create Soap Request to ms crm webservice
    xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
    xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
    xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
    xmlHttpRequest.send(xml);

    resultXml = xmlHttpRequest.responseXML;

    var errorCount = resultXml.selectNodes('//error').length;

    if (errorCount != 0) {
        var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
        alert("Error Message : " + msg);
    }
    else {
        return resultXml;
    }
}