Exemple #1
0
        private async Task <DialogTurnResult> FirstStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var changeAggregateDetails = (ChangeAggregateDetails)stepContext.Options;

            if (changeAggregateDetails.toAggregate == null)
            {
                //There is information missing to execute the task ==> tell the user how to do it in the right way
                string message = "I could not recognize what aggregate you want to apply. Say something like \"change aggregate of xAxis to sum\"";

                var cancelMessage = MessageFactory.Text(message, CancelMsgText, InputHints.IgnoringInput);
                await stepContext.Context.SendActivityAsync(cancelMessage, cancellationToken);

                return(await stepContext.CancelAllDialogsAsync(cancellationToken));
            }
            else if (changeAggregateDetails.visualizationPart == null)
            {
                //There is information missing to execute the task ==> tell the user how to do it in the right way
                string message = "I could not recognize what axis you want to apply the aggregate " + changeAggregateDetails.toAggregate + " to. Say something like \"change xAxis to sum\"";

                var cancelMessage = MessageFactory.Text(message, CancelMsgText, InputHints.IgnoringInput);
                await stepContext.Context.SendActivityAsync(cancelMessage, cancellationToken);

                return(await stepContext.CancelAllDialogsAsync(cancellationToken));
            }

            return(await stepContext.NextAsync(changeAggregateDetails, cancellationToken));
        }
Exemple #2
0
        protected async Task <DialogTurnResult> SetIdFromNumber(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var state = await StateAccessor.GetAsync(sc.Context, () => new SkillState());

            var management = ServiceManager.CreateManagement(Settings, sc.Result as TokenResponse, state.ServiceCache);
            var result     = await management.SearchTicket(0, number : state.TicketNumber);

            if (!result.Success)
            {
                return(await SendServiceErrorAndCancel(sc, result));
            }

            if (result.Tickets == null || result.Tickets.Length == 0)
            {
                await sc.Context.SendActivityAsync(ResponseManager.GetResponse(TicketResponses.TicketFindNone));

                return(await sc.CancelAllDialogsAsync());
            }

            if (result.Tickets.Length >= 2)
            {
                await sc.Context.SendActivityAsync(ResponseManager.GetResponse(TicketResponses.TicketDuplicateNumber));

                return(await sc.CancelAllDialogsAsync());
            }

            state.TicketTarget = result.Tickets[0];
            state.Id           = state.TicketTarget.Id;

            var card = GetTicketCard(sc.Context, state.TicketTarget, false);

            await sc.Context.SendActivityAsync(ResponseManager.GetCardResponse(TicketResponses.TicketTarget, card, null));

            return(await sc.NextAsync());
        }
Exemple #3
0
        public async Task <DialogTurnResult> IfClearContextStep(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                // clear context before show emails, and extract it from luis result again.
                var state = await Accessor.GetAsync(sc.Context);

                var luisResult = state.LuisResult;

                var topIntent = luisResult?.TopIntent().intent;

                if (topIntent == Calendar.Intent.Summary)
                {
                    state.SummaryEvents = null;
                }

                var generalLuisResult = state.GeneralLuisResult;
                var topGeneralIntent  = generalLuisResult?.TopIntent().intent;

                if (topGeneralIntent == General.Intent.Next)
                {
                    if ((state.ShowEventIndex + 1) * CalendarSkillState.PageSize < state.SummaryEvents.Count)
                    {
                        state.ShowEventIndex++;
                    }
                    else
                    {
                        await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(SummaryResponses.CalendarNoMoreEvent));

                        return(await sc.CancelAllDialogsAsync());
                    }
                }

                if (topGeneralIntent == General.Intent.Previous)
                {
                    if (state.ShowEventIndex > 0)
                    {
                        state.ShowEventIndex--;
                    }
                    else
                    {
                        await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(SummaryResponses.CalendarNoPreviousEvent));

                        return(await sc.CancelAllDialogsAsync());
                    }
                }

                return(await sc.NextAsync());
            }
            catch
            {
                await HandleDialogExceptions(sc);

                throw;
            }
        }
Exemple #4
0
        /// <summary>
        /// Check if To Do task content is valid.
        /// </summary>
        /// <param name="sc">current step context.</param>
        /// <param name="cancellationToken">cancellation token.</param>
        /// <returns>Task completion.</returns>
        public async Task <DialogTurnResult> AfterAskToDoTaskContent(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await this.accessors.ToDoSkillState.GetAsync(sc.Context);

                if (string.IsNullOrEmpty(state.ToDoTaskContent))
                {
                    if (sc.Result != null)
                    {
                        sc.Context.Activity.Properties.TryGetValue("OriginText", out JToken toDoContent);
                        state.ToDoTaskContent = toDoContent != null?toDoContent.ToString() : sc.Context.Activity.Text;

                        return(await sc.EndDialogAsync(true));
                    }
                    else
                    {
                        return(await sc.BeginDialogAsync(Action.CollectToDoTaskContent));
                    }
                }
                else
                {
                    return(await sc.EndDialogAsync(true));
                }
            }
            catch (Exception ex)
            {
                await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(ex.Message));

                await this.accessors.ToDoSkillState.SetAsync(sc.Context, new ToDoSkillState());

                return(await sc.CancelAllDialogsAsync());
            }
        }
Exemple #5
0
        private async Task <DialogTurnResult> SetPizzaAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            if (await ShouldCancelDialogsAsync(stepContext.Context, cancellationToken))
            {
                return(await stepContext.CancelAllDialogsAsync());
            }
            var orderInfo = await _orderInfo.GetAsync(stepContext.Context);

            string name = (string)stepContext.Result;

            if (name.Equals("personalizada", System.StringComparison.InvariantCultureIgnoreCase))
            {
                return(await stepContext.BeginDialogAsync(nameof(CustomPizzaDialog), orderInfo));
            }

            var pizza = _pizzaRepository.GetPizzas()
                        .FirstOrDefault(p => name.ToLower().Contains(p.Name));

            // if the pizza does not exists, it means that we are printing the menu.
            if (pizza == null)
            {
                await MenuHelper.PrintMenuAsync(stepContext, _pizzaRepository, cancellationToken);

                return(await stepContext.ReplaceDialogAsync(nameof(WaterfallDialog), orderInfo, cancellationToken));
            }
            orderInfo.Pizzas.Add(pizza);
            await _orderInfo.SetAsync(stepContext.Context, orderInfo);

            return(await stepContext.NextAsync());
        }
Exemple #6
0
        private async Task <DialogTurnResult> EndPizzaAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            if (await ShouldCancelDialogsAsync(stepContext.Context, cancellationToken))
            {
                return(await stepContext.CancelAllDialogsAsync());
            }
            var orderInfo = await _orderInfo.GetAsync(stepContext.Context, null, cancellationToken);

            bool right = (bool)stepContext.Result;

            if (!right)
            {
                string sorryMessage = "¡Oh, vaya, lo siento, te habré entendido mal! ¡Empecemos de nuevo!";
                await stepContext.Context.SendActivityAsync(sorryMessage, sorryMessage, InputHints.IgnoringInput, cancellationToken);

                orderInfo.Pizzas.Remove(orderInfo.Pizzas.Last());
                return(await stepContext.ReplaceDialogAsync(nameof(WaterfallDialog), orderInfo, cancellationToken));
            }
            var successMessage = "¡Pizza añadida satisfactoriamente!";
            await stepContext.Context.SendActivityAsync(successMessage, successMessage, InputHints.IgnoringInput, cancellationToken);

            if (orderInfo.NumberOfPizzas > orderInfo.Pizzas.Count)
            {
                orderInfo.ConfiguringPizzaIndex++;
                var nextPizzaMessage = "¡Vamos a por la siguiente pizza!";
                await stepContext.Context.SendActivityAsync(nextPizzaMessage, nextPizzaMessage, InputHints.IgnoringInput, cancellationToken);

                return(await stepContext.ReplaceDialogAsync(nameof(WaterfallDialog), orderInfo, cancellationToken));
            }
            return(await stepContext.NextAsync());
        }
