Skip to content

Instantly share code, notes, and snippets.

@dgkanatsios
Created May 11, 2017 11:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgkanatsios/fe08335c013ec969e1b30e978b235731 to your computer and use it in GitHub Desktop.
Save dgkanatsios/fe08335c013ec969e1b30e978b235731 to your computer and use it in GitHub Desktop.
A LoopWhileDialog for BotBuilder C# SDK
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