Auto-Populating a Name field

When using MSCRM I have often come across the requirement for a linking or relationship entity that associates two core entities together – most often when we want a ‘Organisation Relationship’ or ‘Team Role’ style many-to-many relationship that then needs to contain a number of fields to define the relationship meaning we are unable to use the standard Customer Relationship functionality in MSCRM.

For creating a custom entity to manage this relationship, MSCRM will always force us to have a Name field to identify records of this entity type from each other. We must have this field in place and populated for MSCRM to work correctly (the field can be made non-required and left blank, however this poses problems for Lookups and other core MSCRM logic) however this field has no real-world meaning to a user adding the relationship between Organisations – forcing the user to fill in an unwanted field.

Typically we could use a simple piece of form-scripting to populate this field for the user based on some of the other information given for the relationship. However if we imagine that these relationships may be automatically created by Data Migration or internal system logic, this piece of form-scripting will not fire and so no name field would be given.

In this instance it is often helpful to use a simple Pre-Create/Pre-Update plugin to automatically populate the Name field based on one of the relationships involved, such that with the Plugin logic taking place server-side a value for the Name will always be populated.

For these circumstances, the following is a very simple set of example code for a Pre Plugin that will automatically populate a Name field based on a particular relationship within the custom entity:

public class AutoName : IPlugin
{
    const string LOOKUPENTITY = "account";
    const string LOOKUPENTITY_NAME = "name";

    const string ENTITY = "new_relationship";
    const string LOOKUPFIELD = "new_organisationid";
    const string NAMEFIELD = "new_name";

    public void Execute(IPluginExecutionContext cxt)
    {
        try
        {
            DynamicEntity targetMessage;
            string typeName;

            #region Get Target
            // Check if the input parameters property bag contains a target
            // of the create operation and that target is of type DynamicEntity.
            if (cxt.InputParameters.Properties.Contains("Target") &&
               cxt.InputParameters.Properties["Target"] is DynamicEntity)
            {
                // Obtain the target business entity from the input parmameters.
                targetMessage = (DynamicEntity)cxt.InputParameters.Properties["Target"];

                typeName = targetMessage.Name;

                if (typeName != ENTITY)
                {
                    // plugin is valid for this entity
                    throw new Exception("This instance of the AutoName Plugin is not valid for the '" + typeName + "' entity type");
                }

            }
            else
            {
                throw new Exception("No Target Entity in Plugin Context");
            }
            #endregion

            #region Create instance of CRM Methods class to invoke any Data Access requests to/from MSCRM
            PluginCRMMethods crmMethods = null;
            if (cxt.InvocationSource == 0)
            {
                // Parent Pipeline
                crmMethods = new PluginCRMMethods(cxt.CreateCrmService(true));
            }
            else
            {
                throw new Exception("Unknown Plugin Invocation Source " + cxt.InvocationSource.ToString() + "");
            }
            #endregion

            #region Business Logic
            Guid lookupEntityId = Guid.Empty;

            if (targetMessage.Properties.Contains(LOOKUPFIELD))
            {
                Microsoft.Crm.Sdk.Lookup lookupField = (Microsoft.Crm.Sdk.Lookup)targetMessage.Properties[LOOKUPFIELD];
                lookupEntityId = lookupField.Value;
            }

            if (!(lookupEntityId.Equals(Guid.Empty)))
            {
                string newName = crmMethods.GetName(LOOKUPENTITY_NAME, LOOKUPENTITY, lookupEntityId);

                if (targetMessage.Properties.Contains(NAMEFIELD))
                {
                    targetMessage.Properties[NAMEFIELD] = newName;
                }
                else
                {
                    Microsoft.Crm.Sdk.StringProperty nameField = new StringProperty();
                    nameField.Name = NAMEFIELD;
                    nameField.Value = newName;
                    targetMessage.Properties.Add(nameField);
                }
            }
            #endregion

        }
        catch (Exception ex)
        {
            string errMessage = "AutoName.Execute (" + ex.Message + ")";
            throw new Exception(errMessage);
        }
    }
}

One Response to Auto-Populating a Name field

  1. I do not even understand how I finished up right here, but I believed this post was once great. I do not know who you might be but certainly you are going to a famous blogger should you are not already. Cheers!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s