Setting Entity State in Dynamics CRM 2011

Setting Entity State in Dynamics CRM 2011
I had an interesting challenge recently.

As part of a Credit Card Payment Solution we are working on, I was trying to set the Invoice State.

According to the MSDN documentation, all you need to do is set the Status Code = 100001 and the State Code = 2.

Eg:


Guid invoiceID = new Guid("Existing Invoice Guid");
IOrganizationService orgService = OrgServiceFactory.GetInstance();

orgService.BeginRetrieve("invoice", invoiceID, new ColumnSet(new string[] { "invoiceid", "statecode", "statuscode" }), (result) =>
{
    var fetchResp = orgService.EndRetrieve(result);

    var statecodeAttrib = fetchResp.Attributes.Single(a => a.Key == "statecode");
    OptionSetValue statecode = (OptionSetValue)statecodeAttrib.Value;
    statecode.Value = 2; 


    var statuscodeAttrib = fetchResp.Attributes.Single(a => a.Key == "statuscode");
    OptionSetValue statuscode = (OptionSetValue)statuscodeAttrib.Value;
    statuscode.Value = 100001;

    orgService.BeginUpdate(fetchResp, (updateResult) =>
    {
        /* Web Exception thrown here */
        orgService.EndUpdate(updateResult);
        Console.Write("");
    }, orgService);

}, orgService);

When I did this, I was getting a “NotFound” exception.

So I asked this on Stackoverflow.  Turns out in CRM 2011, you need to use the SetState message.

Digging a little further, the SDK has a good example of how to take an Opportunity to a Won Order, to a Sales Order to an Invoice.

Illustration courtesy of Jon Watson.