C# - A ‘dynamic’ keyword for CRM

Vitalii Symon, 24 December 2010

C# - A ‘dynamic’ keyword for CRM

With every ‘next’ version of Microsoft .NET Framework we get more and more features and as result – more chances to shoot our own leg.  Not so long ago, var keyword was discussed by the community as potentially dangerous and now we have one more keyword – dynamic - which gives some more freedom and finally allows us to produce an unlimited number of runtime errors as old school Memory Access Failure.

But, we are going to get profit from this feature and figure out how to use it to make programming for Dynamics CRM easier. A bit about the feature – it allows binding methods, properties and fields dynamically to objects, without any compile – stage check. So basically you can write a class which will interpret a method or a property name as an entity of some other nature – e.g. registry node or CRM entity.

To make that work, inherit your class from DynamicObject and overload this TryGetMember  method. Like this:

    class CrmConnection : DynamicObject
    {
        object connectionDetails ;
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            // smart code here
        }
    }

That way you can create an object which will present the entity and will carry connection information as well. Do the same for attribute:

    class CrmEntity : DynamicObject
    {
        public CrmConnection Connection { get; set; }
        public string EntityName { get; set; }
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = new CrmAttribute { Entity = this, Attribute = binder.Name };
            return true;
        }
    }
    class CrmAttribute : DynamicObject
    {
        public CrmEntity Entity { get; set; }
        public string Attribute { get; set; }
        public object Get()
        {
            // here we have name of entity, name of attribute and connection details - enough to make a query to CRM
        }
    }

And expression MyCrmConnection.account[1].mag_myattribute.Get() is translated to FetchXml instantly with no need to have those properties (account, mag_attribute) existing anywhere – they will be bound on the fly.

Usage

This feature will not handle mistakes (e.g. typos) at compilation time, so if you have deleted the mag_nobodyuses attribute from Dynamics CRM ages ago, but some very smart user  has found a dialog requesting that entity – exception or malfunction is almost guaranteed. You have to be extremely careful when using this feature, no one wants to shoot their own leg. Happy coding!