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.

Retrieving the Text of an OptionSet in Silverlight

I’ve been pulling my hair out over this.

 

If you look at the Dynamics CRM 2011 SDK, you can see how to get an Entity using FetchXML:

Using FetchXML, you can get to an entity like this:


string fetchXML = "<fetch mapping='logical'>";
fetchXML += "<entity name='account'><all-attributes/>";
fetchXML += "</entity></fetch>";

IOrganizationService orgService = OrgServiceFactory.GetInstance();
orgService.BeginRetrieveMultiple(new FetchExpression() { Query = fetchXML }, EntityGet_callback, orgService);

And the callback:


public void EntityGet_callback(IAsyncResult ar)
{
   IOrganizationService orgservice = ar.AsyncState as IOrganizationService;
   var fetchResp = orgservice.EndRetrieveMultiple(ar);
    var entities = fetchResp.Entities;
    foreach (var entity in entities)
    {
        var email = helper.GetValue(entity, "email");
    }
}

 

Nothing fancy in the helper method:


public static object GetValue(Entity entity, string name)
{
    if (entity.Attributes.ContainsKey(name))
    {
        return entity.GetAttributeValue
&amp;nbsp;
    }
    return null;
}

 

If I wanted to get the Address 1 Type, I would use:


helper.GetValue(entity, "address1_addresstypecode");

Unfortunately this returns the value (0, 1, 2…) Not the string.

The answer is the Entity.FormattedValues.

Eg


entity.GetAttributeValue

With thanks to a post on Sayantan Samanta’s blog.