Exemple #7
0
        /// <summary>
        /// Process result from choice prompt to select current location.
        /// </summary>
        /// <param name="sc">Step Context.</param>
        /// <param name="cancellationToken">Cancellation Token.</param>
        /// <returns>Dialog Turn Result.</returns>
        protected async Task <DialogTurnResult> ProcessCurrentLocationSelectionAsync(WaterfallStepContext sc, CancellationToken cancellationToken)
        {
            try
            {
                var state = await Accessor.GetAsync(sc.Context, () => new PointOfInterestSkillState(), cancellationToken);

                bool shouldInterrupt = sc.Context.TurnState.ContainsKey(StateProperties.InterruptKey);

                if (shouldInterrupt)
                {
                    return(await sc.CancelAllDialogsAsync(cancellationToken));
                }

                var cancelMessage = TemplateManager.GenerateActivity(POISharedResponses.CancellingMessage);

                if (sc.Result != null)
                {
                    var userSelectIndex = 0;

                    if (sc.Result is bool)
                    {
                        // If true, update the current coordinates state. If false, end dialog.
                        if ((bool)sc.Result)
                        {
                            state.CurrentCoordinates        = state.LastFoundPointOfInterests[userSelectIndex].Geolocation;
                            state.LastFoundPointOfInterests = null;
                        }
                        else
                        {
                            return(await sc.ReplaceDialogAsync(Actions.CheckForCurrentLocation, cancellationToken : cancellationToken));
                        }
                    }
                    else if (sc.Result is FoundChoice)
                    {
                        // Update the current coordinates state with user choice.
                        userSelectIndex = (sc.Result as FoundChoice).Index;

                        if (userSelectIndex == SpecialChoices.Cancel || userSelectIndex >= state.LastFoundPointOfInterests.Count)
                        {
                            return(await sc.ReplaceDialogAsync(Actions.CheckForCurrentLocation, cancellationToken : cancellationToken));
                        }

                        state.CurrentCoordinates        = state.LastFoundPointOfInterests[userSelectIndex].Geolocation;
                        state.LastFoundPointOfInterests = null;
                    }

                    return(await sc.NextAsync(cancellationToken : cancellationToken));
                }

                await sc.Context.SendActivityAsync(cancelMessage, cancellationToken);

                return(await sc.EndDialogAsync(cancellationToken : cancellationToken));
            }
            catch (Exception ex)
            {
                await HandleDialogExceptionsAsync(sc, ex, cancellationToken);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
        private async Task <DialogTurnResult> GetTimeOffBalance(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var resposne = timeoffBL.GetTimeOffbalance();
            await stepContext.Context.SendActivityAsync(MessageFactory.Text(resposne), cancellationToken);

            return(await stepContext.CancelAllDialogsAsync());
        }
Exemple #9
0
        public async Task <DialogTurnResult> FirstReadMore(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var state = await ToDoStateAccessor.GetAsync(sc.Context);

            state.ReadTaskIndex++;
            var remainingTasksCount = state.Tasks.Count - (state.ReadTaskIndex * state.ReadSize);
            var toDoListAttachment  = ToAdaptiveCardForReadMore(
                state.Tasks,
                state.ReadTaskIndex * state.ReadSize,
                Math.Min(remainingTasksCount, state.ReadSize),
                state.AllTasks.Count,
                state.ListType);

            var cardReply = sc.Context.Activity.CreateReply();

            cardReply.Attachments.Add(toDoListAttachment);

            if ((state.ShowTaskPageIndex + 1) * state.PageSize < state.AllTasks.Count)
            {
                cardReply.InputHint = InputHints.IgnoringInput;
                await sc.Context.SendActivityAsync(cardReply);

                return(await sc.EndDialogAsync(true));
            }
            else
            {
                cardReply.InputHint = InputHints.AcceptingInput;
                await sc.Context.SendActivityAsync(cardReply);

                return(await sc.CancelAllDialogsAsync());
            }
        }
        private async Task <DialogTurnResult> ConfirmCheckoutStep(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var phraseType = Helper.GetPhraseType(stepContext.Context.Activity.Text);

            switch (phraseType)
            {
            case PhraseType.Positive:
            {
                return(EndOfTurn);
                //return await stepContext.ReplaceDialogAsync(nameof(ViewCartDialog), cancellationToken: cancellationToken);
            }

            case PhraseType.Negative:
            {
                await stepContext.Context.SendActivityAsync("Ok. Let's checkout later.", cancellationToken : cancellationToken);

                return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
            }

            default:
            {
                await stepContext.CancelAllDialogsAsync(cancellationToken);

                return(await stepContext.BeginDialogAsync(nameof(MainDialog), "no_intro_msg", cancellationToken : cancellationToken));
            }
            }
        }
Exemple #11
0
        public async Task <DialogTurnResult> UpdateUserName(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await Accessor.GetAsync(sc.Context);

                var currentRecipientName = state.AttendeesNameList[state.ConfirmAttendeesNameIndex];
                if (state.FirstRetryInFindContact)
                {
                    state.FirstRetryInFindContact = false;
                    return(await sc.PromptAsync(Actions.Prompt, new PromptOptions { Prompt = sc.Context.Activity.CreateReply(FindContactResponses.UserNotFound) }));
                }
                else
                {
                    await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(FindContactResponses.UserNotFoundAgain, null, new StringDictionary()
                    {
                        { "source", state.EventSource == EventSource.Microsoft ? "Outlook Calendar" : "Google Calendar" }
                    }));

                    state.FirstRetryInFindContact = true;
                    return(await sc.CancelAllDialogsAsync());
                }
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
        public async Task <DialogTurnResult> AfterAskSecondReadMoreConfirmation(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                sc.Context.Activity.Properties.TryGetValue("OriginText", out var content);
                var userInput = content != null?content.ToString() : sc.Context.Activity.Text;

                var promptRecognizerResult = ConfirmRecognizerHelper.ConfirmYesOrNo(userInput, sc.Context.Activity.Locale);

                if (promptRecognizerResult.Succeeded && promptRecognizerResult.Value == true)
                {
                    return(await sc.EndDialogAsync(true));
                }
                else
                {
                    await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(ToDoSharedResponses.ActionEnded));

                    return(await sc.CancelAllDialogsAsync());
                }
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
Exemple #13
0
        /// <summary>
        /// Check if deletion confirmation is valid.
        /// </summary>
        /// <param name="sc">current step context.</param>
        /// <param name="cancellationToken">cancellation token.</param>
        /// <returns>Task completion.</returns>
        public async Task <DialogTurnResult> AfterAskDeletionConfirmation(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await this.accessors.ToDoSkillState.GetAsync(sc.Context);

                var luisResult = await this.toDoSkillServices.LuisRecognizer.RecognizeAsync <ToDo>(sc.Context, cancellationToken);

                var topIntent = luisResult?.TopIntent().intent;
                if (topIntent == ToDo.Intent.ConfirmYes)
                {
                    state.DeleteTaskConfirmation = true;
                    return(await sc.EndDialogAsync(true));
                }
                else if (topIntent == ToDo.Intent.ConfirmNo)
                {
                    state.DeleteTaskConfirmation = false;
                    return(await sc.EndDialogAsync(true));
                }
                else
                {
                    return(await sc.BeginDialogAsync(Action.CollectDeleteTaskConfirmation));
                }
            }
            catch (Exception ex)
            {
                await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(ex.Message));

                await this.accessors.ToDoSkillState.SetAsync(sc.Context, new ToDoSkillState());

                return(await sc.CancelAllDialogsAsync());
            }
        }
Exemple #14
0
        private async Task <DialogTurnResult> StartPizzaConfigurationAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            if (await ShouldCancelDialogsAsync(stepContext.Context, cancellationToken))
            {
                return(await stepContext.CancelAllDialogsAsync());
            }

            var orderInfo = await _orderInfo.GetAsync(stepContext.Context);

            bool right = (bool)stepContext.Result;

            if (!right)
            {
                string sorryMessage = "¡Oh, vaya, lo siento, te habré entendido mal! ¡Empecemos de nuevo!";
                await stepContext.Context.SendActivityAsync(sorryMessage, sorryMessage, InputHints.IgnoringInput, cancellationToken);

                ResetOrder(stepContext, orderInfo);
                return(await stepContext.ReplaceDialogAsync(nameof(WaterfallDialog), orderInfo, cancellationToken));
            }

            string choosePizzaMsg = "¡Estupendo! ¡Vamos a ver qué te apetece!";
            await stepContext.Context.SendActivityAsync(choosePizzaMsg, choosePizzaMsg, InputHints.IgnoringInput);

            orderInfo.ConfiguringPizzaIndex = 1;
            await _orderInfo.SetAsync(stepContext.Context, orderInfo);

            return(await stepContext.BeginDialogAsync(nameof(PizzaSelectionDialog), orderInfo, cancellationToken));
        }
