ttajic
5/31/2016 - 8:54 AM

EntityExtensions

EntityExtensions

using System;
using System.Linq;
using Microsoft.Xrm.Sdk;

namespace Adacta
{
    public static class EntityExtensions
    {
        public static void ToLocalTime(this Entity entity)
        {
            var newDictionary = entity.Attributes.ToDictionary(entry => entry.Key,
                                               entry => entry.Value);

            foreach (var i in newDictionary)
            {
                if (i.Value is DateTime)
                {
                    var dt = (DateTime)i.Value;
                    entity.Attributes[i.Key] = dt.ToLocalTime();
                }
            }
        }

        private static T GetValueOrDefault<T>(object obj)
        {
            if (obj is T)
                return (T)obj;
            else
                return default(T);
        }

        public static T GetAttributeValueEx<T>(this Entity entity, string name)
        {
            if (!entity.Attributes.ContainsKey(name))
                return default(T);

            object obj = entity.Attributes[name];
            if (obj is AliasedValue)
            {
                return GetValueOrDefault<T>(((AliasedValue)obj).Value);
            }
            else
            {
                return GetValueOrDefault<T>(obj);
            }
        }

        public static int? GetAttributeOptionSetValue(this Entity entity, string name)
        {
            var optionSet = entity.GetAttributeValueEx<OptionSetValue>(name);
            if (optionSet == null)
                return null;

            return optionSet.Value;
        }

        public static R SelectSafe<T, R>(this Entity entity, string name, Func<T, R> select)
        {
            var intermediateResult = entity.GetAttributeValueEx<T>(name);
            if (intermediateResult == null)
                return default(R);

            return select(intermediateResult);
        }
    }
}