Parse string to enum
Hi,
I was wondering about how the bot framework does the matching from string to enum, and if that part is reuseable without a formflow dialog.
There is always Enum.Parse as a baseline:
https://github.com/Microsoft/BotBuilder/blob/master/CSharp/Samples/PizzaBot/PizzaOrderDialog.cs#L60
I suspect this is the code in FormFlow for recognizing enumerations
https://github.com/Microsoft/BotBuilder/blob/afde93738234a5395a85d3ab251e6c75112a1eec/CSharp/Library/FormFlow/Recognize.cs#L48
@chrimc62 is this the relevant code?
Yes, that is the relevant code. You could reuse this recognizer. Can you describe what it is you are trying to do?
Hmm...what if I don't have a form/field to initialize the recognizer with, and I just want to reuse the recognition part?
My use case is to go from an entity from Luis to an enumeration - the bot I'm building uses Luis to try to understand as much intent as possible from a query, and fall back to a FormFlow dialog if there isn't enough information. So for example, I would like both strings "sentiment" and "sentiments" (and mild mispellings) to be parsed as the Sentiment enumeration value.
Starting from Recognize.cs, I found the code I wanted in Language.cs and FieldReflector.cs. Thanks for the help!
@sixpi Can you share the code you used, thank you.
I just wrote my own version using reflection:
FieldInfo[] fields = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static);
var field = fields.SingleOrDefault(n =>
n.Name.ToLower() == query // Match enumeration value.
|| (((TermsAttribute)n.GetCustomAttribute(typeof(TermsAttribute)))?.Alternatives.Any(x => x.ToLower() == query) ?? false)); // Or match a terms alternatives.