Exemple #15
0
        private async Task <DialogTurnResult> BookTableAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var context = stepContext.Context;

            // Report table booking based on confirmation outcome.
            if (stepContext.Result != null)
            {
                // User confirmed.
                // Get current reservation from accessor.
                var reservationFromState = await ReservationsAccessor.GetAsync(context);

                await context.SendActivityAsync($"Sure. I've booked the table for {reservationFromState.ConfirmationReadOut()}");

                if ((DialogTurnStatus)stepContext.Result == DialogTurnStatus.Complete)
                {
                    // Clear out the reservation property since this is a successful reservation completion.
                    await ReservationsAccessor.SetAsync(context, null);
                }

                await stepContext.CancelAllDialogsAsync();

                return(await stepContext.EndDialogAsync());
            }
            else
            {
                // User rejected cancellation.
                // Clear out state.
                await ReservationsAccessor.SetAsync(context, null);

                await context.SendActivityAsync("Ok.. I've cancelled the reservation.");

                return(await stepContext.EndDialogAsync());
            }
        }
Exemple #16
0
        protected async Task <DialogTurnResult> IfContinueShow(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var intent = (GeneralLuis.Intent)sc.Result;

            if (intent == GeneralLuis.Intent.Reject)
            {
                await sc.Context.SendActivityAsync(ResponseManager.GetResponse(SharedResponses.ActionEnded));

                return(await sc.CancelAllDialogsAsync());
            }
            else if (intent == GeneralLuis.Intent.Confirm)
            {
                return(await sc.EndDialogAsync());
            }
            else if (intent == GeneralLuis.Intent.ShowNext)
            {
                var state = await StateAccessor.GetAsync(sc.Context, () => new SkillState());

                state.PageIndex += 1;
                return(await sc.ReplaceDialogAsync(Actions.ShowTicketLoop));
            }
            else if (intent == GeneralLuis.Intent.ShowPrevious)
            {
                var state = await StateAccessor.GetAsync(sc.Context, () => new SkillState());

                state.PageIndex = Math.Max(0, state.PageIndex - 1);
                return(await sc.ReplaceDialogAsync(Actions.ShowTicketLoop));
            }
            else
            {
                throw new Exception($"Invalid GeneralLuis.Intent ${intent}");
            }
        }
        public async Task <DialogTurnResult> FirstReadMore(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var state = await ToDoStateAccessor.GetAsync(sc.Context);

            var allTasksCount    = state.AllTasks.Count;
            var currentTaskIndex = state.ShowTaskPageIndex * state.PageSize;

            state.Tasks = state.AllTasks.GetRange(currentTaskIndex, Math.Min(state.PageSize, allTasksCount - currentTaskIndex));
            var toDoListCard = ToAdaptiveCardForReadMore(
                state.Tasks,
                allTasksCount,
                state.ListType);

            toDoListCard.InputHint = InputHints.IgnoringInput;

            if ((state.ShowTaskPageIndex + 1) * state.PageSize < state.AllTasks.Count)
            {
                await sc.Context.SendActivityAsync(toDoListCard);

                return(await sc.EndDialogAsync(true));
            }
            else
            {
                await sc.Context.SendActivityAsync(toDoListCard);

                await sc.CancelAllDialogsAsync();

                return(await sc.ReplaceDialogAsync(Actions.CollectGoBackToStartConfirmation));
            }
        }
        public async Task <DialogTurnResult> AfterAskSecondReadMoreConfirmation(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await ToDoStateAccessor.GetAsync(sc.Context);

                var confirmResult = (bool)sc.Result;
                if (confirmResult)
                {
                    state.ShowTaskPageIndex++;
                    return(await sc.EndDialogAsync(true));
                }
                else
                {
                    await sc.Context.SendActivityAsync(ResponseManager.GetResponse(ToDoSharedResponses.ActionEnded));

                    return(await sc.CancelAllDialogsAsync());
                }
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
Exemple #19
0
        public async Task <DialogTurnResult> CancelActiveRoute(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await _accessors.PointOfInterestSkillState.GetAsync(sc.Context);

                if (state.ActiveRoute != null)
                {
                    var replyMessage = sc.Context.Activity.CreateReply(PointOfInterestBotResponses.CancelActiveRoute, _responseBuilder);
                    await sc.Context.SendActivityAsync(replyMessage);

                    state.ActiveRoute    = null;
                    state.ActiveLocation = null;
                }
                else
                {
                    var replyMessage = sc.Context.Activity.CreateReply(PointOfInterestBotResponses.CannotCancelActiveRoute, _responseBuilder);
                    await sc.Context.SendActivityAsync(replyMessage);
                }

                return(await sc.EndDialogAsync());
            }
            catch
            {
                await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(PointOfInterestBotResponses.PointOfInterestErrorMessage, _responseBuilder));

                var state = await _accessors.PointOfInterestSkillState.GetAsync(sc.Context);

                state.Clear();
                await _accessors.PointOfInterestSkillState.SetAsync(sc.Context, state);

                return(await sc.CancelAllDialogsAsync());
            }
        }
