{ADVANCED CODE TIP}My take on the Key not found exception in Dynamics CRM Plugins

Many times we have been there that we get the exception from our plugins called “The Given key was not found”.

The problem with Dictionary collection is that it doesn’t give the key name when it is not found.

The reasoning which I read on different blog posts, forums and Microsoft is key, value pair can be any type.

So, key name is not given in the exception.

clip_image001

But I wanted to have the key name in the plugin log.

I spent many weeks with this exception in my CRM online project and trying to understand how this can be custom built.

So, I have implemented this change on the plugins:

     string[] Cols = { “name “,“accounttype “};

     Object outValue;

            var fieldsMisssing = string.Empty;

            //Do tracing for key not found exception

            foreach(string str in Cols)

            {

                if(!entity.Attributes.TryGetValue(str, out outValue))

                {

                    fieldsMisssing += str + “,”;

                }

            }

 

            fieldsMisssing = fieldsMisssing.TrimEnd(‘,’);

 

            if (fieldsMisssing != string.Empty)

            {

                tracingService.Trace(“Following keys were not found: “ + fieldsMisssing);

            }

 

The result is I have a log in my Plugin trace whenever there are missing keys (Under Settings-> Plug-in Trace logs):

clip_image001[8]

Hope it helps and Happy CRMing!