Primer on CRM Web Services Part 2 - Dynamic Entities

When using the CRM Web Services, there are times when you need to work with custom entities that aren't described in the current WSDL that you have. The DynamicEntity lets you program against types that you don't have the full description in the WSDL. This can be very helpful when you don't have access to fetch the systems current WSDL files.
Let's look at a code snippet to do this.

Here at the steps .
1. Create all the attribute values
2. Create Dynamic Entity
3. Set the attribute properties
4. Create the Target
5. Execute the Request

I'll show how to create a rocket entity and associate an existing account id to the new entity. The CRM SDK support a variety of property type objects. Be sure to use the correct object type with the definition of the attribute. Mismatching this is a common error. I'll save you some time with this tip: Use LookUpProperty instead of Guid type when relating entities together. Even though the value you set will be a GUID, it only works with the LookupProperty object.

// Create Properties
LookupProperty accountid = new LookupProperty();
accountid.Name = "acme_accountid";
accountid.Value = new Lookup();
accountid.Value.Value = new Guid("260FB27F-25E6-DC11-BEDA-0013210AC0BE");
accountid.Value.type = EntityName.account.ToString();

StringProperty name = new StringProperty();
name.Name = "acme_RocketName";
name.Value = "Titian";

DateTime userTime = new DateTime();
userTime = dtExpDate;

CrmService.CrmDateTime LaunchDate = new CrmService.CrmDateTime();
LaunchDate.Value = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:s}", userTime);
CrmDateTimeProperty LaunchDate = new CrmDateTimeProperty();
LaunchDate.Name = "acme_LaunchDate";
LaunchDate.Value = LaunchDate;

// Create the DynamicEntity object.
DynamicEntity AcmeEntity = new DynamicEntity();

// Set the name of the entity type.
AcmeEntity.Name = "acme_rocket";

// Set the properties
KeyEntity.Properties = new Property[] { name, accountid, LaunchDate };

// Create the target.
TargetCreateDynamic targetCreate = new TargetCreateDynamic();
targetCreate.Entity = KeyEntity;

// Create the request object.
CreateRequest create = new CreateRequest();

// Set the properties of the request object.
create.Target = targetCreate;

// Execute the request.
CreateResponse created = (CreateResponse)crmService.Execute(create);

That's it. Now we have an instance of the entity type acme_rocket that is related to the account id. Don't forget to check out the SDK for complete samples and descriptions of all the property objects. Also, if you get errors, the first to check is that the attribute type matches the property object that you are using.

-cheers
Jon