Tuesday, April 13, 2010

The Given Key Was Not Present In The Dictionary

There've been a few times I've come across this error with CRM when writing small plug-ins, more as a test exercise than anything to use in production - yet.

It's always the same scenario too. You write your plugin, maybe a Create message or an Update message, you check the code and you register the DLL and a step. You come to test it, and you get a pop-up with the not so helpful text of "The given key was not present in the dictionary".

At first I found the message very confusing, but I eventually found an explantion for why it was happen (or at least had a vague grasp of the problem that was causing it).

When ever you reference an attribute of a Dynamic Entity, you are using a key/value pair. The key is the name of the attribute, the value is obviously the value of that attribute and a container which holds key/value pairs is called a dictionary.

The error is down to referencing an attribute name that is not available in the dictionary you are looking at. There may be a number of reasons for this, but I think the most common two are: 1) The key (attribute name) has been mistyped in the code; or 2) It's not available in the current message.

I've had this happen in Update Message plugins, because in an Update Message the Dynamic Entity containd in the Target property of the context's InputParameters only contains the attributes on the entity which have changed. If the user did not change the name of the account before they pressed save then "accountname" is not going to be present in an Update Message.

I hope that makes sense, but there's a chance it wont, because like I said I'm still trying to grasp the finer points of it, especially when it comes down to using the InputParameters and the Target property. They are something I've seen in many plug-in tutorials and copied down as gospel, but not really taken the time to sit down and find out what it's for.

Hopefully this post will get you past an error and make you sit down and find out what's actually going on with your context properties too.

No comments:

Post a Comment