예제 #1
0
        private async Task <DialogTurnResult> DbInstanceStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var entitiDetails = (EntitiDetails)stepContext.Options;

            switch (entitiDetails.Intent)
            {
            case "Acronym":
                return(await stepContext.NextAsync(entitiDetails.Acronym, cancellationToken));

            case "Build_Deployment":

                if (entitiDetails.Project == "DB-Deployment")
                {
                    if (entitiDetails.Buildwar == null)
                    {
                        entitiDetails.Buildwar = (string)stepContext.Result;
                    }
                    entitiDetails.DbInstance = entitiDetails.Environment;
                    return(await stepContext.NextAsync(entitiDetails, cancellationToken));

                    //return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("Please enter DB Instance name") }, cancellationToken);
                }
                else if (entitiDetails.Project == "RMI-Deployment")
                {
                    entitiDetails.DbInstance = "VPMTST1";
                    return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("Please enter the repository for deployment") }, cancellationToken));
                }
                else
                {
                    if (entitiDetails.Buildwar == null)
                    {
                        entitiDetails.Buildwar = (string)stepContext.Result;
                    }
                    return(await stepContext.NextAsync(entitiDetails, cancellationToken));
                }

            case "Trigger_Service":
                if (entitiDetails.Portfolio == "PCA" || entitiDetails.Portfolio == "CCV")
                {
                    if (entitiDetails.Tag == null && entitiDetails.Project.ToUpper() != "PRODUCTIONDAILYHEALTHCHECK")
                    {
                        entitiDetails.Tag = ((FoundChoice)stepContext.Result).Value.ToString();
                    }
                    if (entitiDetails.Tag == "DerivationLogic")
                    {
                        return(await stepContext.PromptAsync(nameof(ChoicePrompt),
                                                             new PromptOptions
                        {
                            Prompt = MessageFactory.Text("Please select the test"),
                            Choices = ChoiceFactory.ToChoices(new List <string> {
                                "DMUVDerivationForSingleSource", "DMUVDerivationForMultipleSources", "SubsetDerivationForSingleSource", "SubsetDerivationForMultipleSources"
                            }),
                            RetryPrompt = MessageFactory.Text("Sorry, I'm still learning. Please provide the valid option or below mentioned Sequence Number."),
                        }, cancellationToken));
                    }
                    else if (entitiDetails.Tag == "DMUVFunctionality")
                    {
                        return(await stepContext.PromptAsync(nameof(ChoicePrompt),
                                                             new PromptOptions
                        {
                            Prompt = MessageFactory.Text("Please select the test"),
                            Choices = ChoiceFactory.ToChoices(new List <string> {
                                "DateBand", "NoChange", "Subset", "SuperPayerDelta", "IndividualDelta", "POS", "CMUS", "MUE/NonMUE", "Undo", "NonMUEStateMedicaid", "SelectAllBulkActions"
                            }),
                            RetryPrompt = MessageFactory.Text("Sorry, I'm still learning. Please provide the valid option or below mentioned Sequence Number."),
                        }, cancellationToken));
                    }
                    else if (entitiDetails.Tag == "Custom")
                    {
                        return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("Please enter tag for customized execution.\n\n" + "For Single Ex: @Tag , For Multiple Ex: @Tag1,@Tag2") }, cancellationToken));
                    }
                    else if (entitiDetails.Tag == "AutoDerivation")
                    {
                        var entitiDetails1 = stepContext.Result != null
                                ?
                                             await LuisHelper.ExecuteLuisQuery(Configuration, Logger, stepContext.Context, cancellationToken)
                                 :
                                             new EntitiDetails();

                        var eDetails = (EntitiDetails)entitiDetails1;
                        entitiDetails.TravelDate = eDetails.TravelDate;
                    }

                    return(await stepContext.NextAsync(entitiDetails, cancellationToken));
                }
                else
                {
                    if (entitiDetails.Client == null && (entitiDetails.Project.ToUpper() != "PRODUCTIONDAILYHEALTHCHECK"))
                    {
                        if (/*entitiDetails.Project.ToUpper() != "ANNOCODER"&&*/ entitiDetails.Environment != "PROD")
                        {
                            entitiDetails.Client = ((FoundChoice)stepContext.Result).Value.ToString();
                        }
                        return(await stepContext.PromptAsync(nameof(ChoicePrompt),
                                                             new PromptOptions
                        {
                            Prompt = MessageFactory.Text("Please select the test"),
                            Choices = ChoiceFactory.ToChoices((entitiDetails.Project.ToUpper() == "ANNOCODER") ? new List <string> {
                                "Regression"
                            } : new List <string> {
                                "Smoke", "Regression"
                            }),
                            RetryPrompt = MessageFactory.Text("Sorry, I'm still learning. Please provide the valid option or below mentioned Sequence Number."),
                        }, cancellationToken));
                    }
                    else
                    {
                        return(await stepContext.NextAsync(entitiDetails, cancellationToken));
                    }
                }

            default:
                return(await stepContext.NextAsync(entitiDetails, cancellationToken));
            }
        }
        public void ShouldRenderChoicesAsAList()
        {
            var activity = ChoiceFactory.List(colorChoices, "select from:");

            Assert.AreEqual("select from:\n\n   1. red\n   2. green\n   3. blue", activity.Text);
        }
예제 #3
0
        /// <summary>
        /// AppendChoices is utility method to build up a message activity given all of the options.
        /// </summary>
        /// <param name="prompt">prompt.</param>
        /// <param name="channelId">channelId.</param>
        /// <param name="choices">choices to present.</param>
        /// <param name="style">listType.</param>
        /// <param name="options">options to control the choice rendering.</param>
        /// <param name="cancellationToken">cancellation Token.</param>
        /// <returns>bound activity ready to send to the user.</returns>
        protected virtual IMessageActivity AppendChoices(IMessageActivity prompt, string channelId, IList <Choice> choices, ListStyle style, ChoiceFactoryOptions options = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Get base prompt text (if any)
            var text = prompt != null && !string.IsNullOrEmpty(prompt.Text) ? prompt.Text : string.Empty;

            // Create temporary msg
            IMessageActivity msg;

            switch (style)
            {
            case ListStyle.Inline:
                msg = ChoiceFactory.Inline(choices, text, null, options);
                break;

            case ListStyle.List:
                msg = ChoiceFactory.List(choices, text, null, options);
                break;

            case ListStyle.SuggestedAction:
                msg = ChoiceFactory.SuggestedAction(choices, text);
                break;

            case ListStyle.HeroCard:
                msg = ChoiceFactory.HeroCard(choices, text);
                break;

            case ListStyle.None:
                msg      = Activity.CreateMessageActivity();
                msg.Text = text;
                break;

            default:
                msg = ChoiceFactory.ForChannel(channelId, choices, text, null, options);
                break;
            }

            // Update prompt with text, actions and attachments
            if (prompt != null)
            {
                // clone the prompt the set in the options (note ActivityEx has Properties so this is the safest mechanism)
                prompt = JsonConvert.DeserializeObject <Activity>(JsonConvert.SerializeObject(prompt));

                prompt.Text = msg.Text;

                if (msg.SuggestedActions != null && msg.SuggestedActions.Actions != null && msg.SuggestedActions.Actions.Count > 0)
                {
                    prompt.SuggestedActions = msg.SuggestedActions;
                }

                if (msg.Attachments != null && msg.Attachments.Any())
                {
                    prompt.Attachments = msg.Attachments;
                }

                return(prompt);
            }
            else
            {
                msg.InputHint = InputHints.ExpectingInput;
                return(msg);
            }
        }
예제 #4
0
        private async Task <DialogTurnResult> CompanyStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            // Get the Plan
            //try
            //{
            //    string food = BotMethods.GetDocument("eatingplan", "ButlerOverview.json", this.botConfig.Value.StorageAccountUrl, this.botConfig.Value.StorageAccountKey);
            //    plan = JsonConvert.DeserializeObject<Plan>(food);
            //    dayId = plan.Planday.FindIndex(x => x.Name == DateTime.Now.DayOfWeek.ToString().ToLower());
            //    valid = true;
            //}
            //catch
            //{
            //    valid = false;
            //}

            IMealService mealService = new MealService(this.clientFactory.CreateClient(), this.botConfig.Value);
            var          meals       = await mealService.GetMeals(string.Empty, string.Empty);

            var mealEnumerator = meals.GetEnumerator();

            this.planDay = new PlanDay();
            while (mealEnumerator.MoveNext())
            {
                if (string.IsNullOrEmpty(this.planDay.Restaurant1))
                {
                    this.planDay.Restaurant1 = mealEnumerator.Current.Restaurant;
                }

                if (string.IsNullOrEmpty(this.planDay.Restaurant2) && this.planDay.Restaurant1 != mealEnumerator.Current.Restaurant)
                {
                    this.planDay.Restaurant2 = mealEnumerator.Current.Restaurant;
                }
            }


            stepContext.Values["name"] = stepContext.Context.Activity.From.Name;
            if (companyStatus == "extern")
            {
                stepContext.Values["companyStatus"] = companyStatus;
                return(await stepContext.NextAsync());
            }
            else
            {
                //if (DateTime.Now.IsDaylightSavingTime())
                //{

                //    if (DateTime.Now.Hour > 12)
                //    {
                //        await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Es ist nach 12 Uhr. Bitte bestelle für einen anderen Tag."));
                //        return await stepContext.BeginDialogAsync(nameof(OrderForOtherDayDialog));
                //    }
                //}
                //else
                //{
                //    if (DateTime.Now.Hour + 1 > 12)
                //    {
                //        await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Es ist nach 12 Uhr. Bitte bestelle für einen anderen Tag."));
                //        return await stepContext.BeginDialogAsync(nameof(OrderForOtherDayDialog));
                //    }
                //}


                return(await stepContext.PromptAsync(
                           nameof(ChoicePrompt),
                           new PromptOptions
                {
                    Prompt = MessageFactory.Text(nextOrderDialogWhoPrompt),
                    Choices = ChoiceFactory.ToChoices(new List <string> {
                        nextOrderDialogMyself, nextOrderDialogTrainee, nextOrderDialogCostumer
                    }),
                    Style = ListStyle.HeroCard,
                }, cancellationToken));
            }
        }
예제 #5
0
        private void AddGetExactBeerNameDialog()
        {
            const string usualBeerDialog = "usualBeer";

            AddDialog(new WaterfallDialog(usualBeerDialog, new WaterfallStep[]
            {
                (stepContext, cancellationToken) =>
                {
                    string usualBeer = (string)stepContext.Options;
                    return(stepContext.PromptAsync(Inputs.Confirm, new PromptOptions
                    {
                        Prompt = MessageFactory.Text(
                            $"Would you like your usual {usualBeer}?",
                            $"Would you like your usual {usualBeer}?",
                            InputHints.ExpectingInput),
                    }, cancellationToken));
                },
                (stepContext, cancellationToken) =>
                {
                    var usualConfirmed = (bool)stepContext.Result;
                    if (usualConfirmed)
                    {
                        string usualBeer = (string)stepContext.Options;
                        return(stepContext.EndDialogAsync(usualBeer, cancellationToken));
                    }

                    return(stepContext.PromptAsync(Inputs.Text, new PromptOptions
                    {
                        Prompt = MessageFactory.Text("So what can I offer you instead?", "So what can I offer you instead?", InputHints.ExpectingInput),
                    }, cancellationToken));
                },
                (stepContext, cancellationToken) =>
                {
                    var beerName = (string)stepContext.Result;
                    return(stepContext.EndDialogAsync(beerName, cancellationToken));
                },
            }));

            AddDialog(new WaterfallDialog(DialogIds.GetExactBeerName, new WaterfallStep[]
            {
                async(stepContext, cancellationToken) =>
                {
                    var beerName = (string)stepContext.Options;
                    if (beerName != null)
                    {
                        return(await stepContext.NextAsync(beerName, cancellationToken));
                    }

                    var userInfo = await _userInfo.GetAsync(stepContext.Context, () => new UserInfo(), cancellationToken);
                    if (!string.IsNullOrEmpty(userInfo.UsualBeer))
                    {
                        return(await stepContext.BeginDialogAsync(usualBeerDialog, userInfo.UsualBeer, cancellationToken));
                    }

                    return(await stepContext.PromptAsync(Inputs.Text, new PromptOptions
                    {
                        Prompt = MessageFactory.Text("What beer would you like to order?", "What beer would you like to order?", InputHints.ExpectingInput),
                    }, cancellationToken));
                },
                async(stepContext, cancellationToken) =>
                {
                    var beerName = (string)stepContext.Result;
                    var beers    = await _beerService.BeersGetBySearchTermAsync(beerName, cancellationToken);
                    switch (beers.Count)
                    {
                    case 0:
                        await stepContext.Context.SendActivityAsync(
                            $"Oops! I haven't found any beer! {Emoji.Disappointed}",
                            "Oops! I haven't found any beer!",
                            cancellationToken: cancellationToken);
                        return(await stepContext.ReplaceDialogAsync(DialogIds.GetExactBeerName, cancellationToken: cancellationToken));

                    case 1:
                        return(await stepContext.EndDialogAsync(beers[0].Name, cancellationToken));

                    default:
                        {
                            var choices = ChoiceFactory.ToChoices(beers.Random(10).Select(beer => beer.Name).ToList());
                            return(await stepContext.PromptAsync(Inputs.Choice, new PromptOptions
                            {
                                Prompt = MessageFactory.Text(
                                    "I'm not sure which one",
                                    "I'm not sure which one"),
                                RetryPrompt = MessageFactory.Text(
                                    "I probably drank too much. I'm not sure which one.",
                                    "I probably drank too much. I'm not sure which one."),
                                Choices = choices,
                            }, cancellationToken));
                        }
                    }
                },
                (stepContext, cancellationToken) =>
                {
                    var beerChoice = (FoundChoice)stepContext.Result;
                    return(stepContext.EndDialogAsync(beerChoice.Value, cancellationToken));
                }
            }));
        }
        public void Create_WithEmptyChoiceText_ThrowsException(string choiceText)
        {
            var choice = ChoiceFactory.Create(choiceText, 0);

            Assert.That(choice, Is.Null);
        }
