Created
May 11, 2017 11:25
-
-
Save dgkanatsios/fe08335c013ec969e1b30e978b235731 to your computer and use it in GitHub Desktop.
A LoopWhileDialog for BotBuilder C# SDK
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Bot.Builder.Dialogs; | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using System.Web; | |
namespace ParkAroundBot.CustomDialog | |
{ | |
public static class Extensions | |
{ | |
/// <summary> | |
/// Loop the <see cref="IDialog{T}"/> while <see cref="whileFunc"/> returns true. | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
/// <param name="antecedent"></param> | |
/// <param name="whileFunc"></param> | |
/// <returns></returns> | |
public static IDialog<T> LoopWhile<T>(this IDialog<T> antecedent, Func<IBotContext,IAwaitable<T>, Task<bool>> whileFunc) | |
{ | |
return new LoopWhileDialog<T>(antecedent, whileFunc); | |
} | |
} | |
[Serializable] | |
public sealed class LoopWhileDialog<T> : IDialog<T> | |
{ | |
public readonly Func<IBotContext, IAwaitable<T>, Task<bool>> WhileFunc; | |
public readonly IDialog<T> Antecedent; | |
public LoopWhileDialog(IDialog<T> antecedent, Func<IBotContext, IAwaitable<T>, Task<bool>> whileFunc) | |
{ | |
this.Antecedent = antecedent; | |
this.WhileFunc = whileFunc; | |
} | |
async Task IDialog<T>.StartAsync(IDialogContext context) | |
{ | |
context.Call<T>(this.Antecedent, ResumeAsync); | |
} | |
private async Task ResumeAsync(IDialogContext context, IAwaitable<T> result) | |
{ | |
if (await WhileFunc(context, result)) | |
context.Call<T>(this.Antecedent, ResumeAsync); | |
else | |
context.Done(await result); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment