Fetch the ObjectTypeCode based on EntityName

Not a very rocket science, but just something again that I don't want to type over and over again. So here's a piece of code that helps you to fetch the ObjectTypeCode based on the EntityName for CRM 3.0:

private int GetObjectTypeCode (string entityName)
{
CrmMetaDataService.MetadataService metadataService = new CrmMetaDataService.MetadataService();
metadataService.Credentials = System.Net.CredentialCache.DefaultCredentials;
EntityMetadata entityData = metadataService.RetrieveEntityMetadata(entityName, EntityFlags.EntityOnly);
return entityData.ObjectTypeCode;
}


For CRM 4.0 this would be (thanks for the comment Pratima):
private int GetObjectTypeCode (string entityName)
{
CrmMetaDataService.MetadataService metadataService = new CrmMetaDataService.MetadataService();
metadataService.Credentials = System.Net.CredentialCache.DefaultCredentials;
EntityMetadata entityData = metadataService.RetrieveEntityMetadata(entityName, EntityFlags.EntityOnly);
return entityData.ObjectTypeCode.Value;
}


Have fun copy pasting :)

6 comments:

Anonymous said...

Hi Ronald, Do you have a javascript version for getting object type code? Thanks!!!

Anonymous said...

Try using crmForm.ObjectTypeCode

Anonymous said...

Hi Ronald, but the above code will work only on load of that entities edit.aspx page...
What if we want it before hand??
Thanks

Ronald Lemmen said...

This code will work in any asp.net C# application. The code will request the CRM Metadata webservice and will get the otc based on the entityname. Since it is just a webservice call, it will work from every piece of code which has access to the CRM Metadata webservice.

With kind regards,
Ronald

Anonymous said...

for anonymous, you can have a pure javascript function ds_getObjectTypeCode at :
http://www.datasurf.fr/BlogTechnique/Lists/Billets/ViewPost.aspx?ID=23

Pratima said...

Hello Ronald,
Thank you for the post and code. It is really a very nice post for getting the entity type code. One little correction is that the last return statement should be "return entityData.ObjectTypeCode.Value;" to match with the return type Int of the function. Just to let you know so that to make your blog a more cleaner.

Thanks for the help.
Pratima.