I've been working with Dynamics CRM 4.0 for a while now, and last week had to write the most complicated workflow I've ever done. It was pretty challenging logic, and gave me a great opportunity to explore parts of the CRM SDK I had never used up until that point.
In the past I had selected specific instances of some entity based on a guid and had no trouble doing so. CRM allows for custom properties added to a base entity, and in this particular case I had to retrieve information from some of these custom properties. However, my standard way of retrieving an object wasn't including these extended custom properties!
It was pretty easy to solve once I got to understand the DynamicEntity object. DynamicEntity can be an instance of any of CRM entity and contains all of the custom properties.
So I wrote my Execute method as follows:
protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
{
try
{
// Get the context service.
IContextService contextService = (IContextService)executionContext.GetService(typeof(IContextService));
IWorkflowContext context = contextService.Context;
// Use the context service to create an instance of CrmService.
ICrmService crmService = context.CreateCrmService(true);
DynamicEntity CaseEntity = GetCase(crmService, context.PrimaryEntityId);
//check if CaseEntity was null
if (CaseEntity == null)
{
//handle
}
//check if CaseEntity has the desired custom property
if (!CaseEntity.Properties.Contains("custom_someproperty"))
{
//handle
}
//get the custom property, let's assume it was a lookup
Lookup MyNewObjectFromTheCustomField = (Lookup)CaseEntity["custom_someproperty"];
//do other stuff
return ActivityExecutionStatus.Closed;
}
}
The code of the GetCase method is pretty straightforward. We will return a DynamicEntity instance that will contain all base and custom properties of the case object we need.
private DynamicEntity GetCase(ICrmService crmService, Guid caseid)
{
//build up the query
QueryByAttribute query = new QueryByAttribute();
query.EntityName = EntityName.incident.ToString();
query.ColumnSet = new AllColumns();
query.Attributes = new String[] { "mycustomproperty" };
query.Values = new Object[] { caseid };
//build up the request
RetrieveMultipleRequest request = new RetrieveMultipleRequest();
request.ReturnDynamicEntities = true;
request.Query = query;
//execute
RetrieveMultipleResponse response = (RetrieveMultipleResponse)crmService.Execute(request);
if (response.BusinessEntityCollection.BusinessEntities.Count == 1)
{
DynamicEntity entity = (DynamicEntity)response.BusinessEntityCollection.BusinessEntities[0];
return entity;
}
else
{
return null;
}
}