Plugin Extensions: Shorten Your Code

There are some lines of code in plugins and workflows that I've written too many times.

1. Getting an attribute

Before we get an entity's attribute, we always check that the entity first contains the attribute. This is because attempting to access the value of an attribute that doesn't exist throws a NullReferenceException. Here's an example that gets the first name of a contact:

2. Initialising plugin variables

The following code gets the basic objects needed to run a decent plugin. Look how long-winded it is!

How to shorten things: write extension methods

Create a separate, static class called Extensions.cs. Note the namespace your class is in. If it's in a different namespace to your plugins, you must add a using statement at the top of your plugin classes.

Here's an example extension method that allows the simplification of 1. from above:

It can be used as follows. Note that we no longer need to check if an entity contains an attribute.

Here's an extension method that shortens the initialisation of plugin variables:

Here's how we can now initialise the same variables as shown in 2. from above:

Much cleaner!

2 comments:

  1. I love extension methods too - real time saved.
    It's worth noting that you don't need to do the check on GetAttributeValue because it actually does it for you:

    private object GetAttributeValue(string attributeLogicalName)
    {
    if (string.IsNullOrWhiteSpace(attributeLogicalName))
    {
    throw new ArgumentNullException("attributeLogicalName");
    }
    if (!this.Contains(attributeLogicalName))
    {
    return null;
    }
    return this[attributeLogicalName];
    }

    ReplyDelete
    Replies
    1. Superb, thank you for the feedback Scott! I'll update my post.

      Delete