How to populate Enum from the values retrieved from Database - botframework

Looking at the example here at Message Controller for Pizza Example, if I want to populate Size or Kind based on some user input and make a call to the database, how would I do that?
So far as I know, there is not an easy way to populate the Enum at runtime.

It looks like this hasn't been implemented yet. I took a look inside https://github.com/Microsoft/BotBuilder/blob/master/CSharp/Library/FormFlow/FormBuilder.cs and found this:
internal static void TypePaths(Type type, string path, List<string> paths)
{
if (type.IsClass)
{
if (type == typeof(string))
{
paths.Add(path);
}
else if (type.IsIEnumerable())
{
var elt = type.GetGenericElementType();
if (elt.IsEnum)
{
paths.Add(path);
}
else
{
// TODO: What to do about enumerations of things other than enums?
}
}
else
{
FieldPaths(type, path, paths);
}
}
else if (type.IsEnum)
{
paths.Add(path);
}
else if (type == typeof(bool))
{
paths.Add(path);
}
else if (type.IsIntegral())
{
paths.Add(path);
}
else if (type.IsDouble())
{
paths.Add(path);
}
else if (type.IsNullable() && type.IsValueType)
{
paths.Add(path);
}
else if (type == typeof(DateTime))
{
paths.Add(path);
}
}
Notice the TODO about enumerations other than enums.
Outside of the FormBuilder we can use PromptDialog.Choice which takes an IEnumerable<> of your options.
It is possible to chain dialogs together, so you may have to split your FormDialog into two with the PromptDialog in-between.
Alternatively take a fork of BotBuilder and implement the TODO!

Related

Updating a struct with reflect

I want to make my code shorter and I'm trying to understand how reflect works. The code below works (the real code has many more structs and are much longer). So shortly the function processInput gets string data from a TCP connection and it is used to populate the Hyperdeck struct.
type configuration struct {
videoInput string `cmd:"video input:"`
audioMapping int64 `cmd:"audio mapping:"`
genlockInputResync bool `cmd:"genlock input resync:"`
}
type Hyperdeck struct {
configuration configuration
}
func (hd *Hyperdeck) processInput(s string) {
switch hd.multilineCmd {
case "configuration":
if s != "\r\n" {
if strings.HasPrefix(s, "video input:") {
hd.configuration.videoInput = strings.TrimSpace(s[strings.Index(s, ":")+1 : len(s)-1])
} else if strings.HasPrefix(s, "audio mapping:") {
hd.configuration.audioMapping = stringToInt(strings.TrimSpace(s[strings.Index(s, ":")+1:len(s)-1]), hd)
} else if strings.HasPrefix(s, "genlock input resync:") {
hd.configuration.genlockInputResync = stringToBool(strings.TrimSpace(s[strings.Index(s, ":")+1:len(s)-1]), hd)
}
} else {
hd.multilineCmd = ""
}
}
switch {
case strings.Contains(strings.ToLower(s), "configuration"):
hd.multilineCmd = "configuration"
}
}
I was thinking of making something like this that loops the stuct and identifies the type but I can't figure out how to update the struct. I've read and tried things from multiple websites but I just can't get it right.
func (hd *Hyperdeck) processInput(s string) {
switch hd.multilineCmd {
case "configuration":
if s != "\r\n" {
v := reflect.ValueOf(hd.configuration)
t := v.Type()
for i := 0; i < v.NumField(); i++ {
if strings.HasPrefix(s, t.Field(i).Tag.Get("cmd")) {
if t.Field(i).Type.String() == "string" {
// UPDATE hd.configuration.videoInput
} else if t.Field(i).Type.String() == "int" {
//UPDATE hd.configuration.audioMapping
} else if t.Field(i).Type.String() == "bool" {
//UPDATE hd.configuration.genlockInputResync
}
}
}
} else {
hd.multilineCmd = ""
}
}
switch {
case strings.Contains(strings.ToLower(s), "configuration"):
hd.multilineCmd = "configuration"
}
}
I think this code is usable for strings but can't figure out how to address it...
...FieldByName(types.Field(i).Name).SetString(strings.TrimSpace(s[strings.Index(s, ":")+1 : len(s)-1]))
And maybe the most important question, should I do it with reflect or leave it as it is now?

Skip chained function call on certain result(s)

I'm trying to implement a chain of function calls that could be expensive on their own, and I would like to only call the subsequent functions if the result of the previous satisfied the condition(s). For instance, I have these "models":
data class In(val a: Int, val c: String, val f: String, val t: String)
data class Out(val passed: Boolean, val code: String?)
...then this is the logic (never mind the variables/method names):
class Filter : SomeFilter {
override fun filter(input: In): Out {
return Stream.of(chML(input), chC(input), chA(input))
.filter { !it.passed }
.findFirst()
.orElseGet { Out(true, "SUCCESS") }
}
private fun chC(input: In): Out {
if (input.c !== "ADA") {
return Out(false, "INVALID_C")
}
return Out(true, "SUCCESS")
}
private fun chA(input: In): Out {
if (input.a >= 100) {
return Out(false, "INVALID_A")
}
return Out(true, "SUCCESS")
}
private fun chML(input: In): Out {
if (context.contains(input.f)) {
// context.add(input.to)
return Out(false, "INVALID_ML")
}
return Out(true, "SUCCESS")
}
}
The problem with these functions is that they should be expensive, so if the output from any of those is Out.passed === false, then I wouldn't like to call the next one because it could be interpreted as a terminal operation at that point.
Is there a way to implement this in such way without going the if/else-if route? The approach with streams is cleaner, but it does execute all the functions, regardless.
You can use sequence and yield
fun filter(input: In): Out {
return sequence {
yield(chML(input))
yield(chC(input))
yield(chA(input))
}
.firstOrNull { !it.passed }
?: Out(true, "SUCCESS")
}
You can use function references and invoke them in a map operation. Kotlin Sequences short-circuit based on any filters in the chain, including firstOrNull.
override fun filter(input: In): Out {
return sequenceOf(::chML, ::chC, ::chA)
.map { it(input) }
.firstOrNull { !it.passed }
?: Out(true, "SUCCESS")
}
By the way, I advise against using === or !== with Strings. That is checking reference equality which is very hard to use reliably unless all your source strings are private to this class so you can carefully make sure you know where/when they were instantiated and whether they were string literals. You should probably use != instead.

Shouldn't variables be defined on fragment calls in GraphQL?

I'm new to GraphQL. I was going through the documentation and found something which I feel is odd.
The way to pass data to variables in fragments is to do it through the root query the fragments are part of. The example given in the docs is repeated here for convenience.
query HeroComparison($first: Int = 3) {
leftComparison: hero(episode: EMPIRE) {
...comparisonFields
}
rightComparison: hero(episode: JEDI) {
...comparisonFields
}
}
fragment comparisonFields on Character {
name
friendsConnection(first: $first) {
totalCount
edges {
node {
name
}
}
}
}
My question is, why does HeroComparison define the parameter to be passed down to the enclosed fragments and not the fragments directly? We use the variables in the fragments, so shouldn't it be something like this?
query HeroComparison {
leftComparison: hero(episode: EMPIRE) {
...comparisonFields($first: Int = 3)
}
rightComparison: hero(episode: JEDI) {
...comparisonFields($first: Int = 3)
}
}
fragment comparisonFields on Character {
name
friendsConnection(first: $first) {
totalCount
edges {
node {
name
}
}
}
}
Since this is repetitive, we may even do something like
query HeroComparison {
leftComparison: hero(episode: EMPIRE) {
...comparisonFields
}
rightComparison: hero(episode: JEDI) {
...comparisonFields($first: Int = 2)
}
}
fragment comparisonFields on Character {
*var $first: Int
name
friendsConnection(first: $first = 3) {
totalCount
edges {
node {
name
}
}
}
}
My main concern in asking this is what if we wanted the first instantiation of comparisonFields to get the value 3 and the second to get 2 in the same query?
The docs page mentioned nothing to this end.
Also, aren't the second and third approaches better from the standpoint of separation of concerns?
Pros and Cons of your approach are discussed in detail in this issue.

Using an enum instead of a switch case in Gosu

I want to avoid creating a switch case and instead use an enum but when writing the following code, I get a compile error saying unexpected token public:
public enum Status {
INACTIVE {
public void doSomething() {
//do something
}
},
ACTIVE {
public void doSomething() {
//do something else
}
},
UNKNOWN {
public void doSomething() {
//do something totally different
}
};
public abstract void doSomething()
}
Basically what I want to achieve is something similar to this:
public enum Status {
ACTIVE,
INACTIVE,
UNKNOWN;
}
switch (getState()) {
case INACTIVE:
//do something
break;
case ACTIVE:
//do something else
break;
case UNKNOWN:
//do something totally different
break;
}
Is this allowed in Gosu? How should I go about achieving such a behavior?
You have miss-understood the concept of Enum. First of all, enum is inherited from java.lang.Enum. It's not allowed to implement inner classes to Enum constants. You have to consider ACTIVE,INACTIVE and UNKNOWN (Enum constants) as objects of class type Status.
Proof:
Status.ACTIVE.getClass() == class Status
Status.ACTIVE instanceof Status == true
Status.ACTIVE instanceof java.lang.Enum == true
If you want to avoid the switch statement in your main code, you can move the switch into the implementation of enum as follows; (coded in Gosu)
enum Status {
ACTIVE,INACTIVE,UNKNOWN;
public function doSomething(){
switch (this) {
case INACTIVE:
//do something
break;
case ACTIVE:
//do something
break;
case UNKNOWN:
//do something
break;
}
}
}
Now you have the capability to call the doSomething() method from the enum constants in your main code
Example:
var a=Status.ACTIVE
var b=Status.INACTIVE
var c=Status.UNKNOWN
a.doSomething()
b.doSomething()
c.doSomething()
As you can read in
Gosu grammar or below function is not allowed inside enum consts, even brackets {} after consts are not allowed.
What is allowed in enum body:
enumBody = "{" [enumConstants] classMembers "}" .
enumConstants = enumConstant {"," enumConstant} [","] [";"] .
enumConstant = {annotation} id optionalArguments .
So basically in GOSU enum contains consts and rest normally as in any other class.

A way to simplify these if statements

I've often run into this situation where I have a complicated if statement with a lot of inner if statements and a lot of repeated code. It essentially boils down to I have a bunch of cases and certain code blocks that execute based on those statements, but if a different condition is true then I want those code blocks to execute in different conditions. Here's a generic example:
if (condition) {
if (conditionA) {
codeBlockW;
}
else if (conditionB) {
codeBlockX;
}
else if (conditionC) {
codeBlockY;
}
else if (conditionD) {
codeBlockZ;
}
}
else {
if (conditionA) {
codeBlockZ;
}
else if (conditionB) {
codeBlockY;
}
else if (conditionC) {
codeBlockX;
}
else if (conditionD) {
codeBlockW;
}
}
if ((condition AND conditionA) OR (!condition AND conditionD)) { codeBlockW }
else if ((condition AND conditionB) OR (!condition AND conditionC)) { codeBlockX }
else if ((condition AND conditionC) OR (!condition AND conditionB)) { codeBlockY }
else if ((condition AND conditionD) OR (!condition AND conditionA)) { codeBlockZ }
You can shorten it a little bit like this maybe, I don't imagine any shorter way...

Resources