예제 #7
0
        /// <summary>
        /// Resolve everything is OK.
        /// </summary>
        private async Task <DialogTurnResult> ResolveIsEverythingOk(
            WaterfallStepContext stepContext,
            CancellationToken cancellationToken)
        {
            CustomerState customerState =
                await _customerService.GetCustomerStateById(stepContext.Context.Activity.From.Id);

            var whatToChange = stepContext.Result as FoundChoice;

            // Save name, if prompted.
            if (whatToChange == null)
            {
                await stepContext.Context.SendActivityAsync(ShowCartDialog.GetPrintableCart(customerState.Cart, "order"));

                await stepContext.Context.SendActivityAsync(GetPrintableCustomerInfo(customerState));

                return(await stepContext.PromptAsync(
                           ConfirmUserInfoPrompt,
                           new PromptOptions
                {
                    Prompt = MessageFactory.Text(Messages.GetUserInfoPromptIsOrderOk),
                    RetryPrompt = MessageFactory.Text(Messages.GetUserInfoPromptIsOrderOk + Messages.CancelPrompt),
                    Choices = ChoiceFactory.ToChoices(new List <string> {
                        Messages.Yes, Messages.No
                    }),
                },
                           cancellationToken));
            }
            else
            {
                switch (whatToChange.Value)
                {
                case Messages.Name:
                    customerState.Name = null;
                    break;

                case Messages.Email:
                    customerState.Email = null;
                    break;

                case Messages.PhoneNumber:
                    customerState.PhoneNumber = null;
                    break;

                case Messages.Address:
                    customerState.Address = null;
                    break;

                case Messages.PostCode:
                    customerState.PostCode = null;
                    break;

                case Messages.City:
                    customerState.City = null;
                    break;

                case Messages.IsAddressMatchShippingAddress:
                    customerState.IsShippingAdressMatch = null;
                    break;

                case Messages.ShippingName:
                    customerState.ShippingName = null;
                    break;

                case Messages.ShippingAddress:
                    customerState.ShippingAddress = null;
                    break;

                case Messages.ShippingPostCode:
                    customerState.ShippingPostCode = null;
                    break;

                case Messages.ShippingCity:
                    customerState.ShippingCity = null;
                    break;
                }

                await _customerService.UpdateCustomerState(customerState);

                stepContext.ActiveDialog.State["stepIndex"] = DialogIndex[whatToChange.Value];
                return(await stepContext.ContinueDialogAsync());
            }
        }
        private static async Task <DialogTurnResult> CategoryStep3Async(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            stepContext.Values["category2"] = ((FoundChoice)stepContext.Result).Value;
            string category2 = (string)stepContext.Values["category2"];

            var promptList = new List <string> {
                "T-Shirts", "PhotoFrames", "Bouquets"
            };

            var attachment = new List <Attachment>();
            var reply      = MessageFactory.Attachment(attachment);

            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

            if (category2 == "T-Shirts")
            {
                var cardDisplay1 = new Attachment();
                var cardDisplay2 = new Attachment();
                var cardDisplay3 = new Attachment();


                cardDisplay1.Name        = "Men Orange & Black Solid Casual T-shirt";
                cardDisplay1.ContentType = "image/png";
                cardDisplay1.ContentUrl  = "https://eshopstorage.blob.core.windows.net/res/Men_tshirt 1.png";

                cardDisplay2.Name        = "U.S. Polo Assn Men Fit Casual T-shirt";
                cardDisplay2.ContentType = "image/png";
                cardDisplay2.ContentUrl  = "https://eshopstorage.blob.core.windows.net/res/Men_tshirt 2.png";

                cardDisplay3.Name        = "Striped Men Hooded Neck Red, Black T-shirt";
                cardDisplay3.ContentType = "image/png";
                cardDisplay3.ContentUrl  = "https://eshopstorage.blob.core.windows.net/res/Men_tshirt 3.png";

                reply.Attachments.Add(cardDisplay1);
                reply.Attachments.Add(cardDisplay2);
                reply.Attachments.Add(cardDisplay3);

                promptList = new List <string> {
                    "Orange & Black shirt", "U.S. Polo shirt", "Hooded Neck shirt"
                };
            }

            else
            if (category2 == "Cakes")
            {
                var cardDisplay1 = new Attachment();
                var cardDisplay2 = new Attachment();
                var cardDisplay3 = new Attachment();


                cardDisplay1.Name        = "Mango & Strawberry flavored Cup cake";
                cardDisplay1.ContentType = "image/png";
                cardDisplay1.ContentUrl  = "https://eshopstorage.blob.core.windows.net/reswoman/Women_Cake 1.png";

                cardDisplay2.Name        = "Cream & Vanilla cup cakes";
                cardDisplay2.ContentType = "image/png";
                cardDisplay2.ContentUrl  = "https://eshopstorage.blob.core.windows.net/reswoman/Women_Cake 2.png";

                cardDisplay3.Name        = "Color full cake";
                cardDisplay3.ContentType = "image/png";
                cardDisplay3.ContentUrl  = "https://eshopstorage.blob.core.windows.net/reswoman/Women_Cake 3.png";

                reply.Attachments.Add(cardDisplay1);
                reply.Attachments.Add(cardDisplay2);
                reply.Attachments.Add(cardDisplay3);


                promptList = new List <string> {
                    "Mango & Strawberry cupcake", "Cream & Vanilla cupcake", "Color full cake"
                };
            }

            else
            if (category2 == "Candies")
            {
                var cardDisplay1 = new Attachment();
                var cardDisplay2 = new Attachment();
                var cardDisplay3 = new Attachment();


                cardDisplay1.Name        = "Color full candy";
                cardDisplay1.ContentType = "image/png";
                cardDisplay1.ContentUrl  = "https://eshopstorage.blob.core.windows.net/reskids/Kids_Candy 1.png";

                cardDisplay2.Name        = "All fruit flavored candies";
                cardDisplay2.ContentType = "image/png";
                cardDisplay2.ContentUrl  = "https://eshopstorage.blob.core.windows.net/reskids/Kids_Candy 2.png";

                cardDisplay3.Name        = "Candies";
                cardDisplay3.ContentType = "image/png";
                cardDisplay3.ContentUrl  = "https://eshopstorage.blob.core.windows.net/reskids/Kids_Candy 3.png";

                reply.Attachments.Add(cardDisplay1);
                reply.Attachments.Add(cardDisplay2);
                reply.Attachments.Add(cardDisplay3);


                promptList = new List <string> {
                    "Color full candy", "All fruit flavored candies", "Candies"
                };
            }
            // WaterfallStep always finishes with the end of the Waterfall or with another dialog; here it is a Prompt Dialog.
            // Running a prompt here means the next WaterfallStep will be run when the user's response is received.
            await stepContext.Context.SendActivityAsync($"Here are {stepContext.Values["category"]} collections");

            await stepContext.Context.SendActivityAsync(reply);

            return(await stepContext.PromptAsync(nameof(ChoicePrompt),

                                                 new PromptOptions
            {
                Prompt = MessageFactory.Text("  "),
                Choices = ChoiceFactory.ToChoices(new List <string> {
                    promptList[0], promptList[1], promptList[2]
                }),
            }, cancellationToken));
        }
        private static async Task <DialogTurnResult> CategoryStep2Async(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            stepContext.Values["category"] = ((FoundChoice)stepContext.Result).Value;
            string category = (string)stepContext.Values["category"];

            var promptList = new List <string> {
                "T-Shirts", "PhotoFrames", "Bouquets"
            };

            var attachment = new List <Attachment>();
            var reply      = MessageFactory.Attachment(attachment);

            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

            if (category == "Men")
            {
                var cardDisplay1 = new Attachment();
                var cardDisplay2 = new Attachment();
                var cardDisplay3 = new Attachment();


                cardDisplay1.Name        = "T-Shirts";
                cardDisplay1.ContentType = "image/png";
                cardDisplay1.ContentUrl  = "https://eshopstorage.blob.core.windows.net/res/Men_carousel_tshirts.png";

                cardDisplay2.Name        = "PhotoFrame";
                cardDisplay2.ContentType = "image/png";
                cardDisplay2.ContentUrl  = "https://eshopstorage.blob.core.windows.net/res/Men_carousel_photo frames.png";

                cardDisplay3.Name        = "Bouquets";
                cardDisplay3.ContentType = "image/png";
                cardDisplay3.ContentUrl  = "https://eshopstorage.blob.core.windows.net/res/Men_carousel_Bouquets.png";

                reply.Attachments.Add(cardDisplay1);
                reply.Attachments.Add(cardDisplay2);
                reply.Attachments.Add(cardDisplay3);

                promptList = new List <string> {
                    "T-Shirts", "PhotoFrames", "Bouquets"
                };
            }

            else
            if (category == "Women")
            {
                var cardDisplay1 = new Attachment();
                var cardDisplay2 = new Attachment();
                var cardDisplay3 = new Attachment();


                cardDisplay1.Name        = "Cosmetics";
                cardDisplay1.ContentType = "image/png";
                cardDisplay1.ContentUrl  = "https://eshopstorage.blob.core.windows.net/reswoman/Women_carousel_cosmetics.png";

                cardDisplay2.Name        = "Fashion";
                cardDisplay2.ContentType = "image/png";
                cardDisplay2.ContentUrl  = "https://eshopstorage.blob.core.windows.net/reswoman/Women_carousel_fashion.png";

                cardDisplay3.Name        = "Cakes";
                cardDisplay3.ContentType = "image/png";
                cardDisplay3.ContentUrl  = "https://eshopstorage.blob.core.windows.net/reswoman/Women_carousel_cakes.png";

                reply.Attachments.Add(cardDisplay1);
                reply.Attachments.Add(cardDisplay2);
                reply.Attachments.Add(cardDisplay3);

                promptList = new List <string> {
                    "Cosmetics", "Fashion", "Cakes"
                };
            }

            else
            if (category == "Kids")
            {
                var cardDisplay1 = new Attachment();
                var cardDisplay2 = new Attachment();
                var cardDisplay3 = new Attachment();


                cardDisplay1.Name        = "Toys";
                cardDisplay1.ContentType = "image/png";
                cardDisplay1.ContentUrl  = "https://eshopstorage.blob.core.windows.net/reskids/Kids_carousel_toys.png";

                cardDisplay2.Name        = "Candies";
                cardDisplay2.ContentType = "image/png";
                cardDisplay2.ContentUrl  = "https://eshopstorage.blob.core.windows.net/reskids/Kids_carousel_candy.png";

                cardDisplay3.Name        = "Fashion";
                cardDisplay3.ContentType = "image/png";
                cardDisplay3.ContentUrl  = "https://eshopstorage.blob.core.windows.net/reskids/Kids_carousel_fashion.png";

                reply.Attachments.Add(cardDisplay1);
                reply.Attachments.Add(cardDisplay2);
                reply.Attachments.Add(cardDisplay3);

                promptList = new List <string> {
                    "Toys", "Candies", "Fashion"
                };
            }
            // WaterfallStep always finishes with the end of the Waterfall or with another dialog; here it is a Prompt Dialog.
            // Running a prompt here means the next WaterfallStep will be run when the user's response is received.
            await stepContext.Context.SendActivityAsync($"Here are {stepContext.Values["category"]} collections");

            await stepContext.Context.SendActivityAsync(reply);

            return(await stepContext.PromptAsync(nameof(ChoicePrompt),

                                                 new PromptOptions
            {
                Prompt = MessageFactory.Text(""),
                Choices = ChoiceFactory.ToChoices(new List <string> {
                    promptList[0], promptList[1], promptList[2]
                }),
            }, cancellationToken));
        }
