Monday, November 2, 2009

Retrieve EntityTypeCode on Entity name

When customizing MS CRM you will sometimes need the EntityTypeCode (ETC) of a certain entity. The problem is that the ETC for custom entities isn’t always the same for a specific entity in different CRM environments. So the ETC for let’s say ‘new_project’ may be different in a test-environment than in a production-environment. This means that when using ETC’s in your (javascript) customizations, you will have to check and if necessary change the ETC in two places.

To overcome this problem, you can make use of a generic javascript that retrieves the ETC from Microsoft Dynamics CRMs Metadata. The first part is a generic function that is used to access the MS CRM metadata webservice.

QueryMetadataService = function(request) {
var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");"POST", "/mscrmservices/2007/MetadataService.asmx", false);
xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlhttp.setRequestHeader("SOAPAction", "");
var soapMessage = "<?xml version='1.0' encoding='utf-8'?>" +
"<soap:Envelope xmlns:xsi='' " +
"xmlns:xsd='' xmlns:soap=''>" +
"<soap:Header>" +
"<CrmAuthenticationToken xmlns=''>" +
"<AuthenticationType xmlns=''>" + AUTHENTICATION_TYPE + "</AuthenticationType>" +
"<OrganizationName xmlns=''>" + ORG_UNIQUE_NAME + "</OrganizationName>" +
"<CallerId xmlns=''>00000000-0000-0000-0000-000000000000</CallerId>" +
"</CrmAuthenticationToken>" +
"</soap:Header>" +
"<soap:Body><Execute xmlns=''>" + request+ "</Execute></soap:Body>" +
return xmlhttp.responseXML;

Now to call this function to access MS CRMs Metadata webservice and retrieve the ETC based on the entityname. For this, you can call the next javascript function:

GetEntityTypeCode = function(entityName) {
    var request = "<Request xsi:type='RetrieveEntityRequest'>" +
        "<MetadataId>00000000-0000-0000-0000-000000000000</MetadataId>" +
        "<EntityItems>EntityOnly</EntityItems>" +
        "<LogicalName>" + entityName + "</LogicalName>" +
        "<RetrieveAsIfPublished>true</RetrieveAsIfPublished>" +
    var result = QueryMetadataService(request);
    var entityTypeCode = result.selectNodes("//EntityMetadata/ObjectTypeCode")[0].text;

For Example, if you want to retrieve the ETC of ‘new_project’, just make sure the two functions shown before are on the OnLoad of your CRM Form and call the function like this: 
var projectEtc = GetEntityTypeCode("new_project");

This will allow you to write your code only once, without worrying whether or not you have the right ETC in your scripts.

My next post will be an example on how to use this in real life customizing.


P.S. The first function (QueryMetadataService) I found at the CustomerEffective blog and inspired me to create the second function. You can some other examples on what you can retrieve using the metadataservice on their blog.

No comments:

Post a Comment