internal static Dictionary <string, MemberInfo> GetEnumMembers(Type type)
        {
            bool hasDataContract = GetDataContractAttribute(type) != null;

            FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Static);
            Dictionary <string, MemberInfo> members = new Dictionary <string, MemberInfo>(fields.Length);

            foreach (MemberInfo memberInfo in fields)
            {
                if (hasDataContract)
                {
                    EnumMemberAttribute enumAttribute = GetAttribute <EnumMemberAttribute>(memberInfo);
                    if (enumAttribute != null)
                    {
                        string enumName = enumAttribute.Value;
                        if (String.IsNullOrEmpty(enumName))
                        {
                            enumName = memberInfo.Name;
                        }
                        members.Add(enumName, memberInfo);
                    }
                }
                else
                {
                    members.Add(memberInfo.Name, memberInfo);
                }
            }
            return(members);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// The enum attribute value.
        /// </summary>
        /// <param name="enumEntity">Enum entity.</param>
        /// <returns></returns>
        internal static string GetEnumAttributeValue(Enum enumEntity)
        {
            FieldInfo           fieldInfo = enumEntity.GetType().GetField(enumEntity.ToString());
            EnumMemberAttribute attribute = fieldInfo.GetCustomAttributes(typeof(EnumMemberAttribute), true).FirstOrDefault() as EnumMemberAttribute;

            return(attribute != null ? attribute.Value : enumEntity.ToString());
        }
        public JsonStringEnumMemberConverter(JsonNamingPolicy?namingPolicy, bool allowIntegerValues, Type?underlyingType)
        {
            Debug.Assert(
                (typeof(T).IsEnum && underlyingType == null) ||
                (Nullable.GetUnderlyingType(typeof(T)) == underlyingType),
                "Generic type is invalid.");

            _AllowIntegerValues = allowIntegerValues;
            _UnderlyingType     = underlyingType;
            _EnumType           = _UnderlyingType ?? typeof(T);
            _EnumTypeCode       = Type.GetTypeCode(_EnumType);
            _IsFlags            = _EnumType.IsDefined(typeof(FlagsAttribute), true);

            string[] builtInNames  = _EnumType.GetEnumNames();
            Array    builtInValues = _EnumType.GetEnumValues();

            _RawToTransformed = new Dictionary <ulong, EnumInfo>();
            _TransformedToRaw = new Dictionary <string, EnumInfo>();

            for (int i = 0; i < builtInNames.Length; i++)
            {
                Enum  enumValue = (Enum)builtInValues.GetValue(i);
                ulong rawValue  = GetEnumValue(enumValue);

                string              name  = builtInNames[i];
                FieldInfo           field = _EnumType.GetField(name, EnumBindings) !;
                EnumMemberAttribute enumMemberAttribute = field.GetCustomAttribute <EnumMemberAttribute>(true);
                string              transformedName     = enumMemberAttribute?.Value ?? namingPolicy?.ConvertName(name) ?? name;

                _RawToTransformed[rawValue]        = new EnumInfo(transformedName, enumValue, rawValue);
                _TransformedToRaw[transformedName] = new EnumInfo(name, enumValue, rawValue);
            }
        }