예제 #10
0
        private static async Task <DialogTurnResult> FindShopStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            string Input = (string)stepContext.Result;

            string     site    = Startup.KakaoAPI;
            string     query   = string.Format("{0}?query={1}", site, Input + " 서브웨이");
            WebRequest request = WebRequest.Create(query);
            string     rkey    = Startup.KakaoKey;

            string header = "KakaoAK " + rkey;

            request.Headers.Add("Authorization", header);

            WebResponse  response = request.GetResponse();
            Stream       stream   = response.GetResponseStream();
            StreamReader reader   = new StreamReader(stream, Encoding.UTF8);

            string json = reader.ReadToEnd();

            stream.Close();

            JObject jtemp = JObject.Parse(json);
            JArray  array = JArray.Parse(jtemp["documents"].ToString());

            var attachments = new List <Attachment>();
            var reply       = MessageFactory.Attachment(attachments);

            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

            List <string> places = new List <string>();

            places.Add("다시 검색하기");
            if (array.Count < 1)
            {
                await stepContext.Context.SendActivityAsync("검색 결과가 없습니다.");

                return(await stepContext.ReplaceDialogAsync(nameof(LocationDialog)));
            }
            foreach (JObject jobj in array)
            {
                string place_name   = jobj["place_name"].ToString();
                string phone        = jobj["phone"].ToString();
                string address_name = jobj["address_name"].ToString();
                places.Add(place_name);

                string id       = jobj["id"].ToString();
                string kakaoUrl = "https://map.kakao.com/link/to/" + id;

                var heroCard = new HeroCard
                {
                    Title    = place_name,
                    Subtitle = phone,
                    Text     = address_name,
                    Buttons  = new List <CardAction>
                    {
                        new CardAction(ActionTypes.OpenUrl, value: kakaoUrl, title: "카카오맵에서 확인하기"),
                        new CardAction(ActionTypes.PostBack, "여기서 주문하기", value: place_name)
                    },
                };
                reply.Attachments.Add(heroCard.ToAttachment());
            }
            await stepContext.Context.SendActivityAsync(MessageFactory.Text("주문할 서브웨이 지점을 선택하세요"), cancellationToken);

            await stepContext.Context.SendActivityAsync(reply, cancellationToken);

            return(await stepContext.PromptAsync(nameof(ChoicePrompt),
                                                 new PromptOptions
            {
                Choices = ChoiceFactory.ToChoices(places),
            }, cancellationToken));
        }
        private async Task <DialogTurnResult> IntroStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var processDetails = (ProcessDetails)stepContext.Options;
            var text           = string.Empty;
            var rpaService     = new RPAService();
            var response       = rpaService.GetConversationFlow(stepContext.Context.Activity.Conversation.Id);
            var result         = JsonConvert.DeserializeObject <List <ConversationFlow> >(response.Content);

            if (result.Count > 0)
            {
                processDetails.CurrentQuestion = result[0];
                if (processDetails.CurrentQuestion.u_last_question_index == 0 && processDetails.AttemptCount == 0)
                {
                    text = "Process " + processDetails.ProcessSelected.Name + " needs input parameters, please start entering them below.";
                }
                else if (processDetails.AttemptCount != 0 && processDetails.CurrentQuestion.u_last_question_index == 0)
                {
                    text = "Input parameters entered are incorrect, please re-enter them below.";
                }

                //delete record from SN
                rpaService.DeactivatedConversationFlow(processDetails.CurrentQuestion.sys_id, stepContext.Context.Activity.Conversation.Id);
                if (processDetails.CurrentQuestion.u_type.Contains("Bool"))
                {
                    var boolParamTrue = JsonConvert.SerializeObject(new PromptOption {
                        Id = "boolParam", Value = "true"
                    });
                    var boolParamFalse = JsonConvert.SerializeObject(new PromptOption {
                        Id = "boolParam", Value = "false"
                    });
                    var choices = new List <Choice> {
                        new Choice
                        {
                            Value  = "true",
                            Action = new CardAction(ActionTypes.PostBack, "true", null, "true", "true", value: boolParamTrue, null)
                        },
                        new Choice
                        {
                            Value  = "false",
                            Action = new CardAction(ActionTypes.PostBack, "false", null, "false", "false", value: boolParamFalse, null)
                        }
                    };
                    return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = (Activity)ChoiceFactory.SuggestedAction(choices, text + Environment.NewLine + "For " + processDetails.CurrentQuestion.u_param_name.UppercaseFirst() + " choose one option below.") }, cancellationToken));
                }
                else
                {
                    return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text(text + Environment.NewLine + "Enter " + processDetails.CurrentQuestion.u_param_name.UppercaseFirst() + ":") }, cancellationToken));
                }
            }
            else
            {
                processDetails.CurrentQuestion = new ConversationFlow();
                //get parameters entered

                return(await stepContext.NextAsync(processDetails, cancellationToken));
            }
        }
예제 #12
0
        public MainMenuHelperDialog(IStatePropertyAccessor <SelectedLanguageState> selectedLanguagePropertyAccessor, IStatePropertyAccessor <CustomWrapperPromptState> customWrapperPromptStateAccessor) : base(MainMenuHelperDialogId)
        {
            this._selectedLanguageStatePropertyAccessor    = selectedLanguagePropertyAccessor;
            this._customWrapperPromptStatePropertyAccessor = customWrapperPromptStateAccessor;
            this.InitialDialogId = MainMenuHelperDialogId;

            List <string> _mainMenuChoices = new List <string>()
            {
                "FAQ QnAMaker", "Azure Search", "Azure Search Facets", "Adaptive Card", "Choose Language"
            };
            ChoicePrompt cp = new ChoicePrompt("choicePrompt");

            cp.Style = ListStyle.SuggestedAction;

            this.AddDialog(cp);
            this.AddDialog(new QnAMakerDialog("QnADialog"));
            this.AddDialog(new AzureSearchDialog("AzureSearchDialog", selectedLanguagePropertyAccessor));
            this.AddDialog(new AzureSearchFacetsDialog("AzureSearchFacetsDialog"));
            this.AddDialog(new AdaptiveCardDialog("AdaptiveCardDialog", customWrapperPromptStateAccessor));
            this.AddDialog(new ChooseLanguageDialog("ChooseLanguageDialog", selectedLanguagePropertyAccessor));

            // Define the conversation flow using the waterfall model.
            this.AddDialog(
                new WaterfallDialog(this.InitialDialogId, new WaterfallStep[]
            {
                async(stepContext, ct) =>
                {
                    SelectedLanguageState selectedLanguage = await _selectedLanguageStatePropertyAccessor.GetAsync(
                        stepContext.Context,
                        () => new SelectedLanguageState()
                    {
                        SelectedLanguage = "en-us"
                    },
                        ct);

                    var cultureInfo = LanguageService.LanguageChoiceMap.ContainsKey(selectedLanguage.SelectedLanguage) ? new CultureInfo(LanguageService.LanguageChoiceMap[selectedLanguage.SelectedLanguage]) : new CultureInfo("en-us");
                    CultureInfo.CurrentUICulture = CultureInfo.CurrentCulture = cultureInfo;

                    return(await stepContext.PromptAsync(
                               "choicePrompt",
                               new PromptOptions
                    {
                        Choices = ChoiceFactory.ToChoices(new List <string> {
                            MainMenuHelperDialogStrings.Option1, MainMenuHelperDialogStrings.Option2, MainMenuHelperDialogStrings.Option3, MainMenuHelperDialogStrings.Option4, MainMenuHelperDialogStrings.Option5
                        }),
                        Prompt = MessageFactory.Text(MainMenuHelperDialogStrings.Prompt),
                        RetryPrompt = MessageFactory.Text(MainMenuHelperDialogStrings.RetryPrompt)
                    },
                               ct
                               ).ConfigureAwait(false));
                },
                async(stepContext, ct) =>
                {
                    var menuChoice = ((FoundChoice)stepContext.Result).Value;

                    SelectedLanguageState selectedLanguage = await _selectedLanguageStatePropertyAccessor.GetAsync(
                        stepContext.Context,
                        () => new SelectedLanguageState()
                    {
                        SelectedLanguage = "en-us"
                    },
                        ct);

                    var cultureInfo = LanguageService.LanguageChoiceMap.ContainsKey(selectedLanguage.SelectedLanguage) ? new CultureInfo(LanguageService.LanguageChoiceMap[selectedLanguage.SelectedLanguage]) : new CultureInfo("en-us");
                    CultureInfo.CurrentUICulture = CultureInfo.CurrentCulture = cultureInfo;

                    if (menuChoice == MainMenuHelperDialogStrings.Option1)
                    {
                        return(await stepContext.BeginDialogAsync("QnADialog"));
                    }
                    else if (menuChoice == MainMenuHelperDialogStrings.Option2)
                    {
                        return(await stepContext.BeginDialogAsync("AzureSearchDialog"));
                    }
                    else if (menuChoice == MainMenuHelperDialogStrings.Option3)
                    {
                        return(await stepContext.BeginDialogAsync("AzureSearchFacetsDialog"));
                    }
                    else if (menuChoice == MainMenuHelperDialogStrings.Option4)
                    {
                        return(await stepContext.BeginDialogAsync("AdaptiveCardDialog"));
                    }
                    else if (menuChoice == MainMenuHelperDialogStrings.Option5)
                    {
                        return(await stepContext.BeginDialogAsync("ChooseLanguageDialog"));
                    }
                    else
                    {
                    }

                    return(await stepContext.NextAsync().ConfigureAwait(false));
                },
                async(stepContext, ct) =>
                {
                    return(await stepContext.ReplaceDialogAsync(MainMenuHelperDialogId).ConfigureAwait(false));
                }
            }
                                    )
                );
        }
예제 #13
0
        public AzureSearchFacetsDialog(string dialogId) : base(dialogId)
        {
            const string imageBaseURI = @"https://andysa.blob.core.windows.net/search/OSL%202019/";

            // ID of the child dialog that should be started anytime the component is started.
            this.InitialDialogId = dialogId;

            this.AddDialog(new ChoicePrompt("navigatePrompt"));

            // Define the conversation flow using the waterfall model.
            this.AddDialog(
                new WaterfallDialog(dialogId, new WaterfallStep[]
            {
                async(stepContext, ct) =>
                {
                    List <string> _dayChoices = new List <string>()
                    {
                        "Any"
                    };

                    var facets = SearchService.FindFacets("day", null);
                    facets.Values.ToList().ForEach(i => i.ToList().ForEach(j => _dayChoices.Add(j.Value.ToString())));
                    //_dayChoices.AddRange(facets.Select(_ => _.Key));

                    return(await stepContext.PromptAsync(
                               "navigatePrompt",
                               new PromptOptions
                    {
                        Choices = ChoiceFactory.ToChoices(_dayChoices),
                        Prompt = MessageFactory.Text("[Azure Search Facets Dialog] What day would you like to hear more information about the event?"),
                        RetryPrompt = MessageFactory.Text("Please tell me which day you would like to hear more information?")
                    },
                               ct
                               ).ConfigureAwait(false));
                },
                async(stepContext, ct) =>
                {
                    var userAnswer   = ((FoundChoice)stepContext.Result).Value;
                    this.selectedDay = userAnswer;

                    await stepContext.Context.SendActivityAsync("what Genres would you like to see on" + userAnswer + "?");

                    List <string> _dayChoices = new List <string>()
                    {
                    };
                    string searchStr = "day:" + userAnswer;
                    if (userAnswer == "Any")
                    {
                        searchStr        = null;
                        this.selectedDay = null;
                    }

                    var facets = SearchService.FindFacets("genre", searchStr);
                    facets.Values.ToList().ForEach(i => i.ToList().ForEach(j => _dayChoices.Add(j.Value.ToString())));
                    //_dayChoices.AddRange(facets.Select(_ => _.Key));

                    return(await stepContext.PromptAsync(
                               "navigatePrompt",
                               new PromptOptions
                    {
                        Choices = ChoiceFactory.ToChoices(_dayChoices),
                        Prompt = MessageFactory.Text("[Azure Search Facets Dialog] Here are all the genres for " + userAnswer + "?"),
                        RetryPrompt = MessageFactory.Text("Please tell me which genre you would like to hear information?")
                    },
                               ct
                               ).ConfigureAwait(false));
                },
                async(stepContext, ct) =>
                {
                    var userAnswer = ((FoundChoice)stepContext.Result).Value;

                    await stepContext.Context.SendActivityAsync("Based on what you've told me, here are the results you're looking for!");

                    var perf = SearchService.FindPerformances(null, userAnswer, this.selectedDay);

                    List <HeroCard> cards = new List <HeroCard>();
                    foreach (BO.Performance p in perf)
                    {
                        cards.Add(HeroCardService.GetHeroCard(
                                      p.BandName,
                                      p.Description,
                                      null,
                                      imageBaseURI,
                                      new List <string>()
                        {
                            p.Image
                        },
                                      null,
                                      null
                                      ));
                    }

                    var reply = CarouselCardService.GenerateCarouselCard(
                        stepContext.Context,
                        cards.Select(_ => _.ToAttachment()).ToList <Attachment>());

                    await stepContext.Context.SendActivityAsync(reply);

                    return(await stepContext.NextAsync().ConfigureAwait(false));
                }
            }
                                    )
                );
        }
예제 #14
0
        private async Task <DialogTurnResult> PortfolioStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var entitiDetails = (EntitiDetails)stepContext.Options;

            switch (entitiDetails.Intent)
            {
            case "Acronym":
                return(await stepContext.NextAsync(entitiDetails.Acronym, cancellationToken));

            case "Trigger_Service":
                if (entitiDetails.Portfolio == null)
                {
                    entitiDetails.Portfolio = entitiDetails.Portfolio = ((FoundChoice)stepContext.Result).Value.ToString();
                }
                if (!string.IsNullOrEmpty(entitiDetails.Project))
                {
                    if (entitiDetails.Tag == "AutoDerivation" && string.IsNullOrEmpty(entitiDetails.Environment) || entitiDetails.Tag == "CommitFile")
                    {
                        return(await stepContext.PromptAsync(nameof(ChoicePrompt),
                                                             new PromptOptions
                        {
                            Prompt = MessageFactory.Text("Please select the environment"),
                            Choices = ChoiceFactory.ToChoices(new List <string> {
                                "DEV", "QA", "UAT", "PROD"
                            }),
                            Style = ListStyle.Auto,
                            RetryPrompt = MessageFactory.Text("Sorry, I'm still learning. Please provide the valid option or below mentioned Sequence Number."),
                        }, cancellationToken));
                    }
                    if (entitiDetails.Project.ToUpper() == "PRODUCTIONDAILYHEALTHCHECK" && string.IsNullOrEmpty(entitiDetails.Portfolio))
                    {
                        entitiDetails.Portfolio = ((FoundChoice)stepContext.Result).Value.ToString();
                    }
                    return(await stepContext.NextAsync(entitiDetails, cancellationToken));
                }

                //if (entitiDetails.Project == "ProductionDailyHealthCheck")
                //    return await stepContext.NextAsync(entitiDetails, cancellationToken);
                if (entitiDetails.Portfolio.ToUpper() == "PCA")
                {
                    return(await stepContext.PromptAsync(nameof(ChoicePrompt),
                                                         new PromptOptions
                    {
                        Prompt = MessageFactory.Text("Please select the project"),
                        Choices = GetProjectChoices(entitiDetails.Portfolio),
                        Style = ListStyle.List,
                        RetryPrompt = MessageFactory.Text("Sorry, I'm still learning. Please provide the valid option or below mentioned Sequence Number."),
                    }, cancellationToken));
                }
                else if (entitiDetails.Portfolio.ToUpper() == "CCV")
                {
                    return(await stepContext.PromptAsync(nameof(ChoicePrompt),
                                                         new PromptOptions
                    {
                        Prompt = MessageFactory.Text("Please select the project"),
                        Choices = GetProjectChoices(entitiDetails.Portfolio),
                        Style = ListStyle.Auto,
                        RetryPrompt = MessageFactory.Text("Sorry, I'm still learning. Please provide the valid option or below mentioned Sequence Number."),
                    }, cancellationToken));
                }
                //else if (entitiDetails.Tag.Contains("AutoDerivation"))
                //{

                //    return await stepContext.NextAsync(entitiDetails, cancellationToken);
                //}
                else
                {
                    return(await stepContext.PromptAsync(nameof(ChoicePrompt),
                                                         new PromptOptions
                    {
                        Prompt = MessageFactory.Text("Please select the project"),
                        Choices = GetProjectChoices(entitiDetails.Portfolio),
                        Style = ListStyle.Auto,
                        RetryPrompt = MessageFactory.Text("Sorry, I'm still learning. Please provide the valid option or below mentioned Sequence Number."),
                    }, cancellationToken));
                }

            case "Build_Deployment":
                if (!string.IsNullOrEmpty(entitiDetails.Project))
                {
                    return(await stepContext.NextAsync(entitiDetails, cancellationToken));
                }
                //entitiDetails.Portfolio = entitiDetails.Portfolio = ((FoundChoice)stepContext.Result).Value.ToString();
                return(await stepContext.PromptAsync(nameof(ChoicePrompt),
                                                     new PromptOptions
                {
                    Prompt = MessageFactory.Text("Please select the project"),
                    Choices = GetProjectChoices(entitiDetails.Intent),
                    Style = ListStyle.Auto,
                    RetryPrompt = MessageFactory.Text("Sorry, I'm still learning. Please provide the valid option or below mentioned Sequence Number."),
                }, cancellationToken));

            default:
                return(await stepContext.NextAsync(entitiDetails.Project, cancellationToken));
            }
        }
 private static async Task ShowChoices(ITurnContext turnContext, CancellationToken cancellationToken)
 {
     // Create the message
     var message = ChoiceFactory.ForChannel(turnContext.Activity.ChannelId, _options, "Secondary Bot: Please type a message or choose an option");
     await turnContext.SendActivityAsync(message, cancellationToken);
 }
        //Check if input is empty or additionally it is asked to filter for countries, then add country option list
        private async Task <DialogTurnResult> SelectionStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            // Continue using the same selection list, if any, from the previous iteration of this dialog.
            var list = stepContext.Options as List <string> ?? new List <string>();

            bool filterForCountry = false;

            if (stepContext.Options.GetType().ToString().Equals("Microsoft.BotBuilderSamples.FilterForWordDetails"))
            {
                FilterForWordDetails filterForWordDetails = (FilterForWordDetails)stepContext.Options;
                usedColumn = filterForWordDetails.usedColumn;
                // Check if filter for Word Dialog input is empty
                if (filterForWordDetails.columnName == null)
                {
                    string messageNull   = "I could not recognize what column you want to apply that filter to. Please say something like \"Filter for Germany and Canada\"";
                    var    cancelMessage = MessageFactory.Text(messageNull, CancelMsgText, InputHints.IgnoringInput);
                    await stepContext.Context.SendActivityAsync(cancelMessage, cancellationToken);

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

                //Filter for country
                for (int i = 0; i < filterForWordDetails.columnName.Length; i++)
                {
                    string s = UppercaseFirst(filterForWordDetails.columnName[i]);
                    list.Add(s);

                    //becomes true when you enter "filter for country"
                    if (string.Equals(s, "Country") || string.Equals(s, "Countries"))
                    {
                        filterForCountry = true;
                    }
                }

                if ((filterForWordDetails.country == null) && (filterForWordDetails.segment == null) && (filterForWordDetails.product == null) && !filterForCountry)
                {
                    string messageNull = "I could not recognize what column you want to apply that filter to. Please say something like \"Filter for Germany and Canada\"";

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

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


                //Breaks if we did not recognize any countries
                if (!filterForCountry)
                {
                    filterForWordDetails.columnName = list.ToArray();
                    ConsoleWriter.WriteLineInfo("Filter for: " + string.Join(", ", list));
                    ConsoleWriter.WriteLineInfo("ColumnName: " + filterForWordDetails.columnName[0]);
                    await BOT_Api.SendFilterForWord(stepContext, usedColumn, list.ToArray());

                    return(await stepContext.EndDialogAsync(filterForWordDetails.columnName));
                }
            }


            //if user entered "FILTER FOR COUNTRY" OR "COUNTRIES":

            stepContext.Values[CountriesSelected] = list;
            //Create a prompt message
            string message;

            if (list[0] == "Country")
            {
                message = $"Please choose a country to filter to finish.";
                list.Remove("Country");
            }
            else if (list[0] == "Countries")
            {
                message = $"Please choose a country to filter to finish.";
                list.Remove("Countries");
            }
            else
            {
                message = $"You have selected **{String.Join(", ", list)}**. You can filter for an additional country, " +
                          $"or choose `{DoneOption}` to finish.";
            }

            // Create the list of options to choose from.
            var options = _countryOptions.ToList();

            if (list.Count > 0)
            {
                options.Add(DoneOption);
                options = options.Except(list).ToList();
            }

            var promptOptions = new PromptOptions
            {
                Prompt      = MessageFactory.Text(message),
                RetryPrompt = MessageFactory.Text("Please choose an option from the list."),
                Choices     = ChoiceFactory.ToChoices(options),
            };

            // Prompt the user for a choice.
            return(await stepContext.PromptAsync(nameof(ChoicePrompt), promptOptions, cancellationToken));
        }
예제 #17
0
        private async Task <DialogTurnResult> HandleChoiceAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Get the user's info. (Since the type factory is null, this will throw if state does not yet have a value for user info.)
            //UserInfo userInfo = await _accessors.UserInfoAccessor.GetAsync(stepContext.Context, null, cancellationToken);

            // Check the user's input and decide which dialog to start.
            // Pass in the guest info when starting either of the child dialogs.
            string choice = (stepContext.Result as string)?.Trim()?.ToLowerInvariant();

            switch (choice)
            {
            case "1":
            case "adaptive card":
                //return await stepContext.BeginDialogAsync(CardsExampleDialogId, userInfo.Guest, cancellationToken);
                var reply = stepContext.Context.Activity.CreateReply();

                reply.Attachments = new List <Attachment>();

                var adaptiveCardJson = await Demo.Cards.CardsUtility.GetCardText("Locations");

                AdaptiveCardParseResult adaptiveCard;
                try
                {
                    adaptiveCard = AdaptiveCard.FromJson(adaptiveCardJson);
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                var card = adaptiveCard.Card;

                reply.Attachments.Add(new Attachment()
                {
                    Content     = card,
                    ContentType = AdaptiveCard.ContentType,
                    Name        = "Card"
                });

                await stepContext.Context.SendActivityAsync("This is an example of an Adaptive Card.  Adaptive cards can be customized.  View more at https://adaptivecards.io");

                await stepContext.Context.SendActivityAsync(reply, cancellationToken);

                return(Dialog.EndOfTurn);

            case "2":
            case "animation card":

                var animationCardReply = stepContext.Context.Activity.CreateReply();

                var animationCard = new AnimationCard()
                {
                    Title    = "Getting started with Microsoft Bot Framework and Azure Bot Services",
                    Text     = "Animation Card Text",
                    Subtitle = "Animation Card Subtitle",
                    Buttons  = new List <CardAction> {
                        new CardAction(type: "messageBack", title: "Button 1")
                    },
                    Media = new List <MediaUrl> {
                        new MediaUrl(url: "https://www.youtube.com/watch?v=EP3ShiJVpW8")
                    }
                };

                // Add the card to our reply.
                animationCardReply.Attachments = new List <Attachment>()
                {
                    animationCard.ToAttachment()
                };

                await stepContext.Context.SendActivityAsync(animationCardReply, cancellationToken);

                // ContinueDialog doesn't wait for user input and keeps moving through the "waterfall"
                return(await stepContext.ContinueDialogAsync());

            case "3":
            case "audio card":

                var audioCardReply = stepContext.Context.Activity.CreateReply();

                var audioCard = new AudioCard()
                {
                    Title    = "Jazz Trio",
                    Text     = "Audio Card Text",
                    Subtitle = "Audio Card Subtitle",
                    Media    = new List <MediaUrl> {
                        new MediaUrl(url: "https://ccrma.stanford.edu/~jos/mp3/JazzTrio.mp3")
                    }
                };

                // Add the card to our reply.
                audioCardReply.Attachments = new List <Attachment>()
                {
                    audioCard.ToAttachment()
                };

                await stepContext.Context.SendActivityAsync(audioCardReply, cancellationToken);

                string[] choices = new string[] { "This is great!", "Show me more." };
                await stepContext.PromptAsync(
                    ChoicePrompt,
                    new PromptOptions
                {
                    Prompt  = MessageFactory.Text("What do you think?"),
                    Choices = ChoiceFactory.ToChoices(choices),
                },
                    cancellationToken);

                return(Dialog.EndOfTurn);

            case "4":
            case "hero card":
                // Present the user with a set of "suggested actions".
                //List<string> menu = new List<string> { "Reserve Table", "Wake Up" };

                //await stepContext.Context.SendActivityAsync(MessageFactory.SuggestedActions(menu, "How can I help you?"), cancellationToken: cancellationToken);

                //return Dialog.EndOfTurn;

                var heroCardReply = stepContext.Context.Activity.CreateReply();

                // Create a HeroCard with options for the user to choose to interact with the bot.
                var heroCard = new HeroCard
                {
                    Text     = "This is an example of a Hero Card.  Select an option to view other card options.",
                    Subtitle = "This is the subtitle of the hero card.",
                    Title    = "This is the title of the hero card.",
                    Images   = new List <CardImage> {
                        new CardImage("https://dev.botframework.com/Client/Images/ChatBot-BotFramework.png", "Example Image"), new CardImage("https://dev.botframework.com/Client/Images/CognitiveServices.png", "Example Image 2")
                    },
                    Buttons = new List <CardAction>()
                    {
                        new CardAction(ActionTypes.Call, title: "Call", value: "+11234567890"),
                        new CardAction(ActionTypes.OpenUrl, title: "Open Url", value: "https://dev.botframework.com"),
                    }
                };

                // Add the card to our reply.
                heroCardReply.Attachments = new List <Attachment>()
                {
                    heroCard.ToAttachment()
                };

                await stepContext.Context.SendActivityAsync(heroCardReply, cancellationToken);

                return(Dialog.EndOfTurn);

            case "5":
            case "thumbnail card":

                var thumbnailCardReply = stepContext.Context.Activity.CreateReply();

                var thumbnailCard = new ThumbnailCard
                {
                    Title    = "Thumbnail Card Title",
                    Subtitle = "Subtitle",
                    Text     = "Learn more about how to use Language Understanding with your bot.",
                    Buttons  = new List <CardAction> {
                        new CardAction("openUrl", "Learn More", value: "https://azure.microsoft.com/en-us/services/cognitive-services/language-understanding-intelligent-service/"), new CardAction("postBack", "Got it", value: "::gotit::")
                    },
                    Images = new List <CardImage>
                    {
                        new CardImage("https://dev.botframework.com/Client/Images/learn-more-icons/luis.png", "LUIS", new CardAction("openUrl", "Language Understanding", value: "https://azure.microsoft.com/en-us/services/cognitive-services/language-understanding-intelligent-service/")),
                    },
                };

                thumbnailCardReply.Attachments = new List <Attachment>()
                {
                    thumbnailCard.ToAttachment()
                };

                await stepContext.Context.SendActivityAsync(thumbnailCardReply, cancellationToken);

                return(Dialog.EndOfTurn);

            case "6":
            case "receipt card":

                var receiptCardReply = stepContext.Context.Activity.CreateReply();

                var receiptCard = new ReceiptCard
                {
                    Title = "Example Receipt Card",
                    Facts = new List <Fact>
                    {
                        new Fact("Name:", "Adam"),
                        new Fact("Company:", "Microsoft"),
                        new Fact("Location:", "Redmond, WA"),
                        new Fact("Website:", "https://www.microsoft.com"),
                        new Fact("----------", ""),
                        new Fact("Order Number:", "912304"),
                        new Fact("Payment Method:", "Visa *1234"),
                        new Fact("----------", ""),
                    },
                    Items = new List <ReceiptItem>
                    {
                        new ReceiptItem("Bing Spell Check", "sku: 123456", "Spell check for your bot", new CardImage("https://dev.botframework.com/Client/Images/learn-more-icons/bing_spell_check.png"), "$1.00", "1000"),
                        new ReceiptItem("Text Analytics API", "sku: 65421", "Analytics, Sentiment and more", new CardImage("https://dev.botframework.com/Client/Images/learn-more-icons/text_analytics_api.png"), "$2.00", "2000")
                    },
                    Tax   = "$12.45",
                    Total = "$5,000"
                };

                receiptCardReply.Attachments = new List <Attachment>()
                {
                    receiptCard.ToAttachment()
                };

                await stepContext.Context.SendActivityAsync(receiptCardReply, cancellationToken);

                return(Dialog.EndOfTurn);

            case "7":
            case "signin card":

                var signinCardReply = stepContext.Context.Activity.CreateReply();

                var signinCard = new SigninCard
                {
                    Text    = "Sign In to your Account",
                    Buttons = new List <CardAction>
                    {
                        new CardAction("signin", "Sign In", value: "https://login.microsoftonline.com/common/oauth/v2.0/authorize?client_id={CLIENT_ID}&scope={SCOPE}")
                    }
                };

                signinCardReply.Attachments = new List <Attachment> {
                    signinCard.ToAttachment()
                };

                await stepContext.Context.SendActivityAsync(signinCardReply, cancellationToken);

                return(Dialog.EndOfTurn);

            case "8":
            case "video card":

                var videoCardReply = stepContext.Context.Activity.CreateReply();

                var videoCard = new VideoCard
                {
                    Title    = "Getting started with Microsoft Bot Framework and Azure Bot Services",
                    Text     = "Animation Card Text",
                    Subtitle = "Animation Card Subtitle",
                    Buttons  = new List <CardAction> {
                        new CardAction(type: "messageBack", title: "Video Card Button")
                    },
                    Media = new List <MediaUrl> {
                        new MediaUrl(url: "https://www.youtube.com/watch?v=EP3ShiJVpW8")
                    },
                };

                videoCardReply.Attachments = new List <Attachment> {
                    videoCard.ToAttachment()
                };

                await stepContext.Context.SendActivityAsync(videoCardReply, cancellationToken);

                return(Dialog.EndOfTurn);

            case "9":
            case "carousel card":

                var carouselCardReply = stepContext.Context.Activity.CreateReply();

                carouselCardReply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

                var carouselCard1 = new HeroCard
                {
                    Title  = "Title 1",
                    Text   = "Text 1",
                    Images = new List <CardImage> {
                        new CardImage("https://dev.botframework.com/Client/Images/learn-more-icons/bing_speech_api.png")
                    }
                };

                var carouselCard2 = new HeroCard
                {
                    Title  = "Title 2",
                    Text   = "Text 2",
                    Images = new List <CardImage> {
                        new CardImage("https://dev.botframework.com/Client/Images/learn-more-icons/luis.png")
                    }
                };

                carouselCardReply.Attachments = new List <Attachment> {
                    carouselCard1.ToAttachment(), carouselCard2.ToAttachment()
                };

                await stepContext.Context.SendActivityAsync(carouselCardReply, cancellationToken);

                return(Dialog.EndOfTurn);

            case "10":
            case "go back":
                return(await stepContext.EndDialogAsync());

            default:
                // If we don't recognize the user's intent, start again from the beginning.
                await stepContext.Context.SendActivityAsync(
                    "Sorry, I don't understand that command. Please choose an option from the list.");

                return(await stepContext.ReplaceDialogAsync(Id, null, cancellationToken));
            }
        }
예제 #18
0
        private PromptOptions BuildOptions(WaterfallStepContext stepContext, ChatState state)
        {
            Stanza current = null;
            string text    = "";

            while (true)
            {
                current = proc.GetStanza(state.CurrentStanzaID);
                if (text.Length > 0)
                {
                    text += "\n";
                }

                text += proc.GetPhrase(((InstructionStanza)current).Text).Internal;

                if (!current.HasNext || current.StanzaType == "Question" || current.Next[0] == "end")
                {
                    break;
                }
                state.CurrentStanzaID = current.Next[0];
            }

            if (current.StanzaType == "Question")
            {
                QuestionStanza qs = (QuestionStanza)current;

                IList <Choice> choices = new List <Choice>();

                for (int i = 0; i < qs.Answers.Length; i += 1)
                {
                    var choice = new Choice
                    {
                        Value = proc.GetPhrase(qs.Answers[i]).Internal
                    };
                    if (choice.Value.ToLower().StartsWith("yes"))
                    {
                        choice.Synonyms = new List <string> {
                            "yes", "yup", "y"
                        };
                    }
                    else if (choice.Value.ToLower().StartsWith("no"))
                    {
                        choice.Synonyms = new List <string> {
                            "no", "nope", "n"
                        };
                    }
                    choices.Add(choice);
                }

                return(new PromptOptions {
                    Prompt = MessageFactory.Text(text), Choices = choices.ToArray()
                });
            }

            if (!current.HasNext || current.Next[0] == "end")
            {
                stepContext.Values[DoneKey] = true;
            }

            return(new PromptOptions {
                Prompt = MessageFactory.Text(text), Choices = ChoiceFactory.ToChoices(new string[] { "OK" })
            });
        }
예제 #19
0
        private async Task <DialogTurnResult> ParseAllGivenInformationStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var luisResult = (LuisResult)stepContext.Options;

            var documentModel = new AccountDocumentModel
            {
                //get ira or standard account type
                AccountType = GetEntityModelResolution(luisResult, AccountTypeEntity),
                //get account document
                AccountDocument = GetEntityModelResolution(luisResult, DocumentTypeEntity)
            };


            documentModel.SetIsIra(); //determines if account is an IRA acct or Standard

            //if any account type was specified.
            if (documentModel.IsIra.HasValue)
            {
                stepContext.Values[DocumentModelValue] = documentModel;

                //the account requested is an IRA
                if (documentModel.IsIra == 1)
                {
                    return(await DispatchIraAccountDocumentAsync(stepContext, documentModel, cancellationToken));
                }

                //account is standard
                return(await DispatchNonIraAccountDocumentAsync(stepContext, documentModel, cancellationToken));
            }
            else
            {
                //no account has been supplied

                //if the document specified is an IRA transfer form, but the user did not specify IRA
                if (Common.IraOnlyDocumentTypes.Contains(documentModel.AccountDocument))
                {
                    documentModel.AccountType = "ira";
                    stepContext.Values[DocumentModelValue] = documentModel;
                    return(await DispatchIraAccountDocumentAsync(stepContext, documentModel, cancellationToken));
                }

                //otherwise, prompt for which account type.
                var msg = "Which type of account would you like to see ";
                if (string.IsNullOrEmpty(documentModel.AccountDocument))
                {
                    msg += " documents for?";
                }
                else
                {
                    msg += $" the {documentModel.AccountDocument} application/form for?";
                }

                msg = ChannelFormattingService.FormatSimpleMessage(stepContext.Context, msg);

                stepContext.Values[DocumentModelValue] = documentModel;

                return(await stepContext.PromptAsync($"{nameof(AccountDocumentsDialog)}.accountType", new PromptOptions
                {
                    Prompt = MessageFactory.Text(msg),
                    RetryPrompt = MessageFactory.Text(ChannelFormattingService.FormatSimpleMessage(stepContext.Context, "Please select a valid account type")),
                    Choices = ChoiceFactory.ToChoices(AccountTypeChoices)
                }, cancellationToken));
            }
        }
