Mavnn's blog

Stuff from my brain

We're running Cloud Native .NET in Brighton, 26th-27th April 2018. High quality training for building .NET Core, distributed, production ready systems.

Dynamics and Extension Methods

Filed under: I should have thought of this months ago…

This is a particularly geeky post, mostly for the benefit of a work college (hi Caroline!) who's going to start seeing this appearing in some of our code base, but I thought it might appeal to some other people as well.

When coding against Microsoft Dynamics CRM 4.0, it's frequent that you end up having to use 'Dynamic Entities' (mostly for custom data types you've added to the system). You basically get access to these as a hash table with string key in your code, e.g.:

    object personName = dynamicEntity["ccc_personname"];

Great, except the compiler doesn't know the type of personName. So:

    string personName = (string)dynamicEntity["ccc_personname"];

Except that for everything apart from strings, the Dynamic SDK wraps values in a property type:

    bool personNice = ((CrmBoolean)dynamicEntity["ccc_personnice"]).Value;

Except that CrmBoolean can be null, but isn't Nullable. There are also other fiddly details to account for. It all gets pretty verbose, pretty annoying, and very error prone very quickly.

So, without further ado: DynamicEntity extension methods that return a strongly typed result, and play nicely with the ?? operator.