Exemple #20
0
        protected async Task HandleDialogExceptions(WaterfallStepContext sc)
        {
            var state = await Accessor.GetAsync(sc.Context);

            state.Clear();
            await sc.CancelAllDialogsAsync();
        }
Exemple #21
0
        public async Task <DialogTurnResult> CheckIfActiveLocationExists(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await _accessors.PointOfInterestSkillState.GetAsync(sc.Context);

                if (state.ActiveLocation == null)
                {
                    await sc.EndDialogAsync(true);

                    return(await sc.BeginDialogAsync(Action.FindPointOfInterest));
                }

                return(await sc.BeginDialogAsync(Action.FindRouteToActiveLocation));
            }
            catch
            {
                await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(PointOfInterestBotResponses.PointOfInterestErrorMessage, _responseBuilder));

                var state = await _accessors.PointOfInterestSkillState.GetAsync(sc.Context);

                state.Clear();
                await _accessors.PointOfInterestSkillState.SetAsync(sc.Context, state);

                return(await sc.CancelAllDialogsAsync());
            }
        }
Exemple #22
0
        protected async Task <DialogTurnResult> AfterGetAuthToken(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await StateAccessor.GetAsync(sc.Context);

                // When the user authenticates interactively we pass on the tokens/Response event which surfaces as a JObject
                // When the token is cached we get a TokenResponse object.
                if (sc.Result is ProviderTokenResponse providerTokenResponse)
                {
                    return(await sc.NextAsync(providerTokenResponse.TokenResponse));
                }
                else
                {
                    await sc.Context.SendActivityAsync(ResponseManager.GetResponse(SharedResponses.AuthFailed));

                    return(await sc.CancelAllDialogsAsync());
                }
            }
            catch (SkillException ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
            catch (Exception ex)
            {
                await HandleDialogExceptions(sc, ex);

                return(new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs));
            }
        }
Exemple #23
0
        private async Task <DialogTurnResult> OrderTypeAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            if (await ShouldCancelDialogsAsync(stepContext.Context, cancellationToken))
            {
                return(await stepContext.CancelAllDialogsAsync());
            }

            var orderInfo = await _orderInfo.GetAsync(stepContext.Context);

            if (!orderInfo.NumberOfPizzas.HasValue)
            {
                orderInfo.NumberOfPizzas = (int)stepContext.Result;
            }
            if (orderInfo.OrderType == OrderType.Undefined)
            {
                var message = "¿Quieres tu pedido a domicilio o para recoger?";
                return(await stepContext.PromptAsync("ChoiceOrderType",
                                                     new PromptOptions
                {
                    Choices = ChoiceFactory.ToChoices(new List <string> {
                        "a domicilio", "para recoger"
                    }),
                    Prompt = MessageFactory.Text(message, message, InputHints.ExpectingInput),
                    RetryPrompt = MessageFactory.Text("Perdona, no entendí tu respuesta. " + message)
                }, cancellationToken));
            }
            return(await stepContext.NextAsync());
        }