예제 #20
0
        private async Task <DialogTurnResult> ShowCardStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var attachments = new List <Attachment>();

            var reply = MessageFactory.Attachment(attachments);

            var initialValue = new JObject {
                { "count", 0 }
            };

            card = new HeroCard
            {
                Title    = "BotFramework Hero Card",
                Subtitle = "Microsoft Bot Framework",
                Text     = "Build and connect intelligent bots to interact with your users naturally wherever they are," +
                           " from text/sms to Skype, Slack, Office 365 mail and other popular services.",
                Buttons = new List <CardAction>
                {
                    new CardAction
                    {
                        Type  = ActionTypes.MessageBack,
                        Title = "Update card",
                        Text  = "Update"
                    },
                    new CardAction
                    {
                        Type  = ActionTypes.MessageBack,
                        Title = "Who am I?",
                        Text  = "whoami"
                    },
                    new CardAction
                    {
                        Type  = ActionTypes.MessageBack,
                        Title = "Delete card",
                        Text  = "Delete"
                    }
                },
            };

            reply.Attachments.Add(card.ToAttachment());

            // Send the card(s) to the user as an attachment to the activity
            await stepContext.Context.SendActivityAsync(reply, cancellationToken);

            //return new DialogTurnResult(DialogTurnStatus.Waiting);
            //return await stepContext.NextAsync(cancellationToken: cancellationToken);
            //return await stepContext.EndDialogAsync();

            var choices = new List <string>
            {
                "One", "Two", "Three"
            };

            return(await stepContext.PromptAsync(
                       TestPrompt,
                       new PromptOptions
            {
                Choices = ChoiceFactory.ToChoices(choices)
            },
                       cancellationToken));
        }
