As many of you who work with development in Microsoft CRM know, callouts is a great tool. Lots of different tasks can be left to be handled by callouts and they are even run when offline data is resynced to the main system. However, a common problem when working with PostUpdate callouts is that the code wants to update the object that created the callout, hence executing the calloutcode again, which might result in an endless recursion.
I recently ran into this problem working at a customer of mine, and found a nice generic way of solving it using the thought behind the design pattern object factory or single instance.
I guess you want some code! Well, the basis of this solution is to have a static instance of a collection that keeps track of if a certain key just has been run. I use the collection StringCollection. It is simple, and just what I needed in this case:
static System.Collections.Specialized.StringCollection justtreated;
Then I created a method that is supposed to return false the first, third, fifth… time it is called and true every second, fourth, sixth… time it is called with a certain key.
bool JustDone(string key)
if (justtreated == null)
justtreated = new System.Collections.Specialized.StringCollection();
The method is not very complicated. First off, it makes sure that the static variable has been created. Then it checks if it can find the key string in the string collection. If it can it will remove it and then return true. If it cannot find the key, it will add it to the collection and return false.
Since, this method is working with a static variable that will remain in memory between instantiations of the class, hence the data will remain between PostUpdate calls.
Then in the beginning of the PostUpdate method just call JustDone() with the object key (or some other unique key) and if it is true, just “return”.