Monday, September 9, 2019

Convert a Dynamics Enum to a C# generic collection

When you need to consume a Dynamics Ax Enum type in a .Net project you should make your project independent from the internal structure of Dynamics and certainly you do not want to create a static copy of your Dynamics Enum in your .Net project.

In order to achieve that I taught to expose the Dynamics Enum as a generic List.

To do that and adhere to the DRY principle (do not repeat yourself) I made an extension method in C# that converts any Enum in a generic list.

first you need to create a POCO class, a data transfer object

namespace MydDynamicsIntegration.Models
{
    public class AxEnumDefinition
    {
        public int Value { get; set; }
        public string Name { get; set; }
        public string Label { get; set; }
    }
}

now here the extension method

using System;
using System.Collections.Generic;
using MydDynamicsIntegration.Models;

namespace MydDynamicsIntegration.DynamicsCommon
{
    public static class AxGetValuesExtensions
    {
        public static List<AxEnumDefinition> FromAxToColl<T>(this T eEnum) where T : struct, IConvertible
        {
            var enumDefinitions = new List<AxEnumDefinition>();

            Type t = typeof(T);

            if (!t.IsEnum)
                throw new ArgumentException("T must be an enumerated type");

            try
            {
                SysDictEnum sysDictEnum = SysDictEnum.newName(t.Name);

                for (int i = 0; i < sysDictEnum.values(); i++)
                {
                    enumDefinitions.Add(new AxEnumDefinition()
                    {
                        Value = sysDictEnum.index2Value(i),
                        Name = sysDictEnum.index2Name(i),
                        Label = sysDictEnum.index2Label(i)
                    });
                }
            }
            catch
            {
                //
            }

            return enumDefinitions;
        }
    }
}

now you can use it like this

use example: 
return new HcmDiscussionStatus().FromAxToColl();
OR to a specific value
Status = new AxEnumDefinition()
   {
      Value = Global.enum2int(discussion.status),
      Name = Global.enum2Value(discussion.status),
      Label = discussion.status.FromAxToColl().Where(x => x.Value == Global.enum2int(discussion.status)).Select(x => x.Label).FirstOrDefault()
   }
OR 
Status = discussion.status.FromAxToColl().FirstOrDefault(x => x.Value == Global.enum2int(discussion.status))

No comments:

Post a Comment