예제 #21
0
        private async Task <DialogTurnResult> IntroStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var processDetails = (ProcessDetails)stepContext.Options;
            var bot            = new Robot();

            foreach (var r in processDetails.ProcessSelected.Releases)
            {
                if (r.robots.Count > 1)
                {
                    if (r.robots.Any(b => b.Shown == false))
                    {
                        bot       = r.robots.Find(b => b.Shown == false);
                        bot.Shown = true;
                        break;
                    }
                    bot = new Robot();
                }
            }

            if (string.IsNullOrEmpty(bot.id))
            {
                processDetails.ProcessSelected.FirstBot = true;
                //all processed
                foreach (var r in processDetails.ProcessSelected.Releases)
                {
                    if (r.robots.Count > 1)
                    {
                        var robots = new List <string>();
                        foreach (var b in r.robots)
                        {
                            if (b.Selected)
                            {
                                robots.Add(b.id);
                            }
                        }
                        if (robots.Count == 0)
                        {
                            foreach (var re in processDetails.ProcessSelected.Releases)
                            {
                                if (re.robots.Count > 1)
                                {
                                    foreach (var b in re.robots)
                                    {
                                        b.Shown = false;
                                    }
                                }
                            }
                            processDetails.ProcessSelected.ReEnterBot = true;
                            return(await stepContext.ReplaceDialogAsync(nameof(RobotsDialog), processDetails, cancellationToken));
                        }
                        r.u_robots = string.Join(',', robots);
                    }
                }
                //if needs params
                if (processDetails.ProcessSelected.Releases.Any(r => r.parameters_required == true))
                {
                    var rpaService = new RPAService();
                    //set all params for this conversation to false(maybe was interrupted by a notification)
                    rpaService.DeactivatedConversationFlow(string.Empty, stepContext.Context.Activity.Conversation.Id);
                    rpaService.SaveConversationFlow(processDetails.ProcessSelected, stepContext.Context.Activity.Conversation.Id);
                    return(await stepContext.ReplaceDialogAsync(nameof(ParametersProcessDialog), processDetails, cancellationToken));
                }
                else
                {
                    return(await stepContext.ReplaceDialogAsync(nameof(StartProcessSharedDialog), processDetails, cancellationToken));
                }
            }
            else
            {
                var message = string.Empty;
                if (processDetails.ProcessSelected.FirstBot)
                {
                    if (processDetails.ProcessSelected.ReEnterBot)
                    {
                        message = "You have to select at least one Bot." + Environment.NewLine;
                        processDetails.ProcessSelected.ReEnterBot = false;
                    }
                    message += "Select the Bot(s) to trigger " + processDetails.ProcessSelected.Name + " process." + Environment.NewLine + "For each one select " + '"' + "Yes or No" + '"';
                    processDetails.ProcessSelected.FirstBot = false;
                }
                processDetails.ProcessSelected.Bot = bot;
                var rpaService = new RPAService();
                var choices    = rpaService.GetConfirmChoices();
                return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                {
                    Prompt = (Activity)ChoiceFactory.SuggestedAction(choices, message + Environment.NewLine + bot.name)
                }, cancellationToken));
            }
        }
예제 #22
0
        private async Task <DialogTurnResult> DispatchStepAsync(WaterfallStepContext stepContext,
                                                                CancellationToken cancellationToken)
        {
            // Call LUIS and gather any potential booking details. (Note the TurnContext has the response to the prompt.)
            Debug.WriteLine(stepContext.Context);
            Debug.WriteLine(cancellationToken);
            var message   = stepContext.Context;
            var qnaResult = await _botServices.QnAMakerService.GetAnswersAsync(message);

            var luisResult = await _botServices.LuisService.RecognizeAsync <LuisContactModel>(message, cancellationToken);

            var thresholdScore = 0.80;

            // Check if score is too low, then it is not understood.
            if ((luisResult.TopIntent().score < thresholdScore || (luisResult.TopIntent().score > thresholdScore && luisResult.TopIntent().intent == LuisContactModel.Intent.None)) &&
                (qnaResult.FirstOrDefault()?.Score *2 ?? 0) < thresholdScore)
            {
                var askAgain = "I can't seem to find my brain ... Could you please ask it again later?";

                // Responses when no answer available
                List <string> notUnderstoodResponses = new List <string>(new String[] { "I'll have to look that up. I'll let you know when I found something!",
                                                                                        "I will ask someone. I'll let you know when I got an answer.",
                                                                                        "Hmmm. Good question. Give me some time and I will try to figure it out. I will keep you updated!" });
                var notUnderstood = notUnderstoodResponses[random.Next(notUnderstoodResponses.Count)];

                // Responses on timeout
                List <string> answerLateResponse = new List <string>(new String[] { "It's taking longer than I'd expect to find an answer. " +
                                                                                    "I'm not that old though. I will notify you when I'm ready.", "I thought I was smart and quick, but right now I only seem to be smart. " +
                                                                                    "Anyway, you'll hear from me when I got something!", "I'm sorry. I'm having trouble finding an answer right now. It seems like " +
                                                                                    "I'm not perfect after all. However, I'll notify you when I found an answer." });
                var answerLate = answerLateResponse[random.Next(answerLateResponse.Count)];

                // Responses to nonsense input
                List <string> responsesToNonsense = new List <string>(new String[] { "That doesn't seem to make sense to me.",
                                                                                     "I'm sorry, I didn't understand you.", "You might have made a typo there. Could you try again?",
                                                                                     "I sometimes really don\'t get what you mean.", "You lost me there.", "I guess I\'m not supposed to understand that? Am I?" });
                var responseToNonsense = responsesToNonsense[random.Next(responsesToNonsense.Count)];

                // Responses to offensive input
                List <string> responsesToOffensive = new List <string>(new String[] {
                    "I find your language quite upsetting.",
                    "Please do watch your language, we want to be nice to other people don't we?",
                    "I'll pretend I didn't read that. Please watch your language.",
                    "I personally don\'t speak that kind of language.", "Maybe you could rephrase that?",
                    "I would not say it is proper to say that.", "As a gentle bot I would not dare to talk like that.",
                    "O my goodness. Gentle bots would not dare to talk like that."
                });
                var responseToOffensive = responsesToOffensive[random.Next(responsesToOffensive.Count)];


                //sending to server
                ServerAnswer answer = null;
                try
                {
                    answer = await Task.Run(() => conchatbot.SendQuestionAndWaitForAnswer(Globals.userID, message.Activity.Text, Globals.timeout));
                } catch (Exception e) {
                    Debug.WriteLine("Exception while requesting questions:\n" + e);
                    // If you want to send the exception to the user.
                    //await stepContext.Context.SendActivityAsync(MessageFactory.Text(e.ToString()), cancellationToken);
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text(askAgain), cancellationToken);

                    return(await stepContext.NextAsync(null, cancellationToken));
                }


                if (answer == null)
                {
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text(answerLate), cancellationToken);
                }
                else if (answer.status_code == (int)ServerStatusCode.Nonsense)
                {
                    // nonsense
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text(responseToNonsense), cancellationToken);
                }
                else if (answer.status_code == (int)ServerStatusCode.Offensive)
                {
                    // offensive
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text(responseToOffensive), cancellationToken);
                }
                else if (answer.answer_id < 0 || answer.answer == "" || answer == null)
                {
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text(notUnderstood), cancellationToken);
                }
                else
                {
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text(answer.answer), cancellationToken);

                    this._answer_id   = answer.answer_id;
                    this._question_id = answer.question_id;
                    //to ask the user if the answer was or was not a good answer to his/her question

                    try
                    {
                        return(await stepContext.PromptAsync(nameof(ChoicePrompt), new PromptOptions
                        {
                            Prompt = MessageFactory.Text("Was this a good answer? I would be grateful if you could press the YES button!"),
                            RetryPrompt = MessageFactory.Text("Please press one of the following buttons."),
                            Choices = ChoiceFactory.ToChoices(feedbackChoices),
                            Style = ListStyle.HeroCard,
                        }, cancellationToken));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }

                return(await stepContext.NextAsync(null, cancellationToken));
            }

            // Check on scores between Luis and Qna.
            if (luisResult.TopIntent().intent != LuisContactModel.Intent.None && luisResult.TopIntent().score >= (qnaResult.FirstOrDefault()?.Score ?? 0))
            {
                // Block proactive messaging while in LUIS dialog.
                Globals.connector.BlockProactiveMessagingForUser(Globals.userID);
                // Start the Luis Weather dialog.
                return(await stepContext.BeginDialogAsync(nameof(LuisContactDialog), luisResult, cancellationToken));
            }


            else
            {
                // Show a Qna message.
                var qnaMessage = MessageFactory.Text(qnaResult.First().Answer, qnaResult.First().Answer,
                                                     InputHints.ExpectingInput);

                await stepContext.Context.SendActivityAsync(qnaMessage, cancellationToken);

                return(await stepContext.NextAsync(null, cancellationToken));
            }
        }
예제 #23
0
        private void AddMainDialog()
        {
            const string orderStateEntry = "beerOrder";

            AddDialog(new WaterfallDialog(DialogIds.Main, new WaterfallStep[]
            {
                (stepContext, cancellationToken) =>
                {
                    var beerOrder = (BeerOrder)stepContext.Options ?? new BeerOrder();
                    stepContext.Values[orderStateEntry] = beerOrder;
                    return(stepContext.BeginDialogAsync(DialogIds.GetExactBeerName, beerOrder.BeerName, cancellationToken));
                },
                (stepContext, cancellationToken) =>
                {
                    var beerOrder      = (BeerOrder)stepContext.Values[orderStateEntry];
                    beerOrder.BeerName = (string)stepContext.Result;

                    if (beerOrder.Chaser != 0)
                    {
                        return(stepContext.NextAsync(cancellationToken: cancellationToken));
                    }

                    return(stepContext.PromptAsync(Inputs.Choice, new PromptOptions
                    {
                        Prompt = MessageFactory.Text(
                            "Which chaser would you like next to your beer?",
                            "Which chaser would you like next to your beer?",
                            InputHints.ExpectingInput),
                        RetryPrompt = MessageFactory.Text(
                            "I probably drank too much. Which chaser would you like next to your beer?",
                            "I probably drank too much. Which chaser would you like next to your beer?",
                            InputHints.ExpectingInput),
                        Choices = ChoiceFactory.ToChoices(PossibleChasers),
                    }, cancellationToken));
                },
                (stepContext, cancellationToken) =>
                {
                    var beerOrder = (BeerOrder)stepContext.Values[orderStateEntry];
                    if (beerOrder.Chaser == 0)
                    {
                        var chaserChoice = (FoundChoice)stepContext.Result;
                        beerOrder.Chaser = Enum.Parse <Chaser>(chaserChoice.Value);
                    }

                    if (beerOrder.Side != 0)
                    {
                        return(stepContext.NextAsync(cancellationToken: cancellationToken));
                    }

                    return(stepContext.PromptAsync(Inputs.Choice, new PromptOptions
                    {
                        Prompt = MessageFactory.Text(
                            "How about something to eat?",
                            "How about something to eat?",
                            InputHints.ExpectingInput),
                        RetryPrompt = MessageFactory.Text(
                            "I probably drank too much. Which side dish would you like next to your beer?",
                            "I probably drank too much. Which side dish would you like next to your beer?",
                            InputHints.ExpectingInput),
                        Choices = ChoiceFactory.ToChoices(PossibleSideDishs),
                    }, cancellationToken));
                },
                (stepContext, cancellationToken) =>
                {
                    var beerOrder = (BeerOrder)stepContext.Values[orderStateEntry];
                    if (beerOrder.Side == 0)
                    {
                        var sideDishChoice = (FoundChoice)stepContext.Result;
                        beerOrder.Side     = Enum.Parse <SideDish>(sideDishChoice.Value);
                    }

                    return(stepContext.PromptAsync(Inputs.Confirm, new PromptOptions
                    {
                        Prompt = MessageFactory.Text(
                            $"Just to make sure, do you want a {beerOrder.BeerName} beer with {beerOrder.Chaser} and some {beerOrder.Side} on the side?",
                            $"Just to make sure, do you want a {beerOrder.BeerName} beer with {beerOrder.Chaser} and some {beerOrder.Side} on the side?",
                            InputHints.ExpectingInput)
                    }, cancellationToken));
                },
                async(stepContext, cancellationToken) =>
                {
                    var orderConfirmed = (bool)stepContext.Result;
                    if (orderConfirmed)
                    {
                        var beerOrder = (BeerOrder)stepContext.Values[orderStateEntry];
                        await _userInfo.SetAsync(stepContext.Context, new UserInfo {
                            UsualBeer = beerOrder.BeerName
                        }, cancellationToken);
                        await stepContext.Context.SendActivityAsync(
                            $"Cheers {Emoji.Beers}",
                            @"<speak version=""1.0"" xmlns=""https://www.w3.org/2001/10/synthesis"" xml:lang=""en-US""><prosody pitch=""high"">Cheers</prosody></speak>",
                            cancellationToken: cancellationToken);
                    }
                    else
                    {
                        await stepContext.Context.SendActivityAsync(
                            $"Maybe I'll get it right next time {Emoji.Confused}",
                            "Maybe I'll get it right next time",
                            cancellationToken: cancellationToken);
                    }

                    return(await stepContext.EndDialogAsync(cancellationToken: cancellationToken));
                }
            }));
            InitialDialogId = DialogIds.Main;
        }
