Search code examples
c#jsonbotframeworkjsonschemaformflow

BotFramework - Define a form using Json schema - How to access form fields in OnCompletion method?


I am following BotFramework documentation to create a form using JSON Schema Link, but whenever I am trying to access the form fields in OnCompletion method and access the bot using bot-emulator I get "Sorry, my bot code is having issues.". I don't know how to debug this code, any help is appreciated.

here are my JSON Schema contents:

TestFlow.json :

{
  "References": [ "EmpoxxxxBot.dll" ],
  "Imports": [ "EmpoxxxxBot.Helpers" ],
  "type": "object",
  "required": [
    "FirstName"
  ],
  "Templates": {
    "NotUnderstood": {
      "Patterns": [ "I do not understand \"{0}\".", "Try again, I don't get \"{0}\"." ]
    }
  },
  "properties": {
    "FirstName": {
      "Prompt": { "Patterns": [ "Enter First Name {||}" ] },
      "Before": [ { "Message": [ "test flow starting..." ] } ],
      "Describe": "First name",
      "type": [
        "string",
        "null"
      ]
    }
  },
  "OnCompletion": "await context.PostAsync(state[\"FirstName\"] );"
}

I also tried state.FirstName

public static IForm<JObject> BuildForm()
{
    using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("EmpowerIDBot.TestFlow.json"))
    {
        var schema = JObject.Parse(new StreamReader(stream).ReadToEnd());
        return new FormBuilderJson(schema)
            .AddRemainingFields()
            .Build();
    }
}

My BotBuilder version : 3.15.2.2


Solution

  • Remember that FirstName will return a JToken. You need to convert it to a string with state[\"FirstName\"].ToString() or perhaps $\"{state[\"FirstName\"]}\" since interpolated strings do string conversion automatically.

    You also have the option of just putting that method in your C# code. That can help you avoid these kinds of mistakes.

    return new FormBuilderJson(schema)
        .AddRemainingFields()
        .OnCompletion(async (context, state) => await context.PostAsync($"Hi {state["FirstName"]}"))
        .Build();