Search code examples
javasoapdynamics-crm-2011dynamics-crm-online

Create Product in MS Dynamics CRM 2011 via SOAP/Java


I generated all required java classes from crm.dynamics.com/XRMServices/2011/Discovery.svc?wsdl and crm.dynamics.com/XRMServices/2011/Organization.svc?wsdl schemas.

I authenticated in CRM with LiveId.

Now i need to create Product in Product Catalog. Here is code for this:

Entity newEntryInfo = new Entity();

AttributeCollection collection = new AttributeCollection();
addAttribute(collection, "name", "Tama Starclassic Performer");
addAttribute(collection, "productnumber", "1");

addAttribute(collection, "price", createMoney("100.0"));
addAttribute(collection, "isstockitem", Boolean.TRUE);
addAttribute(collection, "statuscode", 1);

newEntryInfo.setAttributes(collection);
newEntryInfo.setLogicalName("product");

Guid productGuid = serviceStub.create(newEntryInfo);

private void addAttribute(AttributeCollection collection, String key, Object value) {
    KeyValuePairOfstringanyType values = new KeyValuePairOfstringanyType();
    values.setKey(key);
    values.setValue(value);

    collection.addKeyValuePairOfstringanyType(values);
}

Execution shows error "The unit schedule id is missing."

Looks like i need to provide "Unit Group" and "Default Unit" for new product.

Question: How can i set those values? Should i use RelatedEntities (how create it) or Attributes (how create it)


Solution

  • As it is a lookup on the form, you should be able to set the value with an EntityReference.

    Using your methods that would be:

    addAttribute(collection, "fieldName", new EntityReference("entityName", new Guid("id"))
    

    Where:

    • fieldName is the schema name of the field you want to populate
    • entityName is the schema name of the entity you want to populate the field with
    • id is the Guid of a record which is the same type as entityName.

    To put that into a context (where I happen to know the schema names off the top of my head).

    //Create a new contact first
    Entity contact = new Entity("contact");
    contact["lastname"] = "Wood";
    
    Guid contactId = service.Create(contact);
    
    //Create an incident/case which links to that new contact
    Entity incident = new Entity("incident");
    incident["customerid"] = new EntityReference("contact", contactId)
    service.Create(incident)
    

    As a side is there a particular reason you are using a such a long winded code style? The entity class has an index which links to underlying attribute dictionary. Its a bit more straight forward.

    If you are looking for more examples check out: Use the Late Bound Entity Class in Code