Dynamics 365 Utility Methods

Dynamics 365 makes available features and options that makes possible to implement many solutions and requirements without having to write a single line of code (server-side and client-side). However, despite the fact that Dynamics 365 is a very complete and customisable development platform, it still has limits.

Sometimes in some Dynamics 365 implementations, there is the need to write code to deal with validations, integrations, extensions and automations. In those projects, it is common to create and use programmer-defined utility classes to centralize common and often re-usable methods. Most utility classes define these methods under static scope.

In these series of posts, we will be sharing some ready-to-use utility methods that can be added to utility classes.

Method Name GetOrganisationService
Description Get CRM Organisation Service based on CRM ConnectionString.
Dependencies Libraries Methods
  Microsoft.Xrm.Sdk;

Microsoft.Xrm.Sdk.Messages;

Microsoft.Xrm.Tooling.Connector;

Microsoft.Crm.Sdk.Messages;

N/A

 


/// <summary>
/// Get CRM Organisation Service based on CRM ConnectionString.
/// </summary>
/// <param name="crmConnString"></param>
/// <returns></returns>
public static IOrganizationService GetOrgService(string crmConnString)
{
    try
    {
        var connection = new CrmServiceClient(crmConnString);
        var orgService = connection.OrganizationServiceProxy as IOrganizationService;

        var requestResponse = orgService.Execute(new WhoAmIRequest());

        return orgService;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}


Method Name GetOptionSetLabel
Description Get label from a given option set value, from a given option set attribute, from a given entity.
Dependencies Libraires Methods
  Microsoft.Xrm.Sdk;

Microsoft.Xrm.Sdk.Messages;

Microsoft.Xrm.Sdk.Metadata;

N/A

 


/// <summary>
/// Get label from a given option set value, from a given option set attribute, from a given entity.
/// </summary>
/// <param name="orgService"></param>
/// <param name="entityName"></param>
/// <param name="attributeName"></param>
/// <param name="optionSetValue"></param>
/// <returns></returns>
public static string GetOptionSetLabel(IOrganizationService orgService, string entityName, string attributeName, int optionSetValue)
{
    try
    {
    var attReq = new RetrieveAttributeRequest();
    attReq.EntityLogicalName = entityName;
    attReq.LogicalName = attributeName;
    attReq.RetrieveAsIfPublished = true;

    var attResponse = (RetrieveAttributeResponse)orgService.Execute(attReq);
    var attMetadata = (EnumAttributeMetadata)attResponse.AttributeMetadata;

    var result = attMetadata.OptionSet.Options.Where(x => x.Value == optionSetValue).FirstOrDefault();

    if (result != null)
        return result.Label.UserLocalizedLabel.Label;
    else
        return null;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}


Method Name GetOptionSetValue
Description Get value from a given option set label, from a given option set attribute, from a given entity.
Dependencies Libraires Methods
  Microsoft.Xrm.Sdk;

Microsoft.Xrm.Sdk.Messages;

Microsoft.Xrm.Sdk.Metadata;

N/A

/// <summary>
/// Get value from a given option set label, from a given option set attribute, from a given entity.
/// </summary>
/// <param name="orgService"></param>
/// <param name="entityName"></param>
/// <param name="attributeName"></param>
/// <param name="optionSetLabel"></param>
/// <returns></returns>
public static int? GetOptionSetValue(IOrganizationService orgService, string entityName, string attributeName, string optionSetLabel)
{
    try
    {
        var attReq = new RetrieveAttributeRequest();
        attReq.EntityLogicalName = entityName;
        attReq.LogicalName = attributeName;
        attReq.RetrieveAsIfPublished = true;

        var attResponse = (RetrieveAttributeResponse)orgService.Execute(attReq);
        var attMetadata = (EnumAttributeMetadata)attResponse.AttributeMetadata;

        var result = attMetadata.OptionSet.Options.Where(x => x.Label.UserLocalizedLabel.Label == optionSetLabel).FirstOrDefault();

        if (result != null)
            return result.Value.Value;
        else
            return null;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}


Method Name StringifyCrmAttributeValue
Description Return string value from a given attribute from a given record.
Dependencies Libraires Methods
  Microsoft.Xrm.Sdk; GetOptionSetLabel

/// 
<summary>
/// Get string value from a given attribute, from a given record.
/// </summary>
/// <param name="orgService"></param>
/// <param name="record"></param>
/// <param name="attributeName"></param>
/// <param name="attributeDataType"></param>
/// <param name="getDescription">Defines if the method returns the Id or the description. To be used exclusively with Lookup and PickList attributes.</param>
/// <returns></returns>
public static string StringifyCrmAttributeValue(IOrganizationService orgService, Entity record, string attributeName, string attributeDataType, bool getDescription = false)
{
    try
    {
    string stringValue = String.Empty;

    switch (attributeDataType)
    {
        case "Memo":
        case "String":
            stringValue = record[attributeName].ToString();
            break;
        case "Decimal":
            stringValue = ((Decimal)record[attributeName]).ToString();
            break;
        case "Money":
            stringValue = ((Money)record[attributeName]).Value.ToString();
            break;
        case "DateTime":
            stringValue = ((DateTime)record[attributeName]).ToString();
            break;
        case "Integer":
            stringValue = ((Int32)record[attributeName]).ToString();
            break;
        case "Picklist":
            if (getDescription)
            {
                stringValue = GetOptionSetLabel(orgService, record.LogicalName, attributeName, ((OptionSetValue)record[attributeName]).Value);
            }
            else
            {
                stringValue = ((OptionSetValue)record[attributeName]).Value.ToString();
            }
            break;
        case "Boolean":
            stringValue = ((Boolean)record[attributeName]).ToString();
            break;
        case "Lookup":
            if (getDescription)
            {
                stringValue = ((EntityReference)record[attributeName]).Name;
            }
            else
            {
                stringValue = ((EntityReference)record[attributeName]).Id.ToString();
            };
            break;
        case "Uniqueidentifier":
            stringValue = ((Guid)record[attributeName]).ToString();
            break;
        default:
            break;
    }

    return stringValue;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

Contact me on Linkedin : Hugo Goncalves

About Technical Hero: Dimitri 'Reverso Engineero' Chevkov

The Technical Hero of the Dynamics 365 Heroes Team A programming wizard, I was a child prodigy and had hacked into 7 separate government agencies by the time I was 16 years old. Older, wiser, more experienced and seeing the errors of my impetuous youth, I now spends my time helping others to extend their Dynamics platform beyond what was previously thought as the limit. I can rush into developing a solution to a problem which would be better solved using the Dynamics 365 platform capabilities, and am constantly kept in check by Howard.

Leave a Reply