예제 #24
0
        private async Task <DialogTurnResult> DbInstanceStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var entitiDetails = (EntitiDetails)stepContext.Options;

            if (entitiDetails.Environment == null)
            {
                entitiDetails.Environment = ((FoundChoice)stepContext.Result).Value.ToString();
            }
            if (entitiDetails.Project == "App-Deployment")
            {
                return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("Please enter war to deploy the build.\n\n" + " Ex:Ipp-Portal:<version>,Loginservice:<version>,Client-Profile:<version>") }, cancellationToken));
            }
            else if (entitiDetails.Project == "CIT-Deployment")
            {
                return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("Please enter war to deploy the build.\n\n" + " Ex: hello-world.war:<version>") }, cancellationToken));
            }

            else if (entitiDetails.Project == "RMI-Deployment" || entitiDetails.Project == "DB-Deployment")
            {
                if (entitiDetails.Project == "RMI-Deployment")
                {
                    entitiDetails.HostName = entitiDetails.Environment == "QA(VPMTST1)" ? "usdtrmi03" : "usddevrmi01";
                }
                Dictionary <string, string> dic = new Dictionary <string, string>();
                dic.Add("QA(VPMTST1)", "VPMTST1");
                dic.Add("SprintTest(VPMSPTE)", "VPMSPTE");
                dic.Add("SprintDemo(VPMDEMO)", "VPMDEMO");
                dic.Add("CICD(VPMCICD)", "VPMCICD");
                entitiDetails.DbInstance = dic[entitiDetails.Environment].ToString();
                if (entitiDetails.Project == "DB-Deployment")
                {
                    return(await stepContext.PromptAsync(nameof(ChoicePrompt),
                                                         new PromptOptions
                    {
                        Prompt = MessageFactory.Text("Please select from where you wanto to deploy?"),
                        Choices = ChoiceFactory.ToChoices(new List <string> {
                            "trunk", "tags"
                        }),
                        Style = ListStyle.Auto,
                        RetryPrompt = MessageFactory.Text("Sorry, I'm still learning. Please provide the valid option or below mentioned Sequence Number."),
                    }, cancellationToken));
                }
                else
                {
                    return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("Please enter the repository for deployment") }, cancellationToken));
                }
            }
            else if (entitiDetails.Project == "Informatica-Deployment")
            {
                return(await stepContext.PromptAsync(nameof(ChoicePrompt),
                                                     new PromptOptions
                {
                    Prompt = MessageFactory.Text("Please select the repository branch or press 1 to skip the branch selection"),
                    Choices = GetBranches(),
                    Style = ListStyle.Auto,
                    RetryPrompt = MessageFactory.Text("Sorry, I'm still learning. Please provide the valid option or below mentioned Sequence Number."),
                }, cancellationToken));
            }
            else
            {
                if (entitiDetails.Buildwar == null)
                {
                    entitiDetails.Buildwar = (string)stepContext.Result;
                }
                return(await stepContext.NextAsync(entitiDetails, cancellationToken));
            }
        }
        public void ShouldRenderChoicesInline()
        {
            var activity = ChoiceFactory.Inline(colorChoices, "select from:");

            Assert.AreEqual("select from: (1) red, (2) green, or (3) blue", activity.Text);
        }
예제 #26
0
        private async Task <DialogTurnResult> LoopStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            bool isAdding  = true;
            var  orderData = await _orderDataAccessor.GetAsync(stepContext.Context, () => new OrderData(), cancellationToken);

            var topping = (string)stepContext.Result;

            if (topping.Contains("-"))
            {
                isAdding = false;
            }
            if (topping.Contains("?"))
            {
                topping += ",가이드";
            }

            var client   = new TextAnalyticsClient(endpoint, credentials);
            var response = KeyPhraseExtraction(client, topping);

            foreach (var pharase in response.Value)
            {
                if (pharase == "완성")
                {
                    if (orderData.Cheese.Count == 0 || orderData.Sauce.Count == 0)
                    {
                        return(await stepContext.PromptAsync(nameof(ChoicePrompt),
                                                             new PromptOptions
                        {
                            Prompt = MessageFactory.Text("치즈 혹은 소스가 선택되지 않았어요. 이대로 주문할까요?"),
                            Choices = ChoiceFactory.ToChoices(new List <string> {
                                "네", "아니오", "주문 취소"
                            }),
                        }, cancellationToken));
                    }
                    else
                    {
                        return(await stepContext.PromptAsync(nameof(ChoicePrompt),
                                                             new PromptOptions
                        {
                            Prompt = MessageFactory.Text("이대로 주문할까요?"),     //confirm factory 확인해보고 코드 수정하기?
                            Choices = ChoiceFactory.ToChoices(new List <string> {
                                "네", "아니오", "주문 취소"
                            }),
                        }, cancellationToken));
                    }
                }

                string pharase_type = null;
                if (Topping.vege.Contains(pharase))
                {
                    pharase_type = "야채";
                }
                else if (Topping.cheese.Contains(pharase))
                {
                    pharase_type = "치즈";
                }
                else if (Topping.sauce.Contains(pharase))
                {
                    pharase_type = "소스";
                }
                else if (Topping.topping.Contains(pharase))
                {
                    pharase_type = "추가토핑";
                }
                //토핑 종류
                else if (pharase.Contains("토핑"))
                {
                    //치즈 카드
                    await stepContext.Context.SendActivityAsync(Cards.GetCard("cheese"), cancellationToken);

                    //소스 카드 보여주기
                    await stepContext.Context.SendActivityAsync(Cards.GetCard("sauce"), cancellationToken);

                    //추가 토핑 카드 보여주기
                    await stepContext.Context.SendActivityAsync(Cards.GetCard("topping"), cancellationToken);
                }
                //가이드
                else if (pharase.Contains("가이드") || pharase.Contains("help"))
                {
                    await stepContext.Context.SendActivityAsync(Cards.GetCard("inputTip"), cancellationToken);
                }
                //추천 소스
                else if (pharase.Contains("추천소스"))
                {
                    var sauceRecommendMsg = $"홈페이지에서 제공하는 {orderData.Menu}의 추천 소스는 [";
                    foreach (string sauce in Topping.sauce_recommend[orderData.Menu])
                    {
                        sauceRecommendMsg += $"{sauce}, ";
                    }
                    sauceRecommendMsg += "] 입니다";
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text(sauceRecommendMsg), cancellationToken);
                }
                else
                {
                    await stepContext.Context.SendActivityAsync("없는 토핑입니다, 다시 입력해주세요!");
                }

                if (pharase_type != null)
                {
                    if (isAdding)//토핑추가
                    {
                        switch (pharase_type)
                        {
                        case "야채": orderData.Vege.Add(pharase); break;

                        case "치즈": orderData.Cheese.Add(pharase);
                            if (orderData.Cheese.Count > 1)    //치즈가격
                            {
                                orderData.Price += Topping.topping_price["치즈 추가"];
                                orderData.Topping.Add("치즈 추가");
                            }
                            break;

                        case "소스": orderData.Sauce.Add(pharase); break;

                        case "추가토핑": orderData.Topping.Add(pharase); orderData.Price += Topping.topping_price[pharase]; break;     //토핑 가격
                        }
                        await stepContext.Context.SendActivityAsync(pharase + " 토핑이 추가되었습니다.");
                    }
                    else //토핑삭제
                    {
                        bool flag = true;
                        switch (pharase_type)
                        {
                        case "야채":
                            if (orderData.Vege.Contains(pharase))
                            {
                                orderData.Vege.Remove(pharase);
                            }
                            else
                            {
                                flag = false;
                            }
                            break;

                        case "치즈":
                            if (orderData.Cheese.Contains(pharase))
                            {
                                orderData.Cheese.Remove(pharase);
                                if (orderData.Cheese.Count > 0)
                                {
                                    orderData.Price -= Topping.topping_price["치즈 추가"];
                                    orderData.Topping.Remove("치즈 추가");
                                }
                            }
                            else
                            {
                                flag = false;
                            }
                            break;

                        case "소스":
                            if (orderData.Sauce.Contains(pharase))
                            {
                                orderData.Sauce.Remove(pharase);
                            }
                            else
                            {
                                flag = false;
                            }
                            break;

                        case "추가토핑":
                            if (orderData.Topping.Contains(pharase))
                            {
                                orderData.Topping.Remove(pharase);
                                orderData.Price -= Topping.topping_price[pharase];
                            }
                            else
                            {
                                flag = false;
                            }
                            break;
                        }
                        if (flag)
                        {
                            await stepContext.Context.SendActivityAsync(pharase + " 토핑이 삭제되었습니다.");
                        }
                        else
                        {
                            await stepContext.Context.SendActivityAsync(pharase + " 토핑은 이미 삭제된 토핑입니다.");
                        }
                    }
                }
            }
            return(await stepContext.ReplaceDialogAsync(nameof(AddToppingDialog), null, cancellationToken));
        }
예제 #27
0
        private async Task <DialogTurnResult> MainMenuStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var userProfilesFilePath = _configuration["UsersFilePathSource"];
            // Fetch list of all user profile
            string userProfileJson = await _fileUtility.ReadFromFile(userProfilesFilePath);

            List <UserProfile> userProfiles = JsonConvert.DeserializeObject <List <UserProfile> >(userProfileJson);

            stepContext.Values["password"] = (string)stepContext.Result;
            if (stepContext.Values["Language"] == "KISWAHILI")
            {
                //Get the current profile object from user state
                var userProfile = await _botStateService.UserProfileAccessor.GetAsync(stepContext.Context, () => new UserProfile(), cancellationToken);

                //var Location = await _botStateService.LocationAccessor.GetAsync(stepContext.Context, () => new Location(), cancellationToken);
                //save all of the data inside the user profile
                userProfile.Name      = (string)stepContext.Values["Name"];
                userProfile.County    = (string)stepContext.Values["county"];
                userProfile.SubCounty = (string)stepContext.Values["subCounty"];
                userProfile.Ward      = (string)stepContext.Values["ward"];
                userProfile.UserName  = (string)stepContext.Values["userName"];
                userProfile.Password  = (string)stepContext.Values["password"];

                //show Summary to the user
                await stepContext.Context.SendActivityAsync(MessageFactory.Text($" Huu Hapa muhtasari wa Profaili yako: "), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Jina:{0}", userProfile.Name)), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Kaunti:{0}", userProfile.County)), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Kaunti ndogo:{0}", userProfile.SubCounty)), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Wadi:{0}", userProfile.Ward)), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(String.Format("Your Username: {0}", userProfile.UserName)), cancellationToken);

                //await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Details:{0}", GetUserDetails())), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format(" Hongera {0}!Umesajiliwa kutumia huduma yetu.Tafadhali chagua(1.MAIN MENU) kuendelea kutumia huduma", userProfile.Name)), cancellationToken);

                // Save data in userstate
                await _botStateService.UserProfileAccessor.SetAsync(stepContext.Context, userProfile);

                userProfiles.Add(userProfile);

                // Save user profiles
                var userProfilesString = JsonConvert.SerializeObject(userProfiles, Formatting.Indented);
                await _fileUtility.WriteToFile(userProfilesString, userProfilesFilePath);

                //display main menu
                return(await stepContext.PromptAsync($"{nameof(UserRegistrationDialog)}.mainMenu",
                                                     new PromptOptions
                {
                    Prompt = MessageFactory.Text("MAIN MENU"),
                    Choices = ChoiceFactory.ToChoices(new List <string> {
                        "TAARIFA ", "HABARI", "RUFAA", "UTAFITI", "SASISHA PROFAILI", "SHARE"
                    }),
                }, cancellationToken));

                stepContext.Values["mainMenu"] = (FoundChoice)stepContext.Result;
                //waterfallStep always finishes with the end of the waterfall or with another dialog here it is the end
                return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
            }

            else
            {
                //Get the current profile object from user state
                var userProfile = await _botStateService.UserProfileAccessor.GetAsync(stepContext.Context, () => new UserProfile(), cancellationToken);

                //var Location = await _botStateService.LocationAccessor.GetAsync(stepContext.Context, () => new Location(), cancellationToken);
                //save all of the data inside the user profile
                userProfile.Name      = (string)stepContext.Values["Name"];
                userProfile.County    = (string)stepContext.Values["county"];
                userProfile.SubCounty = (string)stepContext.Values["subCounty"];
                userProfile.Ward      = (string)stepContext.Values["ward"];
                userProfile.UserName  = (string)stepContext.Values["userName"];
                userProfile.Password  = (string)stepContext.Values["password"];

                //show Summary to the user
                await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Here is a summary of your Profile:"), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Name:{0}", userProfile.Name)), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("County:{0}", userProfile.County)), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("SubCounty:{0}", userProfile.SubCounty)), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Ward:{0}", userProfile.Ward)), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(String.Format("Your Username: {0}", userProfile.UserName)), cancellationToken);

                //await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Details:{0}", GetUserDetails())), cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text(string.Format("Congratulations {0}! You are now registered to use our service. Please choose (1.MAIN MENU ) to continue using the service.", userProfile.Name)), cancellationToken);


                //save data in userstate
                await _botStateService.UserProfileAccessor.SetAsync(stepContext.Context, userProfile);

                //Write user details to a json file
                var userDetails = JsonConvert.SerializeObject(userProfile, Formatting.Indented);
                var filePath    = @"C:\Users\Tech Jargon\source\repos\FeedBackLegalBot\FeedBackLegalBot\Data\UserDetails.json";
                if (!File.Exists(filePath))
                {
                    File.WriteAllText(filePath, userDetails);
                }
                else
                {
                    File.AppendAllText(filePath, userDetails);
                }



                //display main menu
                return(await stepContext.PromptAsync($"{nameof(UserRegistrationDialog)}.mainMenu",
                                                     new PromptOptions
                {
                    Prompt = MessageFactory.Text("MAIN MENU"),
                    Choices = ChoiceFactory.ToChoices(new List <string> {
                        "INFORMATION", "NEWS", "REFERAL", "SURVEY", "UPDATE PROFILE", "SHARE"
                    }),
                }, cancellationToken));

                stepContext.Values["mainMenu"] = (FoundChoice)stepContext.Result;
                //waterfallStep always finishes with the end of the waterfall or with another dialog here it is the end
                return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
            }
        }
