Thursday, May 31, 2007

CRM 3.0: Converting DynamicEntity to a Core Entity

Microsoft was very kind. They gave the us the power of the DynamicEntity. Very handy. They also give us the hard-typed "core" entity objects.

In the case of callouts core entities are not used and only dynamic entities are passed to the callout functions. Working with DynamicEntities though can be a pain, especially when it comes to changing one field and updating the record back in CRM. Since there is no direct access to a specific field, if you want to update a field you need to step through each of the Properties on the DynamicEntity until you find the one you want. Not real efficient if you ask me.

So, this is where having a hard-typed "core" entity comes in handy. But how do you convert? EASY! Well, sorta easy. You see, MS provided a great little code snippet in the CRM SDK for doing such a conversion. It's right here.

However, there is one little problem with this.

So I started to play with this by creating a real simple test app and then retrieving an account DynamicEntity:

tempService.Url = @"http://danubecrm:5555/MSCRMServices/2006/crmservice.asmx";
tempService.Credentials = new System.Net.NetworkCredential("administrator","pass@word1","crmdomain");
RetrieveRequest getEntity = new RetrieveRequest();
TargetRetrieveDynamic target = new TargetRetrieveDynamic();
target.EntityId = new Guid("f0705cff-1e0f-dc11-99e2-0003ff2689b7");
target.EntityName = "account";
getEntity.Target = target;
getEntity.ColumnSet = new AllColumns();
getEntity.ReturnDynamicEntities = true;
RetrieveResponse response = (RetrieveResponse) tempService.Execute(getEntity);
DynamicEntity tempDynamicEntity = (DynamicEntity)response.BusinessEntity;

And then I fed it into the Convert function. CRASH!

It turns out that the DynamicEntity comes back with the StateCode field being a "StateProperty" type. However, on the account object the StateCode field is an AccountStateInfo type. When the reflection methods tried to write the String value that came from the StateProperty.Value, it crashed cause there is no implicit converstion between a String and a AccountState object.

So I modified the code conversion routines to ignore this field. I'm sure there is a better solution but right now there is a project to get done and I don't need to know the StateCode of the account to get it done.

No comments: