private static async Task <DialogTurnResult> ReturnResult2Async(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            FoundChoice choice = null;

            //since we either get a choice or a string, need to make sure we are evaluatin a Choice
            if (stepContext.Result.GetType() == (typeof(FoundChoice)))
            {
                choice = (FoundChoice)stepContext.Result;
            }
            if ((long)stepContext.Values["returning"] == 0)
            {
                if (choice.Value == "no")
                {
                    return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
                }

                else
                {
                    return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("Please enter your e-mail address.") }, cancellationToken));
                }
            }

            else
            {
                return(await stepContext.ContinueDialogAsync());
            }
        }
Example #2
0
        private async Task <DialogTurnResult> DerivarTecnologiaAsync(WaterfallStepContext step, CancellationToken cancellationToken)
        {
            FoundChoice respuesta = step.Result as FoundChoice;
            string      resultado = (string)respuesta.Value;
            // Get the current profile object from user state.
            var userProfile = await accessors.UserProfile.GetAsync(step.Context, () => new Usuario(), cancellationToken);

            var dialogSiguiente = "";

            switch (resultado)
            {
            case ("PowerApps"):
                dialogSiguiente = PowerAppsDialogID;
                //await step.BeginDialogAsync(Office365DialogID, cancellationToken: cancellationToken);
                //await step.ReplaceDialogAsync(Office365DialogID, cancellationToken: cancellationToken);

                break;

            default:
                break;
            }
            // We can send messages to the user at any point in the WaterfallStep.
            //await step.Context.SendActivityAsync(MessageFactory.Text($"Thanks {resultado}."), cancellationToken);

            // WaterfallStep always finishes with the end of the Waterfall or with another dialog; here it is a Prompt Dialog.
            //return await step.PromptAsync("confirm", new PromptOptions { Prompt = MessageFactory.Text("Would you like to give your age?") }, cancellationToken);

            return(await step.BeginDialogAsync(dialogSiguiente, cancellationToken : cancellationToken));

            //return await step.EndDialogAsync(cancellationToken: cancellationToken);
        }
Example #3
0
        /// <summary>
        /// Method to execute the task which is to verify the option chosen by user in previos step and start the proper subdialog.
        /// </summary>
        /// <param name="stepContext"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>Begin Dialog Async (ShowOneReservationId, ShowAllReservationsId, GetFlightDetailsDialogId) or End Dialog Async</returns>
        private async Task <DialogTurnResult> VerifyOperationTypeAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            FoundChoice foundChoice = stepContext.Result as FoundChoice;

            //This block verifies the response from previos steps and returns suitable action.
            if (foundChoice.Value.Equals("Show single reservation", StringComparison.InvariantCultureIgnoreCase))
            {
                return(await stepContext.BeginDialogAsync(ShowOneReservationId, null, cancellationToken));
            }
            else if (foundChoice.Value.Equals("Show all reservations", StringComparison.InvariantCultureIgnoreCase))
            {
                return(await stepContext.BeginDialogAsync(ShowAllReservationsId, null, cancellationToken));
            }
            else if (foundChoice.Value.Equals("Cancel the reservation", StringComparison.InvariantCultureIgnoreCase))
            {
                return(await stepContext.BeginDialogAsync(ShowOneReservationId, null, cancellationToken));
            }
            else if (foundChoice.Value.Equals("Finish conversation", StringComparison.InvariantCultureIgnoreCase))
            {
                return(await stepContext.EndDialogAsync());
            }
            else
            {
                return(await stepContext.BeginDialogAsync(GetFlightDetailsDialogId, null, cancellationToken));
            }
        }
Example #4
0
        private async Task <DialogTurnResult> ReviewSelectionStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            FoundChoice result = (FoundChoice)stepContext.Result;
            var         choice = (string)result.Value;

            foreach (var qnaconfig in KBList.KBConfigurationsList)
            {
                if (qnaconfig.CODE == choice)
                {
                    //set current QnA config
                    KBList.KBConfigurationsList[KBList.KBConfigurationsList.IndexOf(qnaconfig)].isCurrent = true;
                }
                else
                {
                    KBList.KBConfigurationsList[KBList.KBConfigurationsList.IndexOf(qnaconfig)].isCurrent = false;
                }
            }

            //reset qnaMaker in SupportDialog
            qnaMaker = null;

            await stepContext.Context.SendActivityAsync(choice + $" is current knowlegde base!", cancellationToken : cancellationToken);

            var promptOptions = new PromptOptions();

            promptOptions.Choices = new List <Choice> {
                new Choice("Back to Main menu"), new Choice("Stop")
            };

            return(await stepContext.PromptAsync(nameof(ChoicePrompt), promptOptions, cancellationToken));
        }
Example #5
0
        protected async override Task <DialogTurnResult> ParseChoiceAsync(FoundChoice choice, WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            if (RecordNewBurglaryResources.Choice_NewReport == choice.Value)
            {
                var channelId   = stepContext.Context.Activity.ChannelId;
                var userProfile = await Accessors.UserProfile_Accessor.GetAsync(stepContext.Context,
                                                                                () => Accessors.Storage.UserProfiles.ReadOrCreateAsync(channelId).Result,
                                                                                cancellationToken);

                var ownerGuid = userProfile.Guid;
                await Accessors.CurrentIncident_Accessor.SetAsync(stepContext.Context, IncidentData.NewBurglary(ownerGuid), cancellationToken);

                return(await stepContext.ReplaceDialogAsync(typeof(ReviewBurglaryDialog).CalcDialogId(), null, cancellationToken));
            }
            else if (RecordNewBurglaryResources.Choice_Back == choice.Value)
            {
                return(await stepContext.EndDialogAsync(cancellationToken));
            }
            else
            {
                await stepContext.Context.SendActivityAsync(MessageFactory.Text(RecordNewBurglaryResources.CannotConfirmIntent), cancellationToken);

                return(await stepContext.EndDialogAsync(cancellationToken));
            }
        }
Example #6
0
        protected override async Task <DialogTurnResult> ParseChoiceAsync(FoundChoice choice, WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            if (MainChoicesResources.Choice_ReviewIncidents == choice.Value)
            {
                await stepContext.Context.SendActivityAsync(MessageFactory.Text(MainChoicesResources.ReviewNotImplemented), cancellationToken);

                return(await stepContext.EndDialogAsync(cancellationToken));
            }
            else if (MainChoicesResources.Choice_UpdatePersonals == choice.Value)
            {
                await stepContext.Context.SendActivityAsync(MessageFactory.Text(MainChoicesResources.UpdatePersonalsNotImplemented), cancellationToken);

                return(await stepContext.EndDialogAsync(cancellationToken));
            }
            else if (MainChoicesResources.Choice_ReportBurglary == choice.Value)
            {
                return(await stepContext.ReplaceDialogAsync(typeof(RecordNewBurglaryDialog).CalcDialogId(), null, cancellationToken));
            }
            else
            {
                await stepContext.Context.SendActivityAsync(MessageFactory.Text(MainChoicesResources.UnrecognisedOption), cancellationToken);

                return(await stepContext.EndDialogAsync(cancellationToken));
            }
        }
Example #7
0
        // confirm attendee waterfall steps
        public async Task <DialogTurnResult> ConfirmAttendee(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await _accessor.GetAsync(sc.Context);

                var currentRecipientName = state.AttendeesNameList[state.ConfirmAttendeesNameIndex];
                var personList           = await GetPeopleWorkWithAsync(sc, currentRecipientName);

                var userList = await GetUserAsync(sc, currentRecipientName);

                // todo: should set updatename reason in sc.Result
                if (personList.Count > 10)
                {
                    return(await sc.BeginDialogAsync(Actions.UpdateName, new UpdateUserNameDialogOptions(UpdateUserNameDialogOptions.UpdateReason.TooMany)));
                }

                if (personList.Count < 1 && userList.Count < 1)
                {
                    return(await sc.BeginDialogAsync(Actions.UpdateName, new UpdateUserNameDialogOptions(UpdateUserNameDialogOptions.UpdateReason.NotFound)));
                }

                if (personList.Count == 1)
                {
                    var user = personList.FirstOrDefault();
                    if (user != null)
                    {
                        var result =
                            new FoundChoice()
                        {
                            Value = $"{user.DisplayName}: {user.ScoredEmailAddresses.FirstOrDefault()?.Address ?? user.UserPrincipalName}",
                        };

                        return(await sc.NextAsync(result));
                    }
                }

                // TODO: should be simplify
                var selectOption = await GenerateOptions(personList, userList, sc);

                // If no more recipient to show, start update name flow and reset the recipient paging index.
                if (selectOption.Choices.Count == 0)
                {
                    state.ShowAttendeesIndex = 0;
                    return(await sc.BeginDialogAsync(Actions.UpdateName, new UpdateUserNameDialogOptions(UpdateUserNameDialogOptions.UpdateReason.NotFound)));
                }

                // Update prompt string to include the choices because the list style is none;
                // TODO: should be removed if use adaptive card show choices.
                var choiceString = GetSelectPromptString(selectOption, true);
                selectOption.Prompt.Text = choiceString;
                return(await sc.PromptAsync(Actions.Choice, selectOption));
            }
            catch
            {
                await HandleDialogExceptions(sc);

                throw;
            }
        }
        /// <summary>
        /// Method to execute the task which is to display already gathered information as an adaptive card and ask user to confirm or start over the reservation waterfall dialog.
        /// </summary>
        /// <remarks>Method gets RentalInfoAccessor in order to save the previous waterfall step result as a class of car and then sets the RentalInfoAccessor.</remarks>
        /// <param name="stepContext"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>ConfirmChoice ChoicePrompt</returns>
        private async Task <DialogTurnResult> DisplayCarReservation(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            FoundChoice carclassChoice = stepContext.Result as FoundChoice;
            RentalInfo  rentalInfo     = await _accessor.RentalInfoAccessor.GetAsync(stepContext.Context, () => new RentalInfo());

            rentalInfo.CarClass   = carclassChoice.Value;
            rentalInfo.RentalCost = GenerateRentalCost(rentalInfo.CarClass, rentalInfo.RentalLength);
            await _accessor.RentalInfoAccessor.SetAsync(stepContext.Context, rentalInfo);

            //This block creates adaptive card attachement with car rental details.
            await stepContext.Context.SendActivityAsync("Thank you, below you can find your car rental details.");

            Attachment attachment = new Attachment();

            attachment = CreateAdaptiveCardAttachement(@".\Resources\RentalDetails.txt", rentalInfo.RentalLength, rentalInfo.PassengersNumber, rentalInfo.ChildSeats, rentalInfo.CarClass, rentalInfo.RentalCost);

            //This block creats reply activity with adaptive card attachement and sends it to the user.
            Activity reply = stepContext.Context.Activity.CreateReply();

            reply.Attachments.Add(attachment);
            await stepContext.Context.SendActivityAsync(reply, cancellationToken : cancellationToken);

            return(await stepContext.PromptAsync("ConfirmChoice", new PromptOptions
            {
                Prompt = MessageFactory.Text("Please verify if rental details are correct and choose option:"),
                RetryPrompt = MessageFactory.Text("I don't recognize this option. Try again"),
                Choices = ChoiceFactory.ToChoices(new List <string> {
                    "Yes, confirm", "No, start over"
                })
            },
                                                 cancellationToken));
        }
        /// <summary>
        /// Method to execute the task which is to end the GetRentalDetailsDialog and set the data to flightInfo object or start over GetRentalDetailsDialog.
        /// </summary>
        /// <param name="stepContext"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>End dialog async or replace dialog async</returns>
        private async Task <DialogTurnResult> EndCarReservatonDialogAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            FoundChoice classflightChoice = stepContext.Result as FoundChoice;
            RentalInfo  rentalInfo        = await _accessor.RentalInfoAccessor.GetAsync(stepContext.Context, () => new RentalInfo());

            //This block is to decide if car rental details should be set to object of FlightInfo class or start over car reservation dialog.
            if (classflightChoice.Value.Equals("Yes, confirm", StringComparison.InvariantCultureIgnoreCase))
            {
                FlightInfo flightInfo = await _accessor.FlightInfoAccessor.GetAsync(stepContext.Context, () => new FlightInfo());

                flightInfo.Rental = rentalInfo;
                await _accessor.FlightInfoAccessor.SetAsync(stepContext.Context, flightInfo);

                await stepContext.Context.SendActivityAsync("Thank you, your car rental has been associated with you flight reservation. Contact with Rental Office at destination airport in order to get the car. You can ask airport staff to get directions of Rental Office.");

                return(await stepContext.EndDialogAsync());
            }
            else
            {
                RentalInfo blankInfo = new RentalInfo();
                await _accessor.RentalInfoAccessor.SetAsync(stepContext.Context, blankInfo);

                return(await stepContext.ReplaceDialogAsync(GetRentalDetailsDialogId, cancellationToken : cancellationToken));
            }
        }
        /// <summary>
        /// Method to execute the task which is to generate the reservation id, display it to the user and ask if user want to rent a car.
        /// <remarks>Method gets FlightInfoAccessor in order to save the previous waterfall step result as departure date on ending point airport and then sets the FlightInfoAccessor.</remarks>
        /// </summary>
        /// <param name="stepContext"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>CarReservationChoice ChoicePrompt</returns>
        private async Task <DialogTurnResult> ConfirmReservationAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            FoundChoice confirmdetailsChoice = stepContext.Result as FoundChoice;
            FlightInfo  flightInfo           = await _accessor.FlightInfoAccessor.GetAsync(stepContext.Context, () => new FlightInfo());

            //This block asks for car rental or starts over the dialog.
            if (confirmdetailsChoice.Value.Equals("Yes, confirm", StringComparison.InvariantCultureIgnoreCase))
            {
                Random random = new Random();
                flightInfo.ReservationId = random.Next(1000000, 9999999);
                await _accessor.FlightInfoAccessor.SetAsync(stepContext.Context, flightInfo);

                await stepContext.Context.SendActivityAsync($"Thank you, please save your reservation id: {flightInfo.ReservationId}.");

                return(await stepContext.PromptAsync("CarReservationChoice", new PromptOptions
                {
                    Prompt = MessageFactory.Text("Would you like to rent a car on destination aiport?"),
                    RetryPrompt = MessageFactory.Text("I don't recognize this option. Try again"),
                    Choices = ChoiceFactory.ToChoices(new List <string> {
                        "Yes, I would like to rent a car.", "No, thank you."
                    })
                },
                                                     cancellationToken));
            }
            else
            {
                return(await stepContext.ReplaceDialogAsync(GetFlightDetailsDialogId, cancellationToken));
            }
        }
Example #11
0
        private async Task <DialogTurnResult> ProcessLanguageResponse(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            try
            {
                // re-enable translation
                await _pauseTranslationProperty.SetAsync(stepContext.Context, false);

                FoundChoice selection = stepContext.Result as FoundChoice;
                string      choice    = selection.Value.ToString()?.Trim();

                if (choice != null)
                {
                    if (await _translator.IsValidTranslationLanguage(choice))
                    {
                        await stepContext.Context.SendActivityAsync($"OK, I'll set your language preference to '{choice}'.");

                        string code = await _translator.GetCodeForLanguage(choice);

                        await _languagePreferenceProperty.SetAsync(stepContext.Context, code);

                        _telemetryClient.TrackEvent(
                            FaqPlusPlusBot.EVENT_LANGUAGE_PREFERENCE_CHANGED,
                            new Dictionary <string, string>
                        {
                            { "UserName", stepContext.Context.Activity.From.Name },
                            { "UserAadId ", stepContext.Context.Activity.From?.AadObjectId ?? "" },
                            { "Product", _options.ProductName },
                            { "Language", code },
                        });
                    }
                    else
                    {
                        await stepContext.Context.SendActivityAsync($"I'm sorry, '{choice}' is not a valid translation language");
                    }
                }
                else
                {
                    await stepContext.Context.SendActivityAsync($"I'm sorry, something went wrong, please try again later");
                }
            }
            catch (Exception ex)
            {
                await stepContext.Context.SendActivityAsync($"I'm sorry, something went wrong, please try again later");

                _telemetryClient.TrackException(ex,
                                                new Dictionary <string, string>
                {
                    { "UserName", stepContext.Context.Activity.From.Name },
                    { "UserAadId ", stepContext.Context.Activity.From?.AadObjectId ?? "" },
                    { "Product", _options.ProductName },
                    { "Message", "failed when attempting to set language preference" },
                });
            }

            return(await stepContext.EndDialogAsync(null, cancellationToken));
        }
Example #12
0
        /// <summary>
        /// Replaces the result with the FoundChoice value if possible, then proceedes to <see cref="Dialog.ResumeDialogAsync(DialogContext, DialogReason, object, CancellationToken)"/>.
        /// </summary>
        /// <param name="dc">The <see cref="DialogContext"/> for the current turn of conversation.</param>
        /// <param name="reason">Reason why the dialog resumed.</param>
        /// <param name="result">Optional, value returned from the dialog that was called. The type
        /// of the value returned is dependent on the child dialog.</param>
        /// <param name="cancellationToken">Optional, a <see cref="CancellationToken"/> that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public override Task <DialogTurnResult> ResumeDialogAsync(DialogContext dc, DialogReason reason, object result = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            FoundChoice foundChoice = result as FoundChoice;

            if (foundChoice != null)
            {
                // return value insted of FoundChoice object
                return(base.ResumeDialogAsync(dc, reason, foundChoice.Value, cancellationToken));
            }

            return(base.ResumeDialogAsync(dc, reason, result, cancellationToken));
        }
Example #13
0
        private async Task <DialogTurnResult> entityPrompt(
            WaterfallStepContext step,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            DialogTurnResult returnResult = new DialogTurnResult(0);

            if (step.Options == null)
            {
                FoundChoice module = (FoundChoice)step.Result;
                ((BotUserEntityContext)step.Values[DialogKey]).module = module.Value;
                List <string> entities = _navigationEntityData.NavigationEntitiesForModule(module.Value.ToString());

                returnResult = await step.PromptAsync(
                    ChoicesPromptId,
                    new PromptOptions
                {
                    Prompt      = MessageFactory.Text($"The {module.Value} area has the following topics that I know about. Please choose one that I can help with."),
                    RetryPrompt = MessageFactory.Text("Please choose an option from the list."),
                    Choices     = ChoiceFactory.ToChoices(entities),
                },
                    cancellationToken);
            }
            else
            {
                FoundChoice branchChoice = (FoundChoice)step.Result;
                if (branchChoice.Value == "Choose an area")
                {
                    ((BotUserEntityContext)step.Values[DialogKey]).module = branchChoice.Value;

                    returnResult = await step.EndDialogAsync(
                        (BotUserEntityContext)step.Values[DialogKey],
                        cancellationToken);
                }
                else
                {
                    ((BotUserEntityContext)step.Values[DialogKey]).module = ((BotUserEntityContext)step.Values[DialogKeyOptions]).module;
                    ((BotUserEntityContext)step.Values[DialogKey]).entity = branchChoice.Value;
                    List <string> entityIntents = _navigationEntityData.CrudActionForEntities(branchChoice.Value.ToString());
                    entityIntents.Add("Find");

                    returnResult = await step.PromptAsync(
                        ChoicesPromptId,
                        new PromptOptions
                    {
                        Prompt      = MessageFactory.Text($"With the {branchChoice.Value} I can do the following things.Please select one."),
                        RetryPrompt = MessageFactory.Text("Please choose an option from the list."),
                        Choices     = ChoiceFactory.ToChoices(entityIntents),
                    },
                        cancellationToken);
                }
            }
            return(returnResult);
        }
Example #14
0
        /// <summary>The final step of the review-selection dialog.</summary>
        /// <param name="stepContext">The waterfall step context for the current turn.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        /// <remarks>If the task is successful, the result contains a <see cref="DialogTurnResult"/> to
        /// communicate some flow control back to the containing WaterfallDialog.</remarks>
        private static async Task <DialogTurnResult> LoopStepAsync(
            WaterfallStepContext stepContext,
            CancellationToken cancellationToken)
        {
            // Retrieve their selection list and the choice they juat made.
            List <string> list   = stepContext.Values[CompaniesSelected] as List <string>;
            FoundChoice   choice = (FoundChoice)stepContext.Result;

            // Handle any local, expected interruptions appropriately.
            switch (choice.Value)
            {
            case Interruptions.Finish:
                // Exit and return their current selection list.
                return(await stepContext.EndDialogAsync(list, cancellationToken));

            case Interruptions.Cancel:
                // Exit and return null.
                return(await stepContext.EndDialogAsync(null, cancellationToken));

            case Interruptions.Help:
                // Dispaly the help options.
                await stepContext.Context.SendActivityAsync(
                    Interruptions.HelpText,
                    cancellationToken : cancellationToken);

                break;

            case Interruptions.MoreInfo:
                // Display more information about the companies.
                await stepContext.Context.SendActivityAsync(
                    Companies.MoreInfo,
                    cancellationToken : cancellationToken);

                break;

            default:
                // If they chose a company, add it to the list.
                list.Add(choice.Value);
                break;
            }

            if (list.Count is 2)
            {
                // If they've selected 2 companies to review, exit and return their list.
                return(await stepContext.EndDialogAsync(list, cancellationToken));
            }
            else
            {
                // Otherwise, repeat this dialog, passing in the list from this iteration.
                return(await stepContext.ReplaceDialogAsync(ReviewSelectionDialog, list, cancellationToken));
            }
        }
Example #15
0
        private async Task <DialogTurnResult> donePrompt(
            WaterfallStepContext step,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            FoundChoice entityintent = (FoundChoice)step.Result;

            ((BotUserEntityContext)step.Values[DialogKey]).entityIntent = entityintent.Value;


            return(await step.EndDialogAsync(
                       (BotUserEntityContext)step.Values[DialogKey],
                       cancellationToken));
        }
        private async Task <DialogTurnResult> donePrompt(
            WaterfallStepContext step,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            FoundChoice _FacilityWorkArea  = (FoundChoice)step.Result;
            var         ixFacilityWorkArea = _setupexecutionparametersService.selectFacilityWorkAreas().Where(ct => ct.sFacilityWorkArea == _FacilityWorkArea.Value).Select(ct => ct.ixFacilityWorkArea).First();

            ((SetUpExecutionParametersPost)step.Values[DialogKey]).ixFacilityWorkArea = ixFacilityWorkArea;

            return(await step.EndDialogAsync(
                       (SetUpExecutionParametersPost)step.Values[DialogKey],
                       cancellationToken));
        }
Example #17
0
        private async Task <DialogTurnResult> entityIntentPrompt(
            WaterfallStepContext step,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            DialogTurnResult returnResult = new DialogTurnResult(0);

            if (step.Options == null)
            {
                FoundChoice entity = (FoundChoice)step.Result;
                ((BotUserEntityContext)step.Values[DialogKey]).entity = entity.Value;
                //Custom Code Start | Removed Block
                //List<string> entityIntents = _navigationEntityData.CrudActionForEntities(entity.Value.ToString());
                //entityIntents.Add("Find");

                //returnResult = await step.PromptAsync(
                //    ChoicesPromptId,
                //    new PromptOptions
                //    {
                //        Prompt = MessageFactory.Text($"With the {entity.Value} I can do the following things.Please select one."),
                //        RetryPrompt = MessageFactory.Text("Please choose an option from the list."),
                //        Choices = ChoiceFactory.ToChoices(entityIntents),
                //    },
                //    cancellationToken);
                //Custom Code End
                //Custom Code Start | Added Code Block
                ((BotUserEntityContext)step.Values[DialogKey]).entityIntent = "Create";
                return(await step.EndDialogAsync(
                           (BotUserEntityContext)step.Values[DialogKey],
                           cancellationToken));

                //Custom Code End
            }
            else
            {
                FoundChoice entityintent = (FoundChoice)step.Result;
                ((BotUserEntityContext)step.Values[DialogKey]).entityIntent = entityintent.Value;


                returnResult = await step.EndDialogAsync(
                    (BotUserEntityContext)step.Values[DialogKey],
                    cancellationToken);
            }

            return(returnResult);
        }
        /// <summary>
        /// Method to execute the task which is to begin GetRentalDetailsDialog dialog if user chose to rent a car in previous step or skip to the next step if user did not choose to rent a car.
        /// </summary>
        /// <param name="stepContext"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task <DialogTurnResult> AskForCarRentalAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            FoundChoice carrentalChoice = stepContext.Result as FoundChoice;

            if (carrentalChoice.Value.Equals("Yes, I would like to rent a car.", StringComparison.InvariantCultureIgnoreCase))
            {
                return(await stepContext.BeginDialogAsync(GetRentalDetailsDialogId, null, cancellationToken));
            }
            else
            {
                var flightInfo = await _accessor.FlightInfoAccessor.GetAsync(stepContext.Context, () => new FlightInfo());

                flightInfo.Rental = null;
                await _accessor.FlightInfoAccessor.SetAsync(stepContext.Context, flightInfo);

                return(await stepContext.NextAsync());
            }
        }
Example #19
0
        private async Task <bool> ValidateRestaurantSelection(PromptValidatorContext <FoundChoice> promptContext, CancellationToken cancellationToken)
        {
            var state = await ConversationStateAccessor.GetAsync(promptContext.Context, cancellationToken : cancellationToken);

            // This is a workaround to a known issue with Adaptive Card button responses and prompts whereby the "Text" of the adaptive card button response
            // is put into a Value object not the Text as expected causing prompt validation to fail.
            // If the prompt was about to fail and the Value property is set with Text set to NULL we do special handling.
            if (!promptContext.Recognized.Succeeded && (promptContext.Context.Activity.Value != null) && string.IsNullOrEmpty(promptContext.Context.Activity.Text))
            {
                dynamic value          = promptContext.Context.Activity.Value;
                string  promptResponse = value["selectedItem"];  // The property will be named after your choice set's ID

                if (!string.IsNullOrEmpty(promptResponse))
                {
                    // Override what the prompt has done
                    promptContext.Recognized.Succeeded = true;
                    var foundChoice = new FoundChoice
                    {
                        Value = promptResponse
                    };
                    promptContext.Recognized.Value = foundChoice;
                }
            }

            if (promptContext.Recognized.Succeeded)
            {
                var restaurants = SeedReservationSampleData.GetListOfRestaurants(state.Booking.Category, "London", _urlResolver);
                var restaurant  = restaurants.First(r => r.Name == promptContext.Recognized.Value.Value);
                if (restaurant != null)
                {
                    state.Booking.BookingPlace = restaurant;

                    var reply = TemplateManager.GenerateActivity(RestaurantBookingSharedResponses.BookRestaurantBookingPlaceSelectionEcho, new Dictionary <string, object> {
                        { "BookingPlaceName", restaurant.Name }
                    });
                    await promptContext.Context.SendActivityAsync(reply, cancellationToken);

                    return(true);
                }
            }

            return(false);
        }
        /// <summary>
        /// Method to execute the task which is to display already gathered information as an adaptive card and ask user to confirm or start over the reservation waterfall dialog.
        /// </summary>
        /// <remarks>Method gets FlightInfoAccessor in order to save the previous waterfall step result as flight class and then sets the FlightInfoAccessor.</remarks>
        /// <param name="stepContext"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>ConfirmChoice ChoicePrompt</returns>
        private async Task <DialogTurnResult> DisplayReservationAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            FoundChoice classflightChoice = stepContext.Result as FoundChoice;
            FlightInfo  flightInfo        = await _accessor.FlightInfoAccessor.GetAsync(stepContext.Context, () => new FlightInfo());

            flightInfo.TripClass = classflightChoice.Value;
            //Use GenerateFlightCost method to generate flight cost base on class chosen by user.
            flightInfo.FlightCost = GenerateFlightCost(flightInfo.TripClass);
            await _accessor.FlightInfoAccessor.SetAsync(stepContext.Context, flightInfo);

            await stepContext.Context.SendActivityAsync("Thank you, below you can find your reservation.");

            FlightInfo reservationInfo = await _accessor.FlightInfoAccessor.GetAsync(stepContext.Context, () => new FlightInfo());

            //Create reply attachement and based on OneWayFlight use suitable adaptive card schema.
            Attachment attachment = new Attachment();

            if (reservationInfo.OneWayFlight)
            {
                attachment = CreateReservationAttachement(@".\Resources\FlightDetailsOneWay.txt", reservationInfo.PassengerName, reservationInfo.FromAirport, reservationInfo.ToAirport, reservationInfo.StartDate, reservationInfo.TripClass, (reservationInfo.FlightCost.ToString() + " $"));
            }
            else
            {
                attachment = CreateReservationAttachement(@".\Resources\FlightDetailsTwoWays.txt", reservationInfo.PassengerName, reservationInfo.FromAirport, reservationInfo.ToAirport, reservationInfo.StartDate, reservationInfo.TripClass, (reservationInfo.FlightCost.ToString() + " $"), reservationInfo.EndDate);
            };

            //Create reply and send it to the user.
            Activity reply = stepContext.Context.Activity.CreateReply();

            reply.Attachments.Add(attachment);
            await stepContext.Context.SendActivityAsync(reply, cancellationToken : cancellationToken);

            return(await stepContext.PromptAsync("ConfirmChoice", new PromptOptions
            {
                Prompt = MessageFactory.Text("Please verify if flight details are correct and choose option:"),
                RetryPrompt = MessageFactory.Text("I don't recognize this option. Try again"),
                Choices = ChoiceFactory.ToChoices(new List <string> {
                    "Yes, confirm", "No, start over"
                })
            },
                                                 cancellationToken));
        }
Example #21
0
        private static async Task <DialogTurnResult> StepFourAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            // flow control here
            FoundChoice userResponse = (FoundChoice)stepContext.Result;

            switch (userResponse.Value)
            {
            case "An option":
                await stepContext.Context.SendActivityAsync(
                    MessageFactory.Text("Common choice")
                    , cancellationToken);

                break;

            case "Another option":
                await stepContext.Context.SendActivityAsync(
                    MessageFactory.Text("Safe choice")
                    , cancellationToken);

                break;

            case "Not an option":
                await stepContext.Context.SendActivityAsync(
                    MessageFactory.Text("Expected")
                    , cancellationToken);

                break;

            default:
                await stepContext.Context.SendActivityAsync(
                    MessageFactory.Text("wrong option")
                    , cancellationToken);

                break;
            }

            await stepContext.Context.SendActivityAsync(
                MessageFactory.Text($"Let's pause for 10s before proceding")
                , cancellationToken);

            return(await stepContext.NextAsync(null, cancellationToken));
        }
        private async Task <DialogTurnResult> PromptForRaceStepAsync(
            WaterfallStepContext stepContext,
            CancellationToken cancellationToken)
        {
            var demographics = await _accessors.BackPainDemographics.GetAsync(
                stepContext.Context,
                () => new BackPainDemographics(),
                cancellationToken);

            FoundChoice choice = (FoundChoice)stepContext.Result;

            demographics.LevelOfPain = choice.Value;
            return(await stepContext.PromptAsync(
                       Prompts.Race,
                       new PromptOptions
            {
                Prompt = MessageFactory.Text("What is your race?"),
                Choices = BackPainTranslations.Races.Select(kv => kv.Value.choice).ToList(),
            }, cancellationToken));
        }
        private async Task <DialogTurnResult> PromptForConfirmChoiceAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var choiceState = await UserProfileAccessor.GetAsync(stepContext.Context);

            FoundChoice isAnswered = stepContext.Result as FoundChoice;

            if (isAnswered.Value == "Yes")
            {
                choiceState.IsQuadrant = true;
            }
            else
            {
                choiceState.IsQuadrant = false;
            }

            if (choiceState.IsQuadrant)
            {
                var opts = new PromptOptions
                {
                    Prompt = new Activity
                    {
                        Type = ActivityTypes.Message,
                        Text = "Nice to hear :)",
                    },
                };
                await stepContext.PromptAsync("Confirmation", opts);
            }
            else
            {
                var opts = new PromptOptions
                {
                    Prompt = new Activity
                    {
                        Type = ActivityTypes.Message,
                        Text = "oh! Why don't you join",
                    },
                };
                await stepContext.PromptAsync("Confirmation", opts);
            }
            return(await stepContext.EndDialogAsync());
        }
        /// <summary>
        /// Validate the Food Type when we have prmpted the user.
        /// </summary>
        /// <param name="promptContext">Prompt Validator Context.</param>
        /// <param name="cancellationToken">Cancellation Token.</param>
        /// <returns>Dialog Turn Result.</returns>
        private async Task <bool> ValidateFoodType(PromptValidatorContext <FoundChoice> promptContext, CancellationToken cancellationToken)
        {
            var state = await ConversationStateAccessor.GetAsync(promptContext.Context);

            // This is a workaround to a known issue with Adaptive Card button responses and prompts whereby the "Text" of the adaptive card button response
            // is put into a Value object not the Text as expected causing prompt validation to fail.
            // If the prompt was about to fail and the Value property is set with Text set to NULL we do special handling.
            if (!promptContext.Recognized.Succeeded && (promptContext.Context.Activity.Value != null) && string.IsNullOrEmpty(promptContext.Context.Activity.Text))
            {
                dynamic value          = promptContext.Context.Activity.Value;
                string  promptResponse = value["selectedItem"];  // The property will be named after your choice set's ID

                if (!string.IsNullOrEmpty(promptResponse))
                {
                    // Override what the prompt has done
                    promptContext.Recognized.Succeeded = true;
                    var foundChoice = new FoundChoice
                    {
                        Value = promptResponse
                    };
                    promptContext.Recognized.Value = foundChoice;
                }
            }

            if (promptContext.Recognized.Succeeded)
            {
                state.Booking.Category = promptContext.Recognized.Value.Value;

                var reply = ResponseManager.GetResponse(RestaurantBookingSharedResponses.BookRestaurantFoodSelectionEcho, new StringDictionary {
                    { "FoodType", state.Booking.Category }
                });
                await promptContext.Context.SendActivityAsync(reply, cancellationToken);

                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #25
0
        private async Task <DialogTurnResult> SelectNotebookProcess(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            await PopulateStateObjects(stepContext);

            var notebooks = (List <Notebook>)stepContext.Values["Notebooks"];
            var sectionId = String.Empty;

            AddUpdateStepContextValue(stepContext, "NotebookCreated", false);

            Notebook    currentNotebook = new Notebook();
            FoundChoice selected        = stepContext.Result as FoundChoice;

            if (selected != null)
            {
                currentNotebook = notebooks.FirstOrDefault(n => n.DisplayName == selected.Value);
            }
            if (String.IsNullOrEmpty(currentNotebook.Id))
            {
                // Try to find the notebook with the default name

                string notebookName = JournalHelper.DefaultNotebookName;
                currentNotebook = notebooks.FirstOrDefault(n => n.DisplayName == notebookName);
                if (currentNotebook == null)
                {
                    // Get or create the notebook
                    _graphHelper = new GraphHelper(_discussionState.UserToken.Token, true);

                    currentNotebook = await _graphHelper.CreateNotebook(notebookName);

                    AddUpdateStepContextValue(stepContext, "NotebookCreated", true);
                }
            }
            _onboardingState.Journal.NotebookId = currentNotebook.Id;
            await StateHelper.PersistInStateAsync <UserState, OnboardingState>(
                _serviceProvider, stepContext.Context, _onboardingState, true);

            AddUpdateStepContextValue(stepContext, "Notebook", currentNotebook);
            return(await stepContext.NextAsync(sectionId, cancellationToken));
        }
        /// <summary>
        /// Method to execute the task which is to collect the date of departure on starting point airport.
        /// </summary>
        /// <remarks>Method gets FlightInfoAccessor in order to save the previous waterfall step result as boolean One Way Flight and then sets the FlightInfoAccessor.</remarks>
        /// <param name="stepContext"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>StartDate DateTimePrompt</returns>
        private async Task <DialogTurnResult> GetStartDateAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            FoundChoice oneortwowayflightChoice = stepContext.Result as FoundChoice;
            FlightInfo  flightInfo = await _accessor.FlightInfoAccessor.GetAsync(stepContext.Context, () => new FlightInfo());

            if (oneortwowayflightChoice.Value == "One way flight")
            {
                flightInfo.OneWayFlight = true;
            }
            else
            {
                flightInfo.OneWayFlight = false;
            }

            await _accessor.FlightInfoAccessor.SetAsync(stepContext.Context, flightInfo);

            return(await stepContext.PromptAsync("StartDate", new PromptOptions
            {
                Prompt = MessageFactory.Text("Please enter departure date.")
            },
                                                 cancellationToken));
        }
        /// <summary>
        /// Method to execute the task which is to confirm cancellation action or end dialog.
        /// </summary>
        /// <param name="stepContext"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>End dialog async</returns>
        private async Task <DialogTurnResult> EndShowOneReservationAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            FoundChoice foundChoice = stepContext.Result as FoundChoice;

            //This block decides if dialog should start over, reservation should be cancelled or end.
            if (foundChoice.Value.Equals("Dispaly other reservation", StringComparison.InvariantCultureIgnoreCase))
            {
                return(await stepContext.ReplaceDialogAsync(ShowOneReservationId, null, cancellationToken));
            }
            else if (foundChoice.Value.Contains("Cancel reservation"))
            {
                int flightId = int.Parse(stepContext.Values["RequestID"].ToString());
                //Get ReservationStorage object.
                ReservationStorage rstorage = await _accessor.ReservationStorageAccessor.GetAsync(stepContext.Context, () => new ReservationStorage());

                //Initialize reservation list and assign list of reservations stored in rstorage.
                IList <FlightInfo> reservations = rstorage.Reservations;
                //Initialize reservationInfo variable.
                FlightInfo reservationInfo = new FlightInfo();
                //This block searches suitable reservation ID in the list of reservations using Linq expression.
                var result = from r in reservations
                             where r.ReservationId == flightId
                             select r;
                reservationInfo = result.First();
                //Remove reservation from ResercationStorage object.
                rstorage.Reservations.Remove(reservationInfo);
                await _accessor.ReservationStorageAccessor.SetAsync(stepContext.Context, rstorage);

                //Inform user that reservation has been cancelled.
                await stepContext.Context.SendActivityAsync("Your reservaton has been successfully cancelled.");

                return(await stepContext.EndDialogAsync());
            }
            else
            {
                return(await stepContext.EndDialogAsync());
            }
        }
Example #28
0
        // Step 2: Project Disambiguation step
        // Result is one or more ConsultingProject objects
        private async Task <DialogTurnResult> ProjectDisambiguationStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var requestDetails = stepContext.Options is ConsultingRequestDetails
                    ? stepContext.Options as ConsultingRequestDetails
                    : new ConsultingRequestDetails();

            List <ConsultingProject> result = stepContext.Result as List <ConsultingProject>;

            if (result == null)
            {
                var projectName = stepContext.Result as string;
                result = await ResolveProject(projectName);
            }
            requestDetails.possibleProjects = result;

            if (result.Count > 1)
            {
                return(await stepContext.PromptAsync(nameof(ChoicePrompt), new PromptOptions
                {
                    Prompt = MessageFactory.Text("Which of these projects did you mean?"),
                    Choices = result.Select(project => new Choice()
                    {
                        Value = $"{project.Client.Name} - {project.Name}"
                    }).ToList()
                }, cancellationToken));
            }
            else
            {
                var project     = result.First();
                var foundChoice = new FoundChoice()
                {
                    Value = $"{project.Client.Name} - {project.Name}",
                    Index = 0,
                };
                return(await stepContext.NextAsync(foundChoice));
            }
        }
        private async Task <DialogTurnResult> FacilityWorkAreaPrompt(
            WaterfallStepContext step,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            FoundChoice _Company  = (FoundChoice)step.Result;
            var         ixCompany = _setupexecutionparametersService.selectCompanies().Where(ct => ct.sCompany == _Company.Value).Select(ct => ct.ixCompany).First();

            ((SetUpExecutionParametersPost)step.Values[DialogKey]).ixCompany = ixCompany;

            return(await step.PromptAsync(
                       FacilityWorkAreaPromptId,
                       new PromptOptions
            {
                //Custom Code Start | Replaced Code Block
                //Replaced Code Block Start
                //Prompt = MessageFactory.Text($"Please enter a FacilityWorkArea:"),
                //Replaced Code Block End
                Prompt = MessageFactory.Text($"Which work area are you working in?{Environment.NewLine}"),
                //Custom Code End
                RetryPrompt = MessageFactory.Text("Please choose an option from the list."),
                Choices = ChoiceFactory.ToChoices(_setupexecutionparametersService.selectFacilityWorkAreas().Select(ct => ct.sFacilityWorkArea).ToList()),
            },
                       cancellationToken));
        }
        /// <summary>The final step of the review-selection dialog.</summary>
        /// <param name="stepContext">The waterfall step context for the current turn.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        /// <remarks>If the task is successful, the result contains a <see cref="DialogTurnResult"/> to
        /// communicate some flow control back to the containing WaterfallDialog.</remarks>
        private async Task <DialogTurnResult> LoopStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            // Retrieve their selection list, the choice they made, and whether they chose to finish.
            List <string> list   = stepContext.Values[CompaniesSelected] as List <string>;
            FoundChoice   choice = (FoundChoice)stepContext.Result;
            bool          done   = choice.Value == DoneOption;

            if (!done)
            {
                // If they chose a company, add it to the list.
                list.Add(choice.Value);
            }

            if (done || list.Count is 2)
            {
                // If they're done, exit and return their list.
                return(await stepContext.EndDialogAsync(list, cancellationToken));
            }
            else
            {
                // Otherwise, repeat this dialog, passing in the list from this iteration.
                return(await stepContext.ReplaceDialogAsync(ReviewSelectionDialog, list, cancellationToken));
            }
        }