Originally published at http://goo.gl/C1n3Hw If you have worked with the Dynamics CRM 2011 SDK you are probably very familiar with the Request/Response model messages in Microsoft.Crm.Sdk.Messages. As a developer trying to write good code I always want to wrap any service call in a Try/Catch statement to provide proper error handling. Another goal is to keep the code as neat as possible for when I – or someone else – has to go back and read it. Wrapping calls in Try/Catch statements increases the total lines of code it takes to implement functionality and makes the code more difficult to read. Recently I was working on a project where I had several of these calls in a row: Execute a request, process the response, build a new request, execute, etc. etc. While I was looking at the code I realized that my catch routine was basically the same (format a message for the user and exit out of the program – in addition to sending a number of execution details to the tracing service). Since the code was getting very long, my first thought was to refactor each of these calls into its own method. While this approach would make my code a bit cleaner, it was still somewhat limited in value. After thinking about the problem a bit more, I decided this would be a perfect opportunity to implement generics, extension methods, and delegates. If you are unfamiliar with any of these topics, here is a super quick introduction: - Generics allow us to create a method without having to know all the input types or the response type thus allowing the developer to specify them when calling the method. Extension methods allow us to create static methods against an existing class without having to inherit to a new class thus we do not disturb any code already relying on the class we want to extend. Delegates let us take a method (that matches the specified signature) and pass it as a variable. You can find out more about each of these concepts in the MSDN documentation links provided. Before we get too far into the details we should review the issue we are trying to resolve. Here is a very basic CRM plug-in that executes a WhoAmI request and gets a WhoAmI response. As I count it there are 6 statements with the try/catch but not including the PluginSetup (see my previous post athttp://goo.gl/lEaa9), to complete the request. It may not seem like a lot, but in the real-world those calls also have logging and the request probably has actual properties that need to be set. No matter what request message you use the basic pattern will remain the same. public void Execute(IServiceProvider serviceProvider) { var p = new PluginSetup(serviceProvider); var req = new WhoAmIRequest(); WhoAmIResponse response = (WhoAmIResponse)p.Service.Execute(req);
...