Skip to content

Commit

Permalink
update C# samples
Browse files Browse the repository at this point in the history
  • Loading branch information
wing328 committed Oct 19, 2022
1 parent 0d56ebc commit 7a2c3f7
Showing 1 changed file with 38 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using KellermanSoftware.CompareNetObjects;
Expand Down Expand Up @@ -116,6 +117,8 @@ public static string ParameterToString(object obj, IReadableConfiguration config
return boolean ? "true" : "false";
if (obj is ICollection collection)
return string.Join(",", collection.Cast<object>());
if (obj is Enum && HasEnumMemberAttrValue(obj))
return GetEnumMemberAttrValue(obj);

return Convert.ToString(obj, CultureInfo.InvariantCulture);
}
Expand Down Expand Up @@ -214,5 +217,40 @@ public static bool IsJsonMime(string mime)

return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json");
}

/// <summary>
/// Is the Enum decorated with EnumMember Attribute
/// </summary>
/// <param name="enumVal"></param>
/// <returns>true if found</returns>
private static bool HasEnumMemberAttrValue(object enumVal)
{
if (enumVal == null)
throw new ArgumentNullException(nameof(enumVal));
var enumType = enumVal.GetType();
var memInfo = enumType.GetMember(enumVal.ToString() ?? throw new InvalidOperationException());
var attr = memInfo.FirstOrDefault()?.GetCustomAttributes(false).OfType<EnumMemberAttribute>().FirstOrDefault();
if (attr != null) return true;
return false;
}

/// <summary>
/// Get the EnumMember value
/// </summary>
/// <param name="enumVal"></param>
/// <returns>EnumMember value as string otherwise null</returns>
private static string GetEnumMemberAttrValue(object enumVal)
{
if (enumVal == null)
throw new ArgumentNullException(nameof(enumVal));
var enumType = enumVal.GetType();
var memInfo = enumType.GetMember(enumVal.ToString() ?? throw new InvalidOperationException());
var attr = memInfo.FirstOrDefault()?.GetCustomAttributes(false).OfType<EnumMemberAttribute>().FirstOrDefault();
if (attr != null)
{
return attr.Value;
}
return null;
}
}
}

0 comments on commit 7a2c3f7

Please sign in to comment.