Ejemplo n.º 4
0
        public void Ctor_Default()
        {
            var attribute = new EnumMemberAttribute();

            Assert.Null(attribute.Value);
            Assert.False(attribute.IsValueSetExplicitly);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Initializes a new <see cref="StringEnumConverter{TEnum}"/>
        /// </summary>
        /// <param name="underlyingType">The underlying <see cref="Enum"/>'s type</param>
        /// <param name="jsonSerializerOptions">The current <see cref="Json.JsonSerializerOptions"/></param>
        public StringEnumConverter(Type underlyingType, JsonSerializerOptions jsonSerializerOptions)
        {
            this.UnderlyingType        = underlyingType;
            this.JsonSerializerOptions = jsonSerializerOptions;
            Array values = this.UnderlyingType.GetEnumValues();

            string[] names = this.UnderlyingType.GetEnumNames();
            this.TypeCode      = Type.GetTypeCode(this.UnderlyingType);
            this.IsFlags       = this.UnderlyingType.IsDefined(typeof(FlagsAttribute), true);
            this.ValueMappings = new Dictionary <ulong, EnumFieldMetadata>();
            this.NameMappings  = new Dictionary <string, EnumFieldMetadata>();
            for (int index = 0; index < values.Length; index++)
            {
                Enum                value               = (Enum)values.GetValue(index);
                ulong               rawValue            = this.GetRawValue(value);
                string              name                = names[index];
                FieldInfo           field               = this.UnderlyingType.GetField(name, BindingFlags.Default | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
                EnumMemberAttribute enumMemberAttribute = field.GetCustomAttribute <EnumMemberAttribute>(true);
                string              transformedName     = enumMemberAttribute?.Value ?? this.JsonSerializerOptions?.PropertyNamingPolicy.ConvertName(name) ?? name;
                EnumFieldMetadata   fieldMetadata       = new EnumFieldMetadata(name, transformedName, value, rawValue);
                if (!this.ValueMappings.ContainsKey(rawValue))
                {
                    this.ValueMappings.Add(rawValue, fieldMetadata);
                }
                this.NameMappings.Add(transformedName, fieldMetadata);
            }
        }
Ejemplo n.º 6
0
        public static string ToEnumString(this object enumValue, Type enumType)
        {
            string name = Enum.GetName(enumType, enumValue);
            EnumMemberAttribute enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetTypeInfo().GetDeclaredField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single();

            return(enumMemberAttribute.Value);
        }
        /// <summary>
        /// Retrieve the KVP Dictionary for the CallOrigOptions instance.
        /// </summary>
        /// <returns>KVP Dictionary</returns>
        private new IDictionary <string, object> toDict()
        {
            // change all properties with settings to a dictionary
            IDictionary <string, object> props = new Dictionary <string, object>();

            if (string.IsNullOrEmpty(getSendDigits) == false)
            {
                props.Add("sendDigits", getSendDigits);
            }

            if (getIfMachine != EIfMachine.NONE)
            {
                EnumMemberAttribute attr = EnumHelper.GetAttributeOfType <EnumMemberAttribute>(getIfMachine);
                props.Add("ifMachine", attr.Value);
            }

            if (getTimeout > 0)
            {
                props.Add("timeout", getTimeout);
            }

            if (string.IsNullOrEmpty(getParentCallId) == false)
            {
                props.Add("parentCallId", getParentCallId);
            }

            if (getPrivacyMode != EBool.NONE)
            {
                EnumMemberAttribute attr = EnumHelper.GetAttributeOfType <EnumMemberAttribute>(getPrivacyMode);
                props.Add("privacyMode", bool.Parse(attr.Value));
            }

            return(props);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Tries to parse a string into an enum honoring EnumMemberAttribute if present
        /// </summary>
        public static bool TryParseWithMemberName <TEnum>(string value, out TEnum result) where TEnum : struct
        {
            result = default;

            if (string.IsNullOrEmpty(value))
            {
                return(false);
            }

            Type enumType = typeof(TEnum);

            foreach (string name in Enum.GetNames(typeof(TEnum)))
            {
                if (name.Equals(value, StringComparison.OrdinalIgnoreCase))
                {
                    result = Enum.Parse <TEnum>(name);
                    return(true);
                }

                EnumMemberAttribute memberAttribute
                    = enumType.GetField(name).GetCustomAttribute(typeof(EnumMemberAttribute)) as EnumMemberAttribute;

                if (memberAttribute is null)
                {
                    continue;
                }

                if (memberAttribute.Value.Equals(value, StringComparison.OrdinalIgnoreCase))
                {
                    result = Enum.Parse <TEnum>(name);
                    return(true);
                }
            }
            return(false);
        }
 public static bool MatchesDescription(this EnumMemberAttribute attribute, string description)
 {
     return
         (attribute != null &&
          string.Equals(
              attribute.Value, (description ?? string.Empty).Trim(), StringComparison.OrdinalIgnoreCase));
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Retrieve the KVP Dictionary for the SetListen instance.
        /// </summary>
        /// <returns>KVP Dictionary</returns>
        /// <exception cref="FreeClimbJSONException">Thrown upon deserialize failure.</exception>
        public override IDictionary <string, object> toKvp()
        {
            // change all properties with settings to a dictionary
            IDictionary <string, object> props = new Dictionary <string, object>();

            if (this.callId == string.Empty)
            {
                throw new FreeClimbJSONException("callId is a required parameter");
            }
            props.Add("callId", this.callId);

            if (this.listen == EBool.NONE)
            {
                EnumMemberAttribute attr = EnumHelper.GetAttributeOfType <EnumMemberAttribute>(EBool.True);
                props.Add("listen", bool.Parse(attr.Value));
            }
            else
            {
                EnumMemberAttribute attr = EnumHelper.GetAttributeOfType <EnumMemberAttribute>(this.listen);
                props.Add("listen", bool.Parse(attr.Value));
            }

            IDictionary <string, object> command = new Dictionary <string, object>();

            command.Add("SetListen", props);

            return(command);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Retrieve the KVP Dictionary for the MessagesSearchFilters instance.
        /// </summary>
        /// <returns>KVP Dictionary</returns>
        public IDictionary <string, string> toDict()
        {
            // change all properties with settings to a dictionary
            IDictionary <string, string> props = new Dictionary <string, string>();

            if (string.IsNullOrEmpty(getFrom) == false)
            {
                props.Add("from", getFrom);
            }
            if (string.IsNullOrEmpty(getTo) == false)
            {
                props.Add("to", getTo);
            }
            if (string.IsNullOrEmpty(getBeginTime) == false)
            {
                props.Add("beginTime", getBeginTime);
            }
            if (string.IsNullOrEmpty(getEndTime) == false)
            {
                props.Add("endTime", getEndTime);
            }
            if (direction != EMessageDirection.NONE)
            {
                EnumMemberAttribute attr = EnumHelper.GetAttributeOfType <EnumMemberAttribute>(getDirection);
                props.Add("direction", attr.Value);
            }
            return(props);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Retrieve the KVP Dictionary for the Play instance.
        /// </summary>
        /// <returns>KVP Dictionary</returns>
        /// <exception cref="FreeClimbJSONException">Thrown upon deserialize failure.</exception>
        public override IDictionary <string, object> toKvp()
        {
            // change all properties with settings to a dictionary
            IDictionary <string, object> props = new Dictionary <string, object>();

            if (String.IsNullOrEmpty(getFile) == true)
            {
                throw new FreeClimbJSONException("file is a required parameter");
            }

            props.Add("file", getFile);

            if (String.IsNullOrEmpty(getConferenceId) == false)
            {
                props.Add("conferenceId", getConferenceId);
            }

            if (getLoop != int.MinValue)
            {
                props.Add("loop", getLoop);
            }

            if (getPrivacyMode != EBool.NONE)
            {
                EnumMemberAttribute attr = EnumHelper.GetAttributeOfType <EnumMemberAttribute>(getPrivacyMode);
                props.Add("privacyMode", bool.Parse(attr.Value));
            }

            IDictionary <string, object> command = new Dictionary <string, object>();

            command.Add("Play", props);

            return(command);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Retrieve the KVP Dictionary for the Say instance.
        /// </summary>
        /// <returns>KVP Dictionary</returns>
        public override IDictionary <string, object> toKvp()
        {
            // change all properties with settings to a dictionary
            IDictionary <string, object> props = new Dictionary <string, object>();

            props.Add("text", getText);

            if (String.IsNullOrEmpty(getConferenceId) == false)
            {
                props.Add("conferenceId", getConferenceId);
            }

            if (getLanguage != ELanguage.NONE)
            {
                EnumMemberAttribute attr = EnumHelper.GetAttributeOfType <EnumMemberAttribute>(getLanguage);
                props.Add("language", attr.Value);
            }

            if (getLoop != int.MinValue)
            {
                props.Add("loop", getLoop);
            }

            IDictionary <string, object> command = new Dictionary <string, object>();

            command.Add("Say", props);

            return(command);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Retrieve the KVP Dictionary for the ConferenceOptions instance.
        /// </summary>
        /// <returns>KVP Dictionary</returns>
        private new IDictionary <string, object> toDict()
        {
            // change all properties with settings to a dictionary
            IDictionary <string, object> props = new Dictionary <string, object>();

            if (aliasFlag == true)
            {
                props.Add("alias", getAlias);
            }

            if (getPlayBeep != EBool.NONE)
            {
                props.Add("playBeep", getPlayBeep);
            }

            if (getStatus != EConferenceStatus.NONE)
            {
                EnumMemberAttribute attr = EnumHelper.GetAttributeOfType <EnumMemberAttribute>(getStatus);
                props.Add("status", attr.Value);
            }
            IDictionary <string, object> baseDict = base.toDict();

            foreach (string key in baseDict.Keys)
            {
                props.Add(key, baseDict[key]);
            }
            return(props);
        }
Ejemplo n.º 15
0
        public virtual string Format(object parameterValue, ParameterInfo parameterInfo)
        {
            var formatString = parameterInfo.GetCustomAttribute <QueryAttribute>(true)?.Format;
            EnumMemberAttribute enummember = null;

            if (parameterValue != null && parameterInfo.ParameterType.GetTypeInfo().IsEnum)
            {
                var cached = enumMemberCache.GetOrAdd(parameterInfo.ParameterType, t => new ConcurrentDictionary <string, EnumMemberAttribute>());
                enummember = cached.GetOrAdd(parameterValue.ToString(), val => parameterInfo.ParameterType.GetMember(val).First().GetCustomAttribute <EnumMemberAttribute>());
            }

            var formattedValue = parameterValue == null
                       ? null
                       : string.Format(CultureInfo.InvariantCulture,
                                       string.IsNullOrWhiteSpace(formatString)
                                           ? "{0}"
                                           : $"{{0:{formatString}}}",
                                       enummember?.Value ?? parameterValue);

            if (string.IsNullOrEmpty(formattedValue))
            {
                return(formattedValue);
            }
            return(char.ToLowerInvariant(formattedValue[0]) + formattedValue.Substring(1));
        }
        public void EnumMemberAttribute_WithValueDefined_AsExpected()
        {
            EnumMemberAttribute memberAttribute = EnumMemberAttribute.EnumMemberAttributeOf(Fragment.ButtonById.button1);

            Console.WriteLine("CSS: " + memberAttribute.Css);
            Assert.IsTrue(memberAttribute.Css.Contains("button#otherId"));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Retrieve the KVP Dictionary for the CallOrigOptions instance.
        /// </summary>
        /// <returns>KVP Dictionary</returns>
        private new IDictionary <string, object> toDict()
        {
            // change all properties with settings to a dictionary
            IDictionary <string, object> props = new Dictionary <string, object>();

            if (string.IsNullOrEmpty(getSendDigits) == false)
            {
                props.Add("sendDigits", getSendDigits);
            }

            if (getIfMachine != EIfMachine.NONE)
            {
                EnumMemberAttribute attr = EnumHelper.GetAttributeOfType <EnumMemberAttribute>(getIfMachine);
                props.Add("ifMachine", attr.Value);
            }

            if (getTimeout > 0)
            {
                props.Add("timeout", getTimeout);
            }

            if (string.IsNullOrEmpty(getParentCallId) == false)
            {
                props.Add("parentCallId", getParentCallId);
            }

            IDictionary <string, object> baseDict = base.toDict();

            foreach (string key in baseDict.Keys)
            {
                props.Add(key, baseDict[key]);
            }
            return(props);
        }
 static EnumValue()
 {
     enumType = typeof(T);
     if (!enumType.IsEnum)
     {
         throw new InvalidOperationException();
     }
     FieldInfo[] fieldInfos = enumType.GetFields(BindingFlags.Static | BindingFlags.Public);
     values  = new long[fieldInfos.Length];
     names   = new string[fieldInfos.Length];
     isULong = Enum.GetUnderlyingType(enumType) == typeof(ulong);
     for (int i = 0; i < fieldInfos.Length; i++)
     {
         FieldInfo           fieldInfo           = fieldInfos[i];
         EnumMemberAttribute enumMemberAttribute = (EnumMemberAttribute)fieldInfo
                                                   .GetCustomAttributes(typeof(EnumMemberAttribute), false)
                                                   .FirstOrDefault();
         IConvertible value = (IConvertible)fieldInfo.GetValue(null);
         values[i] = (isULong)
                 ? (long)value.ToUInt64(null)
                 : value.ToInt64(null);
         names[i] = (enumMemberAttribute == null || string.IsNullOrEmpty(enumMemberAttribute.Value))
                 ? fieldInfo.Name
                 : enumMemberAttribute.Value;
     }
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Retrieve the KVP Dictionary for the CallsSearchFilters instance.
        /// </summary>
        /// <returns>KVP Dictionary</returns>
        public IDictionary <string, string> toDict()
        {
            // change all properties with settings to a dictionary
            IDictionary <string, string> props = new Dictionary <string, string>();

            if (string.IsNullOrEmpty(getAlias) == false)
            {
                props.Add("alias", getAlias);
            }

            if (string.IsNullOrEmpty(getDateCreated) == false)
            {
                props.Add("dateCreated", getDateCreated);
            }

            if (string.IsNullOrEmpty(getDateUpdated) == false)
            {
                props.Add("dateUpdated", getDateUpdated);
            }

            if (getStatus != EConferenceStatus.NONE)
            {
                EnumMemberAttribute attr = EnumHelper.GetAttributeOfType <EnumMemberAttribute>(getStatus);
                props.Add("status", attr.Value);
            }

            return(props);
        }
Ejemplo n.º 20
0
        public static string GetDescriptionFromEnumValue(this Enum value)
        {
            // For a list of compile time constants, see:
            // https://docs.microsoft.com/en-us/dotnet/core/tutorials/libraries


#if NETSTANDARD2_0
            EnumMemberAttribute attribute = value.GetType()
                                            .GetField(value.ToString())
                                            .GetCustomAttributes(typeof(EnumMemberAttribute), false)
                                            .SingleOrDefault() as EnumMemberAttribute;

            return(attribute == null?value.ToString() : attribute.Value);
#endif

#if NETSTANDARD1_6 || NETSTANDARD1_3 || NET45 || NET47
            EnumMemberAttribute attribute = value.GetType().GetRuntimeField(value.ToString())
                                            .GetCustomAttributes(typeof(EnumMemberAttribute), false)
                                            .SingleOrDefault() as EnumMemberAttribute;

            return(attribute == null?value.ToString() : attribute.Value);

            //var customAttribs = typeof(EnumMemberAttribute).GetTypeInfo().GetCustomAttributes();

            //EnumMemberAttribute attrib = customAttribs.SingleOrDefault() as EnumMemberAttribute;

            //return attrib == null ? value.ToString() : attrib.Value;
#endif


            throw new NotImplementedException("Not supported in the version of .NET in use");
        }
        public static string GetEnumMemberAttrValue <TEnum>(this TEnum @this) where TEnum : Enum
        {
            EnumMemberAttribute enumMemberAttr = @this.GetAttribute <EnumMemberAttribute>();

            Guard.Guard.ThrowIfNullOrWhitespace(enumMemberAttr.Value, nameof(enumMemberAttr.Value));

            return(enumMemberAttr.Value !);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// 获取枚举的说明
        /// </summary>
        /// <param name="o">枚举值</param>
        /// <returns></returns>
        public static string GetDescription(this Enum o)
        {
            Type   enumType = o.GetType();
            string name     = Enum.GetName(enumType, o);
            EnumMemberAttribute customAttribute = (EnumMemberAttribute)Attribute.GetCustomAttribute(enumType.GetField(name), typeof(EnumMemberAttribute));

            return((customAttribute == null) ? name : customAttribute.Value);
        }
        public void MatchesDescription_EmptyFieldNameNonNullDescript_False()
        {
            var attribute = new EnumMemberAttribute {
                Value = string.Empty
            };

            Assert.False(attribute.MatchesDescription(MyEnumMemberValue));
        }
        public void MatchesDescription_WhiteSpacePaddedConstantNameUsed_True()
        {
            var attribute = new EnumMemberAttribute {
                Value = MyEnumMemberValue
            };

            Assert.True(attribute.MatchesDescription("  " + MyEnumMemberValue + "\t\r\t  "));
        }
        public void MatchesDescription_NameCaseDiffers_True()
        {
            var attribute = new EnumMemberAttribute {
                Value = MyEnumMemberValue
            };

            Assert.True(attribute.MatchesDescription(MyEnumMemberValue.ToUpper()));
        }
        public void MatchesDescription_ConstantNameUsed_True()
        {
            var attribute = new EnumMemberAttribute {
                Value = MyEnumMemberValue
            };

            Assert.True(attribute.MatchesDescription(MyEnumMemberValue));
        }
        public void EnumMemberAttribute_NoExplictDefinition2_AsExpected()
        {
            EnumMemberAttribute memberAttribute = EnumMemberAttribute.EnumMemberAttributeOf(Fragment.ButtonByClass.class11);

            Console.WriteLine("CSS: " + memberAttribute.Css);
            Assert.IsTrue(memberAttribute.Css.Contains("button.class11"));
            Assert.IsNotNullOrEmpty(memberAttribute.Description);
        }
        public void MatchesDescription_FieldNameAndDescriptDiffer_False()
        {
            var attribute = new EnumMemberAttribute {
                Value = "bad value"
            };

            Assert.False(attribute.MatchesDescription("won't match"));
        }
        public void EnumMemberAttribute_FullyDefined_AsExpected()
        {
            EnumMemberAttribute memberAttribute = EnumMemberAttribute.EnumMemberAttributeOf(ButtonById.button2);

            Console.WriteLine("CSS: " + memberAttribute.Css);
            Assert.IsTrue(memberAttribute.Css.Contains("button#actualButton2Id"));
            Assert.AreEqual(memberAttribute.Description, "User defined description");
        }
        public void EnumMemberAttribute_NoExplictDefinition1_AsExpected()
        {
            EnumMemberAttribute memberAttribute = EnumMemberAttribute.EnumMemberAttributeOf(ButtonById.button1);

            Console.WriteLine("CSS: " + memberAttribute.Css);
            Assert.IsTrue(memberAttribute.Css.Contains("button#button1"));
            Assert.IsNotNullOrEmpty(memberAttribute.Description);
        }