Esempio n. 1
0
        public async Task ConfirmPrompt()
        {
            TestAdapter adapter = new TestAdapter()
                                  .Use(new ConversationState <Dictionary <string, object> >(new MemoryStorage()));

            await new TestFlow(adapter, async(turnContext) =>
            {
                var dialogs = new DialogSet();
                dialogs.Add("test-prompt", new ConfirmPrompt(Culture.English));

                var state = ConversationState <Dictionary <string, object> > .Get(turnContext);
                var dc    = dialogs.CreateContext(turnContext, state);

                await dc.Continue();
                var dialogResult = dc.DialogResult;

                if (!dialogResult.Active)
                {
                    if (dialogResult.Result != null)
                    {
                        if (((ConfirmResult)dialogResult.Result).Confirmation)
                        {
                            await turnContext.SendActivity("Confirmed.");
                        }
                        else
                        {
                            await turnContext.SendActivity("Not confirmed.");
                        }
                    }
                    else
                    {
                        await dc.Prompt("test-prompt", "Please confirm.");
                    }
                }
            })
            .Send("hello")
            .AssertReply("Please confirm.")
            .Send("yes")
            .AssertReply("Confirmed.")
            .StartTest();
        }
Esempio n. 2
0
        public async Task DoubleNumberPrompt()
        {
            var convoState  = new ConversationState(new MemoryStorage());
            var dialogState = convoState.CreateProperty <DialogState>("dialogState");

            var adapter = new TestAdapter()
                          .Use(convoState);

            var dialogs = new DialogSet(dialogState);

            var numberPrompt = new NumberPrompt <double>("NumberPrompt", defaultLocale: Culture.English);

            dialogs.Add(numberPrompt);

            await new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                var dc = await dialogs.CreateContextAsync(turnContext);

                var results = await dc.ContinueAsync();
                if (!turnContext.Responded && !results.HasActive && !results.HasResult)
                {
                    var options = new PromptOptions
                    {
                        Prompt = new Activity {
                            Type = ActivityTypes.Message, Text = "Enter a number."
                        }
                    };
                    await dc.PromptAsync("NumberPrompt", options);
                }
                else if (!results.HasActive && results.HasResult)
                {
                    var numberResult = (double)results.Result;
                    await turnContext.SendActivityAsync($"Bot received the number '{numberResult}'.");
                }
            })
            .Send("hello")
            .AssertReply("Enter a number.")
            .Send("3.14")
            .AssertReply("Bot received the number '3.14'.")
            .StartTestAsync();
        }
Esempio n. 3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ProactiveMessage{T}"/> class.
        /// </summary>
        /// <param name="accessors">The state accessors for managing bot state.</param>
        /// <param name="adapterIntegration">The <see cref="BotFrameworkAdapter"/> connects the bot to the service endpoint of the given channel.</param>
        /// <param name="env">Provides information about the web hosting environment an application is running in.</param>
        /// <param name="services">External services.</param>
        /// <param name="queueName">Service Bus queue name.</param>
        /// <param name="dialogs">List of Types of other <see cref="Dialog"/>s used when sending out the proactive message.</param>
        /// <param name="telemetryClient">Telemetry client.</param>
        public ProactiveMessage(StateAccessors accessors, IAdapterIntegration adapterIntegration, IHostingEnvironment env, BotServices services, string queueName, Dialog[] dialogs, TelemetryClient telemetryClient)
        {
            _accessors           = accessors;
            _env                 = env;
            _botFrameworkAdapter = (BotFrameworkAdapter)adapterIntegration;
            _telemetryClient     = telemetryClient;

            _dialogs = new DialogSet(_accessors.DialogStateAccessor);
            foreach (var dialog in dialogs)
            {
                _dialogs.Add(dialog);
            }

            // Verify Endpoint configuration.
            var endpointConfig = env.IsProduction() ? CarWashBot.EndpointConfiguration : CarWashBot.EndpointConfigurationDev;

            if (!services.EndpointServices.ContainsKey(endpointConfig))
            {
                throw new ArgumentException($"Invalid configuration. Please check your '.bot' file for a Endpoint service named '{endpointConfig}'.");
            }

            _endpoint = services.EndpointServices[endpointConfig];

            // Verify Storage configuration.
            if (!services.StorageServices.ContainsKey(CarWashBot.StorageConfiguration))
            {
                throw new ArgumentException($"Invalid configuration. Please check your '.bot' file for a Storage service named '{CarWashBot.StorageConfiguration}'.");
            }

            var tableClient = services.StorageServices[CarWashBot.StorageConfiguration].CreateCloudTableClient();

            _table = tableClient.GetTableReference(CarWashBot.UserStorageTableName);

            // Verify ServiceBus configuration.
            if (!services.ServiceBusServices.ContainsKey(CarWashBot.ServiceBusConfiguration))
            {
                throw new ArgumentException($"Invalid configuration. Please check your '.bot' file for a Service Bus service named '{CarWashBot.ServiceBusConfiguration}'.");
            }

            _queueClient = new QueueClient(services.ServiceBusServices[CarWashBot.ServiceBusConfiguration], queueName, ReceiveMode.PeekLock, null);
        }
Esempio n. 4
0
        public async Task ShouldSendPromptAsANumberedList()
        {
            var convoState  = new ConversationState(new MemoryStorage());
            var dialogState = convoState.CreateProperty <DialogState>("dialogState");

            var adapter = new TestAdapter()
                          .Use(new AutoSaveStateMiddleware(convoState));

            var dialogs = new DialogSet(dialogState);

            // Create ChoicePrompt and change style to ListStyle.List which affects how choices are presented.
            var listPrompt = new ChoicePrompt("ChoicePrompt", defaultLocale: Culture.English)
            {
                Style = ListStyle.List,
            };

            dialogs.Add(listPrompt);

            await new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);

                var results = await dc.ContinueDialogAsync(cancellationToken);
                if (results.Status == DialogTurnStatus.Empty)
                {
                    await dc.PromptAsync(
                        "ChoicePrompt",
                        new PromptOptions
                    {
                        Prompt = new Activity {
                            Type = ActivityTypes.Message, Text = "favorite color?"
                        },
                        Choices = _colorChoices,
                    },
                        cancellationToken);
                }
            })
            .Send("hello")
            .AssertReply("favorite color?\n\n   1. red\n   2. green\n   3. blue")
            .StartTestAsync();
        }
Esempio n. 5
0
        public async Task ShouldNOTrecognizeOtherText()
        {
            var convoState  = new ConversationState(new MemoryStorage());
            var dialogState = convoState.CreateProperty <DialogState>("dialogState");

            var adapter = new TestAdapter()
                          .Use(convoState);

            var dialogs    = new DialogSet(dialogState);
            var listPrompt = new ChoicePrompt("ChoicePrompt", defaultLocale: Culture.English);

            listPrompt.Style = ListStyle.None;
            dialogs.Add(listPrompt);

            await new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);

                var results = await dc.ContinueAsync(cancellationToken);
                if (!turnContext.Responded && !results.HasActive && !results.HasResult)
                {
                    await dc.PromptAsync("ChoicePrompt",
                                         new PromptOptions
                    {
                        Prompt = new Activity {
                            Type = ActivityTypes.Message, Text = "favorite color?"
                        },
                        RetryPrompt = new Activity {
                            Type = ActivityTypes.Message, Text = "your favorite color, please?"
                        },
                        Choices = colorChoices
                    },
                                         cancellationToken);
                }
            })
            .Send("hello")
            .AssertReply(StartsWithValidator("favorite color?"))
            .Send("what was that?")
            .AssertReply("your favorite color, please?")
            .StartTestAsync();
        }
        public async Task TextPrompt()
        {
            var convoState  = new ConversationState(new MemoryStorage());
            var dialogState = convoState.CreateProperty <DialogState>("dialogState");

            var adapter = new TestAdapter(TestAdapter.CreateConversation(TestContext.TestName))
                          .Use(new AutoSaveStateMiddleware(convoState))
                          .Use(new TranscriptLoggerMiddleware(new TraceTranscriptLogger(traceActivity: false)));

            var dialogs = new DialogSet(dialogState);

            var textPrompt = new TextPrompt("TextPrompt");

            dialogs.Add(textPrompt);

            await new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);

                var results = await dc.ContinueDialogAsync(cancellationToken);
                if (results.Status == DialogTurnStatus.Empty)
                {
                    var options = new PromptOptions {
                        Prompt = new Activity {
                            Type = ActivityTypes.Message, Text = "Enter some text."
                        }
                    };
                    await dc.PromptAsync("TextPrompt", options, cancellationToken);
                }
                else if (results.Status == DialogTurnStatus.Complete)
                {
                    var textResult = (string)results.Result;
                    await turnContext.SendActivityAsync(MessageFactory.Text($"Bot received the text '{textResult}'."), cancellationToken);
                }
            })
            .Send("hello")
            .AssertReply("Enter some text.")
            .Send("some text")
            .AssertReply("Bot received the text 'some text'.")
            .StartTestAsync();
        }
Esempio n. 7
0
        public async Task DecimalNumberPrompt()
        {
            var convoState  = new ConversationState(new MemoryStorage());
            var dialogState = convoState.CreateProperty <DialogState>("dialogState");

            var adapter = new TestAdapter()
                          .Use(new AutoSaveStateMiddleware(convoState));

            var dialogs = new DialogSet(dialogState);

            var numberPrompt = new NumberPrompt <decimal>("NumberPrompt", defaultLocale: Culture.English);

            dialogs.Add(numberPrompt);

            await new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);

                var results = await dc.ContinueDialogAsync(cancellationToken);
                if (results.Status == DialogTurnStatus.Empty)
                {
                    var options = new PromptOptions
                    {
                        Prompt = new Activity {
                            Type = ActivityTypes.Message, Text = "Enter a number."
                        },
                    };
                    await dc.PromptAsync("NumberPrompt", options, cancellationToken);
                }
                else if (results.Status == DialogTurnStatus.Complete)
                {
                    var numberResult = (decimal)results.Result;
                    await turnContext.SendActivityAsync(MessageFactory.Text($"Bot received the number '{numberResult}'."), cancellationToken);
                }
            })
            .Send("hello")
            .AssertReply("Enter a number.")
            .Send("3.14")
            .AssertReply("Bot received the number '3.14'.")
            .StartTestAsync();
        }
Esempio n. 8
0
        public async Task ShouldSendPromptWithoutAddingAListButAddingSsml()
        {
            var convoState  = new ConversationState(new MemoryStorage());
            var dialogState = convoState.CreateProperty <DialogState>("dialogState");

            var adapter = new TestAdapter()
                          .Use(new AutoSaveStateMiddleware(convoState));

            var dialogs = new DialogSet(dialogState);

            var listPrompt = new ChoicePrompt("ChoicePrompt", defaultLocale: Culture.English);

            listPrompt.Style = ListStyle.None;
            dialogs.Add(listPrompt);

            await new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);

                var results = await dc.ContinueDialogAsync(cancellationToken);
                if (results.Status == DialogTurnStatus.Empty)
                {
                    await dc.PromptAsync(
                        "ChoicePrompt",
                        new PromptOptions
                    {
                        Prompt = new Activity
                        {
                            Type  = ActivityTypes.Message,
                            Text  = "favorite color?",
                            Speak = "spoken prompt",
                        },
                        Choices = colorChoices,
                    },
                        cancellationToken);
                }
            })
            .Send("hello")
            .AssertReply(SpeakValidator("favorite color?", "spoken prompt"))
            .StartTestAsync();
        }
        public async Task BasicAttachmentPrompt()
        {
            TestAdapter adapter = new TestAdapter()
                                  .Use(new ConversationState <Dictionary <string, object> >(new MemoryStorage()));

            var attachment = new Attachment {
                Content = "some content", ContentType = "text/plain"
            };
            var activityWithAttachment = MessageFactory.Attachment(attachment);

            await new TestFlow(adapter, async(turnContext) =>
            {
                var dialogs = new DialogSet();
                dialogs.Add("test-prompt", new AttachmentPrompt());

                var state = ConversationState <Dictionary <string, object> > .Get(turnContext);
                var dc    = dialogs.CreateContext(turnContext, state);

                await dc.Continue();
                var dialogResult = dc.DialogResult;

                if (!dialogResult.Active)
                {
                    if (dialogResult.Result != null)
                    {
                        var attachmentResult = (AttachmentResult)dialogResult.Result;
                        var reply            = (string)attachmentResult.Attachments.First().Content;
                        await turnContext.SendActivity(reply);
                    }
                    else
                    {
                        await dc.Prompt("test-prompt", "please add an attachment.");
                    }
                }
            })
            .Send("hello")
            .AssertReply("please add an attachment.")
            .Send(activityWithAttachment)
            .AssertReply("some content")
            .StartTest();
        }
Esempio n. 10
0
        // Initializes a new instance of the <see cref="DialogPromptBot"/> class.
        public DialogPromptBot(DialogPromptBotAccessors accessors, ILoggerFactory loggerFactory)
        {
            // ...

            _accessors = accessors ?? throw new System.ArgumentNullException(nameof(accessors));

            // Create the dialog set and add the prompts, including custom validation.
            _dialogSet = new DialogSet(_accessors.DialogStateAccessor);

            //_dialogSet.Add(new NumberPrompt<int>(PartySizePrompt, PartySizeValidatorAsync));
            //_dialogSet.Add(new NumberPrompt<int>(SizeRangePrompt, RangeValidatorAsync));
            //_dialogSet.Add(new ChoicePrompt(LocationPrompt));
            //_dialogSet.Add(new DateTimePrompt(ReservationDatePrompt, DateValidatorAsync));

            // Define the steps of the waterfall dialog and add it to the set.
            WaterfallStep[] steps = new WaterfallStep[]
            {
            };

            _dialogSet.Add(new WaterfallDialog(ReservationDialog, steps));
        }
Esempio n. 11
0
        public ToDoSkill(SkillConfiguration services, ConversationState conversationState, UserState userState, ITaskService serviceManager = null, bool skillMode = false)
        {
            _skillMode         = skillMode;
            _services          = services ?? throw new ArgumentNullException(nameof(services));
            _userState         = userState ?? throw new ArgumentNullException(nameof(userState));
            _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState));

            var isOutlookProvider = _services.Properties.ContainsKey("TaskServiceProvider") &&
                                    _services.Properties["TaskServiceProvider"].ToString().Equals(ProviderTypes.Outlook.ToString(), StringComparison.InvariantCultureIgnoreCase);
            ITaskService taskService = new OneNoteService();

            if (isOutlookProvider)
            {
                taskService = new OutlookService();
            }

            _serviceManager = serviceManager ?? taskService;

            _dialogs = new DialogSet(_conversationState.CreateProperty <DialogState>(nameof(DialogState)));
            _dialogs.Add(new MainDialog(_services, _conversationState, _userState, _serviceManager, _skillMode));
        }
Esempio n. 12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NewsSkill"/> class.
        /// </summary>
        /// <param name="services">Skill Configuration information.</param>
        /// <param name="endpointService">Endpoint service for the bot.</param>
        /// <param name="conversationState">Conversation State.</param>
        /// <param name="userState">User State.</param>
        /// <param name="proactiveState">Proative state.</param>
        /// <param name="telemetryClient">Telemetry Client.</param>
        /// <param name="backgroundTaskQueue">Background task queue.</param>
        /// <param name="serviceManager">Service Manager.</param>
        /// <param name="skillMode">Indicates whether the skill is running in skill or local mode.</param>
        public NewsSkill(
            SkillConfigurationBase services,
            EndpointService endpointService,
            ConversationState conversationState,
            UserState userState,
            ProactiveState proactiveState,
            IBotTelemetryClient telemetryClient,
            IBackgroundTaskQueue backgroundTaskQueue,
            bool skillMode = false)
        {
            _skillMode       = skillMode;
            _services        = services ?? throw new ArgumentNullException(nameof(services));
            _endpointService = endpointService ?? throw new ArgumentNullException(nameof(endpointService));
            _userState       = userState ?? throw new ArgumentNullException(nameof(userState));

            _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState));
            _telemetryClient   = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));

            _dialogs = new DialogSet(_conversationState.CreateProperty <DialogState>(nameof(DialogState)));
            _dialogs.Add(new MainDialog(_services, _conversationState, _userState, _telemetryClient, _skillMode));
        }
Esempio n. 13
0
        public RecommendationBot(StateManager accessors, IDbContext dbContext, IRecommender recommender)
        {
            _accessors = accessors ?? throw new ArgumentNullException(nameof(accessors));

            _menuDialogs.Add(
                new PersonalDataDialogComponent(PERSONAL_DATA_DIALOG, _accessors, dbContext,
                                                BotStrings.Manage_your_personal_information));
            _menuDialogs.Add(
                new ExistedComputerDialogComponent(EXISTED_COMPUTER_DIALOG, _accessors, dbContext,
                                                   BotStrings.RecommendationMenuItemTitle));
            _menuDialogs.Add(
                new NewComputerDialogComponent(NEW_COMPUTER_DIALOG, _accessors, dbContext,
                                               recommender,
                                               nameof(NewComputerDialogComponent)));


            _dialogSet = new DialogSet(accessors.ConversationDataAccessor);

            _dialogSet.Add(
                new MenuDialogComponent(MENU_DIALOG, BotStrings.MainMenuTitle, _menuDialogs, doneTitle: null));
        }
Esempio n. 14
0
        public static async Task <DialogTurnResult> Run(this Dialog dialog, ITurnContext turnContext, IStatePropertyAccessor <DialogState> accessor, CancellationToken cancellationToken = default(CancellationToken), DialogContext ctx = null)
        {
            var dialogSet = new DialogSet(accessor);

            dialogSet.Add(dialog);

            var dialogContext = await dialogSet.CreateContextAsync(turnContext, cancellationToken);

            var results = await dialogContext.ContinueDialogAsync(cancellationToken);

            if (results.Status == DialogTurnStatus.Empty)
            {
                object options = null;
                if (dialog is LeadRegisterDialog)
                {
                    options = new LeadRegisterForm();
                }
                return(await dialogContext.BeginDialogAsync(dialog.Id, options, cancellationToken));
            }
            return(results);
        }
Esempio n. 15
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var dialogStatePropertyAccessor = this.conversationState.CreateProperty <DialogState>("DialogState");

            var dialogSet = new DialogSet(dialogStatePropertyAccessor);

            dialogSet.Add(mainDialog);

            var dialogContext = await dialogSet.CreateContextAsync(turnContext, cancellationToken);

            var dialogTurnResult = await dialogContext.ContinueDialogAsync(cancellationToken);

            if (dialogTurnResult.Status == DialogTurnStatus.Empty)
            {
                await dialogContext.BeginDialogAsync(mainDialog.Id);
            }

            await this.conversationState.SaveChangesAsync(turnContext, false, cancellationToken);

            await this.userState.SaveChangesAsync(turnContext, false, cancellationToken);
        }
        /// <summary>
        /// Initializes a new instance of the class.
        /// </summary>
        /// <param name="accessors">A class containing <see cref="IStatePropertyAccessor{T}"/> used to manage state.</param>
        /// <param name="loggerFactory">A <see cref="ILoggerFactory"/> that is hooked to the Azure App Service provider.</param>
        /// <seealso cref="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.1#windows-eventlog-provider"/>
        public MiniPizzaBotBot(UserState userState, ConversationState conversationState, ILoggerFactory loggerFactory, IHostingEnvironment env)
        {
            if (loggerFactory == null)
            {
                throw new System.ArgumentNullException(nameof(loggerFactory));
            }

            _logger = loggerFactory.CreateLogger <MiniPizzaBotBot>();
            _logger.LogTrace("Turn start.");

            _hostingEnvironment = env;

            _userState         = userState ?? throw new ArgumentNullException(nameof(userState));
            _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState));

            _orderingStateAccessor = _userState.CreateProperty <OrderingState>(nameof(OrderingState));
            _dialogStateAccessor   = _conversationState.CreateProperty <DialogState>(nameof(DialogState));

            Dialogs = new DialogSet(_dialogStateAccessor);
            Dialogs.Add(new OrderingDialog(_orderingStateAccessor, loggerFactory));
        }
Esempio n. 17
0
        // Module 2 add accessors to signature
        public BackMeUp(
            DialogAccessors accessors,
            BackPainDialogFactory backPainDialogFactory,
            HealthOutcomeService healthOutcomeService,
            ILoggerFactory loggerFactory)
        {
            if (loggerFactory == null)
            {
                throw new ArgumentNullException(nameof(loggerFactory));
            }

            // Module 2
            _accessors            = accessors;
            _healthOutcomeService = healthOutcomeService;
            _dialogs = new DialogSet(_accessors.DialogState);
            _dialogs.Add(backPainDialogFactory.Configure(_dialogs));

            ILogger logger = loggerFactory.CreateLogger <BackMeUp>();

            logger.LogTrace("EchoBot turn start.");
        }
Esempio n. 18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BasicBot"/> class.
        /// </summary>
        /// <param name="botServices">Bot services.</param>
        /// <param name="accessors">Bot State Accessors.</param>
        public BasicBot(BotServices services, UserState userState, ConversationState conversationState, ILoggerFactory loggerFactory)
        {
            _services          = services ?? throw new ArgumentNullException(nameof(services));
            _userState         = userState ?? throw new ArgumentNullException(nameof(userState));
            _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState));

            _greetingStateAccessor = _userState.CreateProperty <GreetingState>(nameof(GreetingState));
            _medicStateAccessor    = _userState.CreateProperty <MedicState>(nameof(MedicState));

            _dialogStateAccessor = _conversationState.CreateProperty <DialogState>(nameof(DialogState));

            // Verify LUIS configuration.
            if (!_services.LuisServices.ContainsKey(LuisConfiguration))
            {
                throw new InvalidOperationException($"The bot configuration does not contain a service type of `luis` with the id `{LuisConfiguration}`.");
            }

            Dialogs = new DialogSet(_dialogStateAccessor);
            //Dialogs.Add(new GreetingDialog(_greetingStateAccessor, loggerFactory));
            Dialogs.Add(new MedicDialog(_medicStateAccessor, loggerFactory));
        }
Esempio n. 19
0
        public EmailSkill(
            SkillConfigurationBase services,
            EndpointService endpointService,
            ConversationState conversationState,
            UserState userState,
            ProactiveState proactiveState,
            IBotTelemetryClient telemetryClient,
            IBackgroundTaskQueue backgroundTaskQueue,
            bool skillMode = false,
            ResponseManager responseManager = null,
            IServiceManager serviceManager  = null)
        {
            _skillMode         = skillMode;
            _services          = services ?? throw new ArgumentNullException(nameof(services));
            _userState         = userState ?? throw new ArgumentNullException(nameof(userState));
            _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState));
            _telemetryClient   = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));
            _serviceManager    = serviceManager ?? new ServiceManager(services);

            if (responseManager == null)
            {
                var supportedLanguages = services.LocaleConfigurations.Keys.ToArray();
                responseManager = new ResponseManager(
                    new IResponseIdCollection[]
                {
                    new FindContactResponses(),
                    new DeleteEmailResponses(),
                    new ForwardEmailResponses(),
                    new EmailMainResponses(),
                    new ReplyEmailResponses(),
                    new SendEmailResponses(),
                    new EmailSharedResponses(),
                    new ShowEmailResponses(),
                }, supportedLanguages);
            }

            _responseManager = responseManager;
            _dialogs         = new DialogSet(_conversationState.CreateProperty <DialogState>(nameof(DialogState)));
            _dialogs.Add(new MainDialog(_services, _responseManager, _conversationState, _userState, _telemetryClient, _serviceManager, _skillMode));
        }
Esempio n. 20
0
        public async Task CultureThruNumberPromptCtor()
        {
            var convoState  = new ConversationState(new MemoryStorage());
            var dialogState = convoState.CreateProperty <DialogState>("dialogState");

            var adapter = new TestAdapter()
                          .Use(new AutoSaveStateMiddleware(convoState));

            var dialogs = new DialogSet(dialogState);

            var numberPrompt = new NumberPrompt <double>("NumberPrompt", defaultLocale: Culture.Dutch);

            dialogs.Add(numberPrompt);

            await new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);

                var results = await dc.ContinueDialogAsync(cancellationToken);
                if (results.Status == DialogTurnStatus.Empty)
                {
                    var options = new PromptOptions
                    {
                        Prompt = new Activity {
                            Type = ActivityTypes.Message, Text = "Enter a number."
                        },
                    };
                    await dc.PromptAsync("NumberPrompt", options);
                }
                else if (results.Status == DialogTurnStatus.Complete)
                {
                    var numberResult = (double)results.Result;
                    Assert.AreEqual(3.14, numberResult);
                }
            })
            .Send("hello")
            .AssertReply("Enter a number.")
            .Send("3,14")
            .StartTestAsync();
        }
Esempio n. 21
0
        public async Task TextPrompt()
        {
            var convoState  = new ConversationState(new MemoryStorage());
            var dialogState = convoState.CreateProperty <DialogState>("dialogState");

            var adapter = new TestAdapter()
                          .Use(convoState);

            var dialogs = new DialogSet(dialogState);

            var textPrompt = new TextPrompt("TextPrompt");

            dialogs.Add(textPrompt);

            await new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                var dc = await dialogs.CreateContextAsync(turnContext);

                var results = await dc.ContinueAsync();
                if (!turnContext.Responded && !results.HasActive && !results.HasResult)
                {
                    var options = new PromptOptions {
                        Prompt = new Activity {
                            Type = ActivityTypes.Message, Text = "Enter some text."
                        }
                    };
                    await dc.PromptAsync("TextPrompt", options);
                }
                else if (!results.HasActive && results.HasResult)
                {
                    var textResult = (string)results.Result;
                    await turnContext.SendActivityAsync($"Bot received the text '{textResult}'.");
                }
            })
            .Send("hello")
            .AssertReply("Enter some text.")
            .Send("some text")
            .AssertReply("Bot received the text 'some text'.")
            .StartTestAsync();
        }
Esempio n. 22
0
        public async Task WaterfallWithCallback()
        {
            var convoState = new ConversationState(new MemoryStorage());

            var adapter = new TestAdapter()
                          .Use(new AutoSaveStateMiddleware(convoState));

            var dialogState     = convoState.CreateProperty <DialogState>("dialogState");
            var dialogs         = new DialogSet(dialogState);
            var telemetryClient = new Mock <IBotTelemetryClient>();;
            var waterfallDialog = new WaterfallDialog("test", new WaterfallStep[]
            {
                async(step, cancellationToken) => { await step.Context.SendActivityAsync("step1"); return(Dialog.EndOfTurn); },
                async(step, cancellationToken) => { await step.Context.SendActivityAsync("step2"); return(Dialog.EndOfTurn); },
                async(step, cancellationToken) => { await step.Context.SendActivityAsync("step3"); return(Dialog.EndOfTurn); },
            })
            {
                TelemetryClient = telemetryClient.Object
            };

            dialogs.Add(waterfallDialog);

            await new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);
                await dc.ContinueDialogAsync(cancellationToken);
                if (!turnContext.Responded)
                {
                    await dc.BeginDialogAsync("test", null, cancellationToken);
                }
            })
            .Send("hello")
            .AssertReply("step1")
            .Send("hello")
            .AssertReply("step2")
            .Send("hello")
            .AssertReply("step3")
            .StartTestAsync();
            telemetryClient.Verify(m => m.TrackEvent(It.IsAny <string>(), It.IsAny <IDictionary <string, string> >(), It.IsAny <IDictionary <string, double> >()), Times.Exactly(4));
        }
        /// <summary>
        /// Initializes a new instance of the class.
        /// </summary>
        /// <param name="accessors">A class containing <see cref="IStatePropertyAccessor{T}"/> used to manage state.</param>
        /// <param name="loggerFactory">A <see cref="ILoggerFactory"/> that is hooked to the Azure App Service provider.</param>
        /// <seealso cref="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.1#windows-eventlog-provider"/>
        public TriviaBotT5Bot(TriviaBotT5Accessors accessors, ILoggerFactory loggerFactory, IConfiguration config)
        {
            if (loggerFactory == null)
            {
                throw new System.ArgumentNullException(nameof(loggerFactory));
            }
            _config = config;
            _logger = loggerFactory.CreateLogger <TriviaBotT5Bot>();
            _logger.LogTrace("Turn start.");
            _accessors = accessors ?? throw new System.ArgumentNullException(nameof(accessors));

            choices.Add(new Choice
            {
                Value    = "Plain Pizza",
                Synonyms = new List <string> {
                    "plain"
                }
            });
            choices.Add(new Choice {
                Value = "Pizza with Pepperoni", Synonyms = new List <string> {
                    "4 Day", "workshop", "full"
                }
            });
            choices.Add(new Choice {
                Value = "Pizza with Mushrooms", Synonyms = new List <string> {
                    "mushroom", "mushrooms", "shrooms"
                }
            });
            choices.Add(new Choice {
                Value = "Pizza with Peppers, Mushrooms and Brocolli", Synonyms = new List <string> {
                    "vegtable", "veggie"
                }
            });
            choices.Add(new Choice {
                Value = "Pizza with Anchovies"
            });

            _dialogs = new DialogSet(accessors.ConversationDialogState);
            _dialogs.Add(new ChoicePrompt("choices"));
        }
Esempio n. 24
0
        public async Task OAuthPromptInNotSupportedChannelShouldAddSignInCard()
        {
            var convoState  = new ConversationState(new MemoryStorage());
            var dialogState = convoState.CreateProperty <DialogState>("dialogState");

            var adapter = new TestAdapter()
                          .Use(new AutoSaveStateMiddleware(convoState));

            // Create new DialogSet
            var dialogs = new DialogSet(dialogState);

            dialogs.Add(new OAuthPrompt("OAuthPrompt", new OAuthPromptSettings()));

            BotCallbackHandler botCallbackHandler = async(turnContext, cancellationToken) =>
            {
                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);

                var results = await dc.ContinueDialogAsync(cancellationToken);

                if (results.Status == DialogTurnStatus.Empty)
                {
                    await dc.PromptAsync("OAuthPrompt", new PromptOptions(), cancellationToken : cancellationToken);
                }
            };

            var initialActivity = new Activity()
            {
                ChannelId = Channels.Skype,
                Text      = "hello"
            };

            await new TestFlow(adapter, botCallbackHandler)
            .Send(initialActivity)
            .AssertReply(activity =>
            {
                Assert.Single(((Activity)activity).Attachments);
                Assert.Equal(SigninCard.ContentType, ((Activity)activity).Attachments[0].ContentType);
            })
            .StartTestAsync();
        }
Esempio n. 25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AutomotiveSkill"/> class.
        /// </summary>
        /// <param name="services">Skill Configuration information.</param>
        /// <param name="conversationState">Conversation State.</param>
        /// <param name="userState">User State.</param>
        /// <param name="telemetryClient">Telemetry Client.</param>
        /// <param name="serviceManager">Service Manager.</param>
        /// <param name="skillMode">Indicates whether the skill is running in skill or local mode.</param>
        /// <param name="responseManager">The responses for the bot.</param>
        /// <param name="httpContext">HttpContext accessor used to create relative URIs for images when in local mode.</param>
        public AutomotiveSkill(
            SkillConfigurationBase services,
            ConversationState conversationState,
            UserState userState,
            IBotTelemetryClient telemetryClient,
            bool skillMode = false,
            ResponseManager responseManager  = null,
            IServiceManager serviceManager   = null,
            IHttpContextAccessor httpContext = null)
        {
            _skillMode = skillMode;
            _services  = services ?? throw new ArgumentNullException(nameof(services));
            _userState = userState ?? throw new ArgumentNullException(nameof(userState));

            // If we are running in local-mode we need the HttpContext to create image file paths
            if (!skillMode)
            {
                _httpContext = httpContext ?? throw new ArgumentNullException(nameof(httpContext));
            }

            _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState));
            _serviceManager    = serviceManager ?? new ServiceManager();
            _telemetryClient   = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));

            if (responseManager == null)
            {
                var supportedLanguages = services.LocaleConfigurations.Keys.ToArray();
                responseManager = new ResponseManager(
                    new IResponseIdCollection[]
                {
                    new AutomotiveSkillMainResponses(),
                    new AutomotiveSkillSharedResponses(),
                    new VehicleSettingsResponses(),
                }, supportedLanguages);
            }

            _responseManager = responseManager;
            _dialogs         = new DialogSet(_conversationState.CreateProperty <DialogState>(nameof(DialogState)));
            _dialogs.Add(new MainDialog(_services, _responseManager, _conversationState, _userState, _serviceManager, _httpContext, _telemetryClient, _skillMode));
        }
        public async Task PromptOptionsStyleShouldOverridePromptClassStyleProperty()
        {
            var convoState  = new ConversationState(new MemoryStorage());
            var dialogState = convoState.CreateProperty <DialogState>("dialogState");

            var adapter = new TestAdapter()
                          .Use(new AutoSaveStateMiddleware(convoState));

            var dialogs = new DialogSet(dialogState);
            var prompt  = new ConfirmPrompt("ConfirmPrompt", defaultLocale: Culture.English)
            {
                Style = ListStyle.Inline
            };

            dialogs.Add(prompt);

            await new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);

                var results = await dc.ContinueDialogAsync(cancellationToken);
                if (results.Status == DialogTurnStatus.Empty)
                {
                    await dc.PromptAsync(
                        "ConfirmPrompt",
                        new PromptOptions
                    {
                        Prompt = new Activity {
                            Type = ActivityTypes.Message, Text = "is it true?"
                        },
                        Style = ListStyle.None
                    },
                        cancellationToken);
                }
            })
            .Send("hello")
            .AssertReply("is it true?")
            .StartTestAsync();
        }