Exemple #24
0
        /// <summary>
        /// Mark To Do task completed step.
        /// </summary>
        /// <param name="sc">current step context.</param>
        /// <param name="cancellationToken">cancellation token.</param>
        /// <returns>Task completion.</returns>
        public async Task <DialogTurnResult> MarkToDoTaskCompleted(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await this.accessors.ToDoSkillState.GetAsync(sc.Context);

                if (string.IsNullOrEmpty(state.OneNotePageId))
                {
                    await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(ToDoBotResponses.SettingUpOneNoteMessage));
                }

                var service = await this.toDoService.Init(state.MsGraphToken, state.OneNotePageId);

                var page = await service.GetDefaultToDoPage();

                BotResponse botResponse;
                string      taskToBeMarked = null;
                if (state.MarkOrDeleteAllTasksFlag)
                {
                    await service.MarkAllToDoItemsCompleted(state.ToDoTaskAllActivities, page.ContentUrl);

                    botResponse = ToDoBotResponses.AfterAllToDoTasksCompleted;
                }
                else
                {
                    await service.MarkToDoItemCompleted(state.ToDoTaskActivities[state.ToDoTaskIndex], page.ContentUrl);

                    botResponse    = ToDoBotResponses.AfterToDoTaskCompleted;
                    taskToBeMarked = state.ToDoTaskActivities[state.ToDoTaskIndex].Topic;
                }

                var todosAndPageIdTuple = await service.GetMyToDoList();

                state.OneNotePageId         = todosAndPageIdTuple.Item2;
                state.ToDoTaskAllActivities = todosAndPageIdTuple.Item1;
                var allTasksCount    = state.ToDoTaskAllActivities.Count;
                var currentTaskIndex = state.ShowToDoPageIndex * state.PageSize;
                state.ToDoTaskActivities = state.ToDoTaskAllActivities.GetRange(currentTaskIndex, Math.Min(state.PageSize, allTasksCount - currentTaskIndex));
                var markToDoAttachment = ToDoHelper.ToAdaptiveCardAttachmentForOtherFlows(
                    state.ToDoTaskActivities,
                    state.ToDoTaskAllActivities.Count,
                    taskToBeMarked,
                    botResponse,
                    ToDoBotResponses.ShowToDoTasks);
                var markToDoReply = sc.Context.Activity.CreateReply();
                markToDoReply.Attachments.Add(markToDoAttachment);
                await sc.Context.SendActivityAsync(markToDoReply);

                return(await sc.EndDialogAsync(true));
            }
            catch (Exception ex)
            {
                await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(ex.Message));

                await this.accessors.ToDoSkillState.SetAsync(sc.Context, new ToDoSkillState());

                return(await sc.CancelAllDialogsAsync());
            }
        }
Exemple #25
0
        public async Task <DialogTurnResult> CheckIfFoundLocationExists(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var state = await _accessors.PointOfInterestSkillState.GetAsync(sc.Context);

                if (state.FoundLocations == null)
                {
                    return(await sc.ContinueDialogAsync());
                }

                if (!string.IsNullOrEmpty(state.SearchText))
                {
                    // Set ActiveLocation if one w/ matching name is found in FoundLocations
                    var activeLocation = state.FoundLocations?.FirstOrDefault(x => x.Name.Contains(state.SearchText, StringComparison.InvariantCultureIgnoreCase));
                    if (activeLocation != null)
                    {
                        state.ActiveLocation = activeLocation;
                        state.FoundLocations = null;
                    }
                }

                if (!string.IsNullOrEmpty(state.SearchAddress) && state.FoundLocations != null)
                {
                    // Set ActiveLocation if one w/ matching address is found in FoundLocations
                    var activeLocation = state.FoundLocations?.FirstOrDefault(x => x.Address.FormattedAddress.Contains(state.SearchAddress, StringComparison.InvariantCultureIgnoreCase));
                    if (activeLocation != null)
                    {
                        state.ActiveLocation = activeLocation;
                        state.FoundLocations = null;
                    }
                }

                if (state.LastUtteredNumber != null && state.FoundLocations != null)
                {
                    // Set ActiveLocation if one w/ matching address is found in FoundLocations
                    var indexNumber    = (int)state.LastUtteredNumber[0] - 1;
                    var activeLocation = state.FoundLocations?[indexNumber];
                    if (activeLocation != null)
                    {
                        state.ActiveLocation = activeLocation;
                        state.FoundLocations = null;
                    }
                }

                return(await sc.ContinueDialogAsync());
            }
            catch
            {
                await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(PointOfInterestBotResponses.PointOfInterestErrorMessage, _responseBuilder));

                var state = await _accessors.PointOfInterestSkillState.GetAsync(sc.Context);

                state.Clear();
                await _accessors.PointOfInterestSkillState.SetAsync(sc.Context, state);

                return(await sc.CancelAllDialogsAsync());
            }
        }
Exemple #26
0
        // This method is called by any waterfall step that throws an exception to ensure consistency
        public async Task <Exception> HandleDialogExceptionsAsync(WaterfallStepContext sc, Exception ex, CancellationToken cancellationToken)
        {
            await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(MainStrings.ERROR), cancellationToken);

            await sc.CancelAllDialogsAsync(cancellationToken);

            return(ex);
        }
        // This method is called by any waterfall step that throws an exception to ensure consistency
        public async Task <Exception> HandleDialogExceptions(WaterfallStepContext sc, Exception ex)
        {
            await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(weatherskillSharedResponses.ErrorMessage));

            await sc.CancelAllDialogsAsync();

            return(ex);
        }
Exemple #28
0
        public async Task HandleDialogException(WaterfallStepContext sc)
        {
            var state = await _accessor.GetAsync(sc.Context);

            state.Clear();
            await _accessor.SetAsync(sc.Context, state);

            await sc.CancelAllDialogsAsync();
        }
Exemple #29
0
        protected async Task HandleDialogExceptionAsync(WaterfallStepContext sc, CancellationToken cancellationToken)
        {
            var state = await Accessor.GetAsync(sc.Context, () => new PointOfInterestSkillState(), cancellationToken);

            state.Clear();
            await Accessor.SetAsync(sc.Context, state);

            await sc.CancelAllDialogsAsync(cancellationToken);
        }
Exemple #30
0
        /// <summary>
        /// Call Maps Service to run a fuzzy search from current coordinates based on entities retrieved by bot.
        /// </summary>
        public async Task <DialogTurnResult> GetPointOfInterestLocations(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                string country = string.Empty;

                // Defensive for scenarios where locale isn't correctly set
                try
                {
                    var cultureInfo = new RegionInfo(sc.Context.Activity.Locale);
                    country = cultureInfo.TwoLetterISORegionName;
                }
                catch (Exception)
                {
                    // Default to everything if we can't restrict the country
                }

                var state = await _accessors.PointOfInterestSkillState.GetAsync(sc.Context);

                var service = _serviceManager.InitMapsService(_services.AzureMapsKey);

                if (string.IsNullOrEmpty(state.SearchText) && string.IsNullOrEmpty(state.SearchAddress))
                {
                    // No entities identified, find nearby locations
                    var locationSet = await service.GetLocationsNearby(state.CurrentCoordinates.Latitude, state.CurrentCoordinates.Longitude);
                    await GetPointOfInterestLocationViewCards(sc, locationSet);
                }
                else if (!string.IsNullOrEmpty(state.SearchText))
                {
                    // Fuzzy search
                    var locationSet = await service.GetLocationsByFuzzyQueryAsync(state.CurrentCoordinates.Latitude, state.CurrentCoordinates.Longitude, state.SearchText, country);
                    await GetPointOfInterestLocationViewCards(sc, locationSet);
                }
                else if (!string.IsNullOrEmpty(state.SearchAddress))
                {
                    // Query search
                    var locationSet = await service.GetLocationsByFuzzyQueryAsync(state.CurrentCoordinates.Latitude, state.CurrentCoordinates.Longitude, state.SearchAddress, country);
                    await GetPointOfInterestLocationViewCards(sc, locationSet);
                }

                return(await sc.EndDialogAsync(true));
            }
            catch (Exception e)
            {
                TelemetryClient tc = new TelemetryClient();
                tc.TrackException(e);

                await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(PointOfInterestBotResponses.PointOfInterestErrorMessage, _responseBuilder));

                var state = await _accessors.PointOfInterestSkillState.GetAsync(sc.Context);

                state.Clear();
                await _accessors.PointOfInterestSkillState.SetAsync(sc.Context, state);

                return(await sc.CancelAllDialogsAsync());
            }
        }