Skip to content

Commit

Permalink
[csharp-netcore] Enum parameter serialization to use EnumMember value…
Browse files Browse the repository at this point in the history
… when provided. (OpenAPITools#11448)

* Add modification to petstore yaml to support testing enum string resolve. Move csharp-netcore-net50 to point to new yaml schema.

* [csharp-netcore] - For enum's with an EnumMember Attribute use this value instead of enum.ToString().

-Regenerate csharp samples to accomodate change.

* fix: rebase on master.  Update samples.

* task (Samples): update csharp-netcore samples. (via generate-samples.sh)
  • Loading branch information
jafin authored Oct 19, 2022
1 parent 514dbca commit 0d56ebc
Show file tree
Hide file tree
Showing 13 changed files with 2,656 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ using System.Collections;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
{{#useCompareNetObjects}}
Expand Down Expand Up @@ -112,6 +113,8 @@ namespace {{packageName}}.Client
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 @@ -210,5 +213,40 @@ namespace {{packageName}}.Client
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;
}
}
}
Loading

0 comments on commit 0d56ebc

Please sign in to comment.