Esempio n. 27
0
        public async Task NumberPromptRetry()
        {
            TestAdapter adapter = new TestAdapter()
                                  .Use(new ConversationState <Dictionary <string, object> >(new MemoryStorage()));

            await new TestFlow(adapter, async(turnContext) =>
            {
                var dialogs = new DialogSet();
                dialogs.Add("test-prompt", new NumberPrompt <int>(Culture.English));

                var state = ConversationState <Dictionary <string, object> > .Get(turnContext);
                var dc    = dialogs.CreateContext(turnContext, state);

                await dc.Continue();
                var dialogResult = dc.DialogResult;

                if (!dialogResult.Active)
                {
                    if (dialogResult.Result != null)
                    {
                        var numberResult = (NumberResult <int>)dialogResult.Result;
                        await turnContext.SendActivity($"Bot received the number '{numberResult.Value}'.");
                    }
                    else
                    {
                        await dc.Prompt("test-prompt", "Enter a number.", new PromptOptions {
                            RetryPromptString = "You must enter a number."
                        });
                    }
                }
            })
            .Send("hello")
            .AssertReply("Enter a number.")
            .Send("hello")
            .AssertReply("You must enter a number.")
            .Send("64")
            .AssertReply("Bot received the number '64'.")
            .StartTest();
        }
Esempio n. 28
0
        public EchoWithCounterBot(EchoBotAccessors accessors, ILoggerFactory loggerFactory)
        {
            _accessors = accessors ?? throw new ArgumentNullException(nameof(accessors));
            _dialogs   = new DialogSet(accessors.ConversationDialogState);

            var name_email_slots = new List <SlotDetails>
            {
                new SlotDetails("completename", "text", "Please, enter your complete name."),
                new SlotDetails("mail", "text", "Please, enter with mail you use in Americas University."),
            };

            var description_suggestion_slots = new List <SlotDetails>
            {
                new SlotDetails("problemdescription", "text", "We do know you're not happy with one of the courses you've made with us. Could you explain us why? Please, be detalistic."),
                new SlotDetails("suggestiontosolve", "text", "Get it. What do you think we should do to get that aspect(s) better?"),
            };

            var confirmation_list = new List <SlotDetails>
            {
                new SlotDetails("confirmationdata", "text", "May I send that info to our quality center?"),
            };

            // Dialogs can be nested and the slot filling dialog makes use of that. In this example some of the child
            // dialogs are slot filling dialogs themselves.
            var slots = new List <SlotDetails>
            {
                new SlotDetails("namemail", "namemail"),
                new SlotDetails("descriptionsuggestion", "descriptionsuggestion"),
            };

            // Add the various dialogs that will be used to the DialogSet.
            _dialogs.Add(new SlotFillingDialog("descriptionsuggestion", description_suggestion_slots));
            _dialogs.Add(new SlotFillingDialog("namemail", name_email_slots));
            _dialogs.Add(new TextPrompt("text"));
            _dialogs.Add(new SlotFillingDialog("confirmationdata", confirmation_list));
            _dialogs.Add(new ConfirmPrompt("conf"));
            _dialogs.Add(new SlotFillingDialog("slot-dialog", slots));

            // Defines a simple two step Waterfall to test the slot dialog.
            _dialogs.Add(new WaterfallDialog("root", new WaterfallStep[] { StartDialogAsync, ProcessResultsAsync }));
        }
        public async Task BasicComponentDialogTest()
        {
            var convoState  = new ConversationState(new MemoryStorage());
            var dialogState = convoState.CreateProperty <DialogState>("dialogState");

            var adapter = new TestAdapter(TestAdapter.CreateConversation(TestContext.TestName))
                          .Use(new AutoSaveStateMiddleware(convoState))
                          .Use(new TranscriptLoggerMiddleware(new TraceTranscriptLogger(traceActivity: false)));

            await new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                var state   = await dialogState.GetAsync(turnContext, () => new DialogState());
                var dialogs = new DialogSet(dialogState);

                dialogs.Add(new TestComponentDialog());

                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);

                var results = await dc.ContinueDialogAsync(cancellationToken);
                if (results.Status == DialogTurnStatus.Empty)
                {
                    await dc.BeginDialogAsync("TestComponentDialog", null, cancellationToken);
                }
                else if (results.Status == DialogTurnStatus.Complete)
                {
                    var value = (int)results.Result;
                    await turnContext.SendActivityAsync(MessageFactory.Text($"Bot received the number '{value}'."), cancellationToken);
                }
            })
            .Send("hello")
            .AssertReply("Enter a number.")
            .Send("42")
            .AssertReply("Thanks for '42'")
            .AssertReply("Enter another number.")
            .Send("64")
            .AssertReply("Bot received the number '64'.")
            .StartTestAsync();
        }
        public void DialogSet_GetVersion()
        {
            var ds       = new DialogSet();
            var version1 = ds.GetVersion();

            Assert.NotNull(version1);

            var ds2      = new DialogSet();
            var version2 = ds.GetVersion();

            Assert.NotNull(version2);
            Assert.Equal(version1, version2);

            ds2.Add(new LamdaDialog((dc, ct) => null)
            {
                Id = "A"
            });
            var version3 = ds2.GetVersion();

            Assert.NotNull(version3);
            Assert.NotEqual(version2, version3);

            var version4 = ds2.GetVersion();

            Assert.NotNull(version3);
            Assert.Equal(version3, version4);

            var ds3 = new DialogSet()
                      .Add(new LamdaDialog((dc, ct) => null)
            {
                Id = "A"
            });

            var version5 = ds3.GetVersion();

            Assert.NotNull(version5);
            Assert.Equal(version5, version4);
        }