예제 #28
0
        private async Task <DialogTurnResult> InitializeStateStepAsync(
            WaterfallStepContext stepContext,
            CancellationToken cancellationToken)
        {
            // Initalization of static variables
            askedForFeature  = false;
            questionCounter  = 0;
            questionAkedList = new List <string>();

            var context        = stepContext.Context;
            var onTurnProperty = await _onTurnAccessor.GetAsync(context, () => new OnTurnState());

            if (didYouMean != null || (onTurnProperty.Entities[EntityNames.FindItem] != null &&
                                       onTurnProperty.Entities[EntityNames.FindItem].Count() > 0))
            {
                string firstEntity;
                if (didYouMean == null)
                {
                    firstEntity = (string)onTurnProperty.Entities[EntityNames.FindItem].First;
                }
                else
                {
                    firstEntity = didYouMean;
                }

                // Get all items
                pimItems = await _itemService.GetAllItemsByMatchAsync(firstEntity);

                pimFeatures = await _featureService.GetAllFeatures();

                //                var groupCount = _itemService.GetAllItemsCategory(pimItems).Count();

                if (didYouMean != null)
                {
                    didYouMean = null;
                }

                if (pimItems.Count() == 0)
                {
                    await context.SendActivityAsync($"{Messages.NotFound} **{firstEntity}**.");

                    // Try to find if user doesnt do type error
                    didYouMean = await _itemService.FindSimilarItemsByDescription(firstEntity);

                    return(await stepContext.PromptAsync(
                               DidYouMeanPrompt,
                               new PromptOptions
                    {
                        Prompt = MessageFactory.Text(string.Format(Messages.FindItemDidYouMean, didYouMean)),
                        RetryPrompt = MessageFactory.Text(string.Format(Messages.FindItemDidYouMean, didYouMean) + Messages.CancelPrompt),
                        Choices = ChoiceFactory.ToChoices(new List <string> {
                            Messages.Yes, Messages.No
                        }),
                    },
                               cancellationToken));
                }
                else if (pimItems.Count() == 1)
                {
                    stepContext.ActiveDialog.State["stepIndex"] = ShowItemsDialogIndex;
                    return(await stepContext.ContinueDialogAsync());
                }
                else
                {
                    var prompt = string.Format(Messages.FindItemFound, pimItems.Count(), firstEntity) + Messages.WhatToDoPrompt;

                    return(await stepContext.PromptAsync(
                               ShowAllItemsPrompt,
                               new PromptOptions
                    {
                        Prompt = MessageFactory.Text(prompt),
                        RetryPrompt = MessageFactory.Text(prompt + Messages.CancelPrompt),
                        Choices = ChoiceFactory.ToChoices(new List <string> {
                            Messages.FindItemShowAllItem, Messages.FindItemSpecialize
                        }),
                    },
                               cancellationToken));
                }
            }

            await context.SendActivityAsync(Messages.FindItemForgotItem);

            var categories = await _categoryService.GetAllProductGroupAsync();

            await context.SendActivityAsync(ShowCategoriesDialog.GetPritableGroup(categories));

            return(await stepContext.EndDialogAsync());
        }
        public async Task ShouldAcceptAndRecognizeCustomLocaleDict()
        {
            var convoState  = new ConversationState(new MemoryStorage());
            var dialogState = convoState.CreateProperty <DialogState>("dialogState");

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

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

            var culture = new PromptCultureModel()
            {
                InlineOr      = " customOr ",
                InlineOrMore  = " customOrMore ",
                Locale        = "custom-custom",
                Separator     = "customSeparator",
                NoInLanguage  = "customNo",
                YesInLanguage = "customYes",
            };

            var customDict = new Dictionary <string, ChoiceFactoryOptions>()
            {
                { culture.Locale, new ChoiceFactoryOptions(culture.Separator, culture.InlineOr, culture.InlineOrMore, true) },
            };

            dialogs.Add(new ChoicePrompt("ChoicePrompt", customDict, null, culture.Locale));

            var helloLocale = MessageFactory.Text("hello");

            helloLocale.Locale = culture.Locale;

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

                var results = await dc.ContinueDialogAsync(cancellationToken);
                if (results.Status == DialogTurnStatus.Empty)
                {
                    await dc.PromptAsync(
                        "ChoicePrompt",
                        new PromptOptions
                    {
                        Prompt = new Activity {
                            Type = ActivityTypes.Message, Text = "favorite color?", Locale = culture.Locale
                        },
                        Choices = _colorChoices,
                    },
                        cancellationToken);
                }
            })
            .Send(helloLocale)
            .AssertReply((activity) =>
            {
                // Use ChoiceFactory to build the expected answer, manually
                var expectedChoices = ChoiceFactory.Inline(_colorChoices, null, null, new ChoiceFactoryOptions()
                {
                    InlineOr        = culture.InlineOr,
                    InlineOrMore    = culture.InlineOrMore,
                    InlineSeparator = culture.Separator,
                }).Text;
                Assert.AreEqual($"favorite color?{expectedChoices}", activity.AsMessageActivity().Text);
            })
            .StartTestAsync();
        }
예제 #30
0
        private async Task <DialogTurnResult> TagStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var entitiDetails = (EntitiDetails)stepContext.Options;

            if (!string.IsNullOrEmpty(entitiDetails.Project) && !string.IsNullOrEmpty(entitiDetails.Tag) && entitiDetails.Intent == "Trigger_Service")
            {
                if (string.IsNullOrEmpty(entitiDetails.Environment))
                {
                    entitiDetails.Environment = ((FoundChoice)stepContext.Result).Value.ToString();
                }
                if (entitiDetails.Tag == "CommitFile")
                {
                    entitiDetails.MuvKey = (string)stepContext.Result;
                }
                if (entitiDetails.Tag == "AutoDerivation")
                {
                    entitiDetails.ScheduledOption = ((FoundChoice)stepContext.Result).Value.ToString();
                    if (entitiDetails.ScheduledOption == "Schedule")
                    {
                        return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("Please enter the scheduling Date and Time in EST") }, cancellationToken));
                    }
                }
                return(await stepContext.NextAsync(entitiDetails, cancellationToken));
            }
            if (!string.IsNullOrEmpty(entitiDetails.Project) && !string.IsNullOrEmpty(entitiDetails.Buildwar) && entitiDetails.Intent == "Build_Deployment")
            {
                return(await stepContext.NextAsync(entitiDetails, cancellationToken));
            }
            else if (!string.IsNullOrEmpty(entitiDetails.Project) && string.IsNullOrEmpty(entitiDetails.Tag))
            {
                if (entitiDetails.Project.ToUpper() == "PRODUCTIONDAILYHEALTHCHECK")
                {
                    return(await stepContext.NextAsync(entitiDetails, cancellationToken));
                }
            }
            var bookingDetails = entitiDetails;

            if (entitiDetails.Intent == "Acronym")
            {
                entitiDetails.Acronym = (string)stepContext.Result;
                return(await stepContext.NextAsync(entitiDetails.Acronym, cancellationToken));
            }
            else if (entitiDetails.Intent == "Trigger_Service")
            {
                if (entitiDetails.Portfolio == "PCA" || entitiDetails.Portfolio == "CCV")
                {
                    if (entitiDetails.Project == null)
                    {
                        entitiDetails.Project = ((FoundChoice)stepContext.Result).Value.ToString();//(string)stepContext.Result;
                    }
                    else if (string.IsNullOrEmpty(entitiDetails.Environment))
                    {
                        entitiDetails.Environment = ((FoundChoice)stepContext.Result).Value.ToString();
                    }
                    if (entitiDetails.Tag == null && entitiDetails.Project.ToUpper() != "PRODUCTIONDAILYHEALTHCHECK")
                    {
                        if (entitiDetails.Project.ToUpper() == "CLIENTPROFILE")
                        {
                            return(await stepContext.PromptAsync(nameof(ChoicePrompt),
                                                                 new PromptOptions
                            {
                                Prompt = MessageFactory.Text("Please select the test"),
                                Choices = ChoiceFactory.ToChoices(new List <string> {
                                    "Smoke", "Regression", "DerivationLogic", "DMUVFunctionality"
                                }),
                                RetryPrompt = MessageFactory.Text("Sorry, I'm still learning. Please provide the valid option or below mentioned Sequence Number."),
                            }, cancellationToken));
                        }
                        else
                        {
                            return(await stepContext.PromptAsync(nameof(ChoicePrompt),
                                                                 new PromptOptions
                            {
                                Prompt = MessageFactory.Text("Please select the test"),
                                Choices = ChoiceFactory.ToChoices(new List <string> {
                                    "Smoke", "Regression", "Custom"
                                }),
                                RetryPrompt = MessageFactory.Text("Sorry, I'm still learning. Please provide the valid option or below mentioned Sequence Number."),
                            }, cancellationToken));
                        }
                    }
                }
                else
                {
                    entitiDetails.Environment = ((FoundChoice)stepContext.Result).Value.ToString();
                    if (entitiDetails.Environment != "PROD")
                    {
                        return(await stepContext.PromptAsync(nameof(ChoicePrompt),
                                                             new PromptOptions
                        {
                            Prompt = MessageFactory.Text("Please select the Client"),
                            Choices = (entitiDetails.Project != "Annocoder") ? GetRapidEnvironments("Client") : GetAnnocoderEnvironments("Client"),
                            //Choices = (entitiDetails.Project != "Annocoder")?GetRapidEnvironments("Client"),// ChoiceFactory.ToChoices(new List<string> { "ROC", "Humana" }),
                            RetryPrompt = MessageFactory.Text("Sorry, I'm still learning. Please provide the valid option or below mentioned Sequence Number."),
                        }, cancellationToken));
                    }
                }
            }
            else
            {
                if (entitiDetails.Environment == null)
                {
                    entitiDetails.Environment = ((FoundChoice)stepContext.Result).Value.ToString();
                }
                if (entitiDetails.Project == "App-Deployment")
                {
                    return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("Please enter war to deploy the build.\n\n" + " Ex:Ipp-Portal:<version>,Loginservice:<version>,Client-Profile:<version>") }, cancellationToken));
                }
                else if (entitiDetails.Project == "RMI-Deployment")
                {
                    entitiDetails.HostName = "usdtrmi03";
                }
                else
                {
                    return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("Please enter Sql script path to deploy") }, cancellationToken));
                }
            }
            return(await stepContext.NextAsync(entitiDetails, cancellationToken));
        }