Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Design Pattern for writing CRM 2011 Plugins

Due to complex requests provided by customers, sometimes my code get's messy. I take time to read and understand what I've written since I last worked on it but it takes time.

I was wondering if anyone has implemented a good design pattern which saves time and makes code more organized and readable etc.

like image 601
Anwar Avatar asked Jun 19 '12 08:06

Anwar


1 Answers

Having a base plugin that implements IPlugin is a good step in the right direction. It's Execute function could pass in the IServiceProvider as well as your dataContext or OrganizationService into an abstract onExecute method, which is wrapped in a try catch with a virtual error handler method. This would eliminate a lot of repetitive boilerplate code...

EDIT 1

Added code example showing an abstract OnExecute and a virtual error handler:

public abstract class PluginBase : IPlugin
{

    public void Execute(IServiceProvider serviceProvider)
    {
        try
        {
            OnExecute(serviceProvider);
        }
        catch (Exception ex)
        {
            bool rethrow = false;
            try
            {
                OnError(ex);
            }
            catch
            {
                rethrow = true;
            }

            if (rethrow)
            {
                throw;
            }
        }
        finally
        {
            OnCleanup();
        }
    }

    // method is marked as abstract, all inheriting class must implement it
    protected abstract void OnExecute(IServiceProvider serviceProvider);

    // method is virtual so if an inheriting class wishes to do something different, they can
    protected virtual void OnError(Exception ex){
        // Perform logging how ever you log:
        Logger.Write(ex);
    }

    /// <summary>
    /// Cleanup resources.
    /// </summary>
    protected virtual void OnCleanup()
    {
        // Allows inheriting class to perform any cleaup after the plugin has executed and any exceptions have been handled
    }
}

Edit 2

I have a plugin base defined in DLaB.Xrm (on Nuget) in the DLaB.Xrm.Plugin Namespace that allows handles a lot of great things for you. Here is an example plugin class showing you how to use it.

like image 71
Daryl Avatar answered Nov 04 '22 15:11

Daryl