コード例 #1
0
        public AdapterWithErrorHandler(BotFrameworkAuthentication auth, ILogger <IBotFrameworkHttpAdapter> logger, ConversationState conversationState = null)
            : base(auth, logger)
        {
            Dictionary <string, string> lgFilesPerLocale = new Dictionary <string, string>()
            {
                { "", Path.Combine(".", "Resources", "AdapterWithErrorHandler.lg") },
                { "fr", Path.Combine(".", "Resources", "AdapterWithErrorHandler.fr-fr.lg") }
            };

            _lgManager  = new MultiLanguageLG(lgFilesPerLocale);
            OnTurnError = async(turnContext, exception) =>
            {
                // Log any leaked exception from the application.
                logger.LogError($"Exception caught : {exception.Message}");

                // Send a catch-all apology to the user.
                await turnContext.SendActivityAsync(ActivityFactory.FromObject(_lgManager.Generate("SomethingWentWrong", exception, turnContext.Activity.Locale)));

                if (conversationState != null)
                {
                    try
                    {
                        // Delete the conversationState for the current conversation to prevent the
                        // bot from getting stuck in a error-loop caused by being in a bad state.
                        // ConversationState should be thought of as similar to "cookie-state" in a Web pages.
                        await conversationState.DeleteAsync(turnContext);
                    }
                    catch (Exception e)
                    {
                        logger.LogError($"Exception caught on attempting to Delete ConversationState : {e.Message}");
                    }
                }
            };
        }
コード例 #2
0
        private Activity InternalGenerateActivity(string templateName, object data, string locale)
        {
            var iLocale = locale == null ? "" : locale;

            if (TemplateEnginesPerLocale.ContainsKey(iLocale))
            {
                return(ActivityFactory.FromObject(TemplateEnginesPerLocale[locale].Evaluate(templateName, data)));
            }
            var locales = new string[] { string.Empty };

            if (!LangFallBackPolicy.TryGetValue(iLocale, out locales))
            {
                if (!LangFallBackPolicy.TryGetValue(string.Empty, out locales))
                {
                    throw new Exception($"No supported language found for {iLocale}");
                }
            }

            foreach (var fallBackLocale in locales)
            {
                if (TemplateEnginesPerLocale.ContainsKey(fallBackLocale))
                {
                    return(ActivityFactory.FromObject(TemplateEnginesPerLocale[fallBackLocale].Evaluate(templateName, data)));
                }
            }
            return(new Activity());
        }
コード例 #3
0
        public AdapterWithErrorHandler(ICredentialProvider credentialProvider, ILogger <BotFrameworkHttpAdapter> logger, IStorage storage, UserState userState, ConversationState conversationState, IConfiguration configuration)
            : base(credentialProvider, logger: logger)
        {
            this.Use(new RegisterClassMiddleware <IConfiguration>(configuration));
            this.UseStorage(storage);
            this.UseBotState(userState);
            this.UseBotState(conversationState);

            _lgFile = Templates.ParseFile(Path.Combine(".", "AdapterWithErrorHandler.lg"));

            OnTurnError = async(turnContext, exception) =>
            {
                // Log any leaked exception from the application.
                logger.LogError($"Exception caught : {exception.Message}");
                await turnContext.SendActivityAsync(ActivityFactory.FromObject(_lgFile.Evaluate("SomethingWentWrong", exception)));

                if (conversationState != null)
                {
                    try
                    {
                        // Delete the conversationState for the current conversation to prevent the
                        // bot from getting stuck in a error-loop caused by being in a bad state.
                        // ConversationState should be thought of as similar to "cookie-state" in a Web pages.
                        await conversationState.DeleteAsync(turnContext);
                    }
                    catch (Exception e)
                    {
                        logger.LogError($"Exception caught on attempting to Delete ConversationState : {e.Message}");
                    }
                }
            };
        }
コード例 #4
0
        public AdapterWithErrorHandler(BotFrameworkAuthentication auth, ILogger <IBotFrameworkHttpAdapter> logger, ConversationState conversationState = null)
            : base(auth, logger)
        {
            // combine path for cross platform support
            string[] paths    = { ".", "Resources", "AdapterWithErrorHandler.lg" };
            string   fullPath = Path.Combine(paths);

            _templates  = Templates.ParseFile(fullPath);
            OnTurnError = async(turnContext, exception) =>
            {
                // Log any leaked exception from the application.
                logger.LogError($"Exception caught : {exception.Message}");

                // Send a catch-all apology to the user.
                await turnContext.SendActivityAsync(ActivityFactory.FromObject(_templates.Evaluate("SomethingWentWrong", exception)));

                if (conversationState != null)
                {
                    try
                    {
                        // Delete the conversationState for the current conversation to prevent the
                        // bot from getting stuck in a error-loop caused by being in a bad state.
                        // ConversationState should be thought of as similar to "cookie-state" in a Web pages.
                        await conversationState.DeleteAsync(turnContext);
                    }
                    catch (Exception e)
                    {
                        logger.LogError($"Exception caught on attempting to Delete ConversationState : {e.Message}");
                    }
                }
            };
        }
コード例 #5
0
        /// <summary>
        /// Given the turn context bind to the data to create the object of type <see cref="Activity"/>.
        /// </summary>
        /// <param name="dialogContext">The <see cref="DialogContext"/> for the current turn of conversation.</param>
        /// <param name="data">Optional, data to bind to. If Null, then dc.State will be used.</param>
        /// <param name="cancellationToken">Optional, the <see cref="CancellationToken"/> for this task.</param>
        /// <returns>Instance of <see cref="Activity"/>.</returns>
        public virtual async Task <Activity> BindAsync(DialogContext dialogContext, object data = null, CancellationToken cancellationToken = default)
        {
            if (dialogContext == null)
            {
                throw new ArgumentNullException(nameof(dialogContext));
            }

            if (data is CancellationToken)
            {
                throw new ArgumentException($"{nameof(data)} cannot be a cancellation token");
            }

            if (!string.IsNullOrEmpty(this.Template))
            {
                var languageGenerator = dialogContext.Services.Get <LanguageGenerator>();
                if (languageGenerator != null)
                {
                    var lgStringResult = await languageGenerator.GenerateAsync(dialogContext, this.Template, data ?? dialogContext.State, cancellationToken).ConfigureAwait(false);

                    var result = ActivityFactory.FromObject(lgStringResult);
                    return(result);
                }
                else
                {
                    var message = Activity.CreateMessageActivity();
                    message.Text  = this.Template;
                    message.Speak = this.Template;
                    return(message as Activity);
                }
            }

            return(null);
        }
コード例 #6
0
        protected override async Task OnMembersAddedAsync(IList <ChannelAccount> membersAdded, ITurnContext <IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
        {
            // Actions to include in the welcome card. These are passed to LG and are then included in the generated Welcome card.
            var actions = new {
                actions = new List <Object>()
                {
                    new {
                        title = "Get an overview",
                        url   = "https://docs.microsoft.com/en-us/azure/bot-service/?view=azure-bot-service-4.0"
                    },
                    new {
                        title = "Ask a question",
                        url   = "https://stackoverflow.com/questions/tagged/botframework"
                    },
                    new {
                        title = "Learn how to deploy",
                        url   = "https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-deploy-azure?view=azure-bot-service-4.0"
                    }
                }
            };

            foreach (var member in membersAdded)
            {
                // Greet anyone that was not the target (recipient) of this message.
                // To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
                if (member.Id != turnContext.Activity.Recipient.Id)
                {
                    await turnContext.SendActivityAsync(ActivityFactory.FromObject(_templates.Evaluate("WelcomeCard", actions)));
                }
            }
        }
コード例 #7
0
        public AdapterWithErrorHandler(ICredentialProvider credentialProvider, ILogger <BotFrameworkHttpAdapter> logger, IStorage storage,
                                       UserState userState, ConversationState conversationState, IConfiguration configuration)
            : base(credentialProvider)
        {
            this.UseStorage(storage);
            this.UseBotState(userState);
            this.UseBotState(conversationState);

            string[] paths    = { ".", $"{nameof(AdapterWithErrorHandler)}.lg" };
            string   fullPath = Path.Combine(paths);

            _templates = Templates.ParseFile(fullPath);

            OnTurnError = async(turnContext, exception) =>
            {
                logger.LogError($"Exception caught : {exception.Message}");

                await turnContext.SendActivityAsync(ActivityFactory.FromObject(_templates.Evaluate("SomethingWentWrong", exception)));

                if (conversationState != null)
                {
                    try
                    {
                        await conversationState.DeleteAsync(turnContext);
                    }
                    catch (Exception e)
                    {
                        logger.LogError($"Exception caught on attempting to Delete ConversationState : {e.Message}");
                    }
                }
            };
        }
コード例 #8
0
        private static async Task <DialogTurnResult> NameStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            stepContext.Values["transport"] = ((FoundChoice)stepContext.Result).Value;

            return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions {
                Prompt = ActivityFactory.FromObject(_lgGenerator.Generate("AskForName", null, stepContext.Context.Activity.Locale))
            }, cancellationToken));
        }
コード例 #9
0
        public void TestAnimationCardTemplate()
        {
            dynamic data     = new JObject();
            var     lgResult = templates.Evaluate("AnimationCardTemplate", data);
            var     activity = ActivityFactory.FromObject(lgResult);

            AssertAnimationCardActivity(activity);
        }
コード例 #10
0
        public void TestCustomizedCardTemplate()
        {
            dynamic data     = new JObject();
            var     lgResult = templates.Evaluate("customizedCardActionActivity", data);
            var     activity = ActivityFactory.FromObject(lgResult);

            AssertCustomizedCardActivity(activity);
        }
コード例 #11
0
        private async Task <DialogTurnResult> ResolveAndSendQnAAnswer(DialogContext dc, System.Object options)
        {
            var exp1   = Expression.Parse("@answer").TryEvaluate(dc.State).value;
            var resVal = await this._deleteToDoDialog.Generator.GenerateAsync(dc, exp1.ToString(), dc.State);

            await dc.Context.SendActivityAsync(ActivityFactory.FromObject(resVal));

            return(await dc.EndDialogAsync(options));
        }
コード例 #12
0
        public virtual Activity GenerateActivity(string templateName, object data = null)
        {
            if (string.IsNullOrEmpty(templateName))
            {
                throw new ArgumentNullException(nameof(templateName));
            }

            return(ActivityFactory.FromObject(Generate(templateName, data, null)));
        }
コード例 #13
0
        public void TestNotSupportStructuredType()
        {
            // fallback to text activity
            var lgResult = templates.Evaluate("notSupport");
            var activity = ActivityFactory.FromObject(lgResult);

            Assert.Equal(0, activity.Attachments.Count);
            Assert.Equal("{\"lgType\":\"Acti\",\"key\":\"value\"}", activity.Text.Replace("\r\n", string.Empty).Replace("\n", string.Empty).Replace(" ", string.Empty));
        }
コード例 #14
0
        public void TestHandoffActivity()
        {
            dynamic data = new JObject();

            data.text = "textContent";
            var lgResult = templates.Evaluate("handoffActivity", data);
            var activity = ActivityFactory.FromObject(lgResult);

            AssertHandoffActivity(activity);
        }
コード例 #15
0
        public void TestAdaptivecardActivity()
        {
            dynamic data = new JObject();

            data.adaptiveCardTitle = "test";
            var lgResult = GetNormalStructureLGFile().Evaluate("adaptivecardActivity", data);
            var activity = ActivityFactory.FromObject(lgResult);

            AssertAdaptiveCardActivity(activity);
        }
コード例 #16
0
        public void TestAudioCardTemplate()
        {
            dynamic data = new JObject();

            data.type = "audiocard";
            var lgResult = GetNormalStructureLGFile().Evaluate("AudioCardTemplate", data);
            var activity = ActivityFactory.FromObject(lgResult);

            AssertAudioCardActivity(activity);
        }
コード例 #17
0
        public void TestActivityWithMultiStringSuggestionActions()
        {
            dynamic data = new JObject();

            data.text = "textContent";
            var lgResult = templates.Evaluate("activityWithMultiStringSuggestionActions", data);
            var activity = ActivityFactory.FromObject(lgResult);

            AssertActivityWithMultiStringSuggestionActions(activity);
        }
コード例 #18
0
        public void TestAdaptivecardActivityWithAttachmentStructure()
        {
            dynamic data = new JObject();

            data.adaptiveCardTitle = "test";
            var lgResult = templates.Evaluate("adaptivecardActivityWithAttachmentStructure", data);
            var activity = ActivityFactory.FromObject(lgResult);

            AssertAdaptiveCardActivity(activity);
        }
コード例 #19
0
        public void TestSuggestedActionsReference()
        {
            dynamic data = new JObject();

            data.text = "textContent";
            var lgResult = templates.Evaluate("SuggestedActionsReference", data);
            var activity = ActivityFactory.FromObject(lgResult);

            AssertSuggestedActionsReferenceActivity(activity);
        }
コード例 #20
0
        public void TestExternalAdaptiveCardActivity()
        {
            dynamic data = new JObject();

            data.adaptiveCardTitle = "test";
            var lgResult = templates.Evaluate("externalAdaptiveCardActivity", data);
            var activity = ActivityFactory.FromObject(lgResult);

            AssertAdaptiveCardActivity(activity);
        }
コード例 #21
0
        public void TestVideoCardTemplate()
        {
            dynamic data = new JObject();

            data.type = "videocard";
            var lgResult = templates.Evaluate("VideoCardTemplate", data);
            var activity = ActivityFactory.FromObject(lgResult);

            AssertVideoCardActivity(activity);
        }
コード例 #22
0
        public void TestHandoffActivity()
        {
            dynamic data = new JObject();

            data.text = "textContent";
            var lgResult = GetNormalStructureLGFile().Evaluate("handoffActivity", data);
            var activity = ActivityFactory.FromObject(lgResult);

            AssertHandoffActivity(activity);
        }
コード例 #23
0
        public void TestActivityWithMultiStructuredSuggestionActions()
        {
            dynamic data = new JObject();

            data.text = "textContent";
            var lgResult = GetNormalStructureLGFile().Evaluate("activityWithMultiStructuredSuggestionActions", data);
            var activity = ActivityFactory.FromObject(lgResult);

            AssertActivityWithMultiStructuredSuggestionActions(activity);
        }
コード例 #24
0
        public void TestActivityWithHeroCardAttachment()
        {
            dynamic data = new JObject();

            data.title = "titleContent";
            data.text  = "textContent";
            var lgResult = GetNormalStructureLGFile().Evaluate("activityWithHeroCardAttachment", data);
            var activity = ActivityFactory.FromObject(lgResult);

            AssertActivityWithHeroCardAttachment(activity);
        }
コード例 #25
0
        public void TestHerocardWithCardAction()
        {
            dynamic data = new JObject();

            data.title = "titleContent";
            data.text  = "textContent";
            var lgResult = templates.Evaluate("HerocardWithCardAction", data);
            var activity = ActivityFactory.FromObject(lgResult);

            AssertCardActionActivity(activity);
        }
コード例 #26
0
        public void TestHerocardWithCardAction()
        {
            dynamic data = new JObject();

            data.title = "titleContent";
            data.text  = "textContent";
            var lgResult = GetNormalStructureLGFile().Evaluate("HerocardWithCardAction", data).ToString();
            var activity = ActivityFactory.FromObject(lgResult);

            AssertCardActionActivity(activity);
        }
コード例 #27
0
        public void TestSigninCardTemplate()
        {
            dynamic data = new JObject();

            data.signinlabel = "Sign in";
            data.url         = "https://login.microsoftonline.com/";
            var lgResult = templates.Evaluate("SigninCardTemplate", data);
            var activity = ActivityFactory.FromObject(lgResult);

            AssertSigninCardActivity(activity);
        }
コード例 #28
0
        public void TestMessageActivityAll()
        {
            dynamic data = new JObject();

            data.title = "titleContent";
            data.text  = "textContent";
            var lgResult = templates.Evaluate("messageActivityAll", data);
            var activity = ActivityFactory.FromObject(lgResult);

            AssertMessageActivityAll(activity);
        }
コード例 #29
0
        public void TestHerocardActivityWithAttachmentStructure()
        {
            dynamic data = new JObject();

            data.title = "titleContent";
            data.text  = "textContent";
            var lgResult = templates.Evaluate("activityWithMultiAttachments", data);
            var activity = ActivityFactory.FromObject(lgResult);

            AssertActivityWithMultiAttachments(activity);
        }
コード例 #30
0
        public void TestHerocardAttachment()
        {
            dynamic data = new JObject();

            data.type  = "imBack";
            data.title = "taptitle";
            data.value = "tapvalue";
            var lgResult = templates.Evaluate("herocardAttachment", data);
            var activity = ActivityFactory.FromObject(lgResult);

            AssertActivityWithHeroCardAttachment(activity);
        }