示例#1
0
        public async Task TestDialogInjectionDeclarative()
        {
            var           resourceExplorer = new ResourceExplorer().LoadProject(GetProjectFolder(), monitorChanges: false);
            DialogManager dm = new DialogManager()
                               .UseResourceExplorer(resourceExplorer)
                               .UseLanguageGeneration("test.lg")
                               .UseLanguagePolicy(new LanguagePolicy("fr-fr"));

            dm.RootDialog = (AdaptiveDialog)resourceExplorer.LoadType <Dialog>("test.dialog");

            await CreateFlow(async (dialogContext, cancellationToken) =>
            {
                await dm.OnTurnAsync(dialogContext, cancellationToken: cancellationToken).ConfigureAwait(false);
            })
            .Send("hello")
            .AssertReply("root")
            .AssertReply("overriden in fr")
            .StartTestAsync();
        }
示例#2
0
        public void TestResourceExplorerRegistration(ResourceExplorerOptions options, ComponentRegistration legacyRegistration)
        {
            // Arrange
            // Build resourceExplorer
            using (var explorer = new ResourceExplorer(options))
            {
                // Clear component registration
                if (legacyRegistration != null)
                {
                    ComponentRegistration.Add(legacyRegistration);
                }

                // Test
                var declarativeType = explorer.LoadType <TestDeclarativeType>(new MemoryResource());

                // Assert
                Assert.NotNull(declarativeType);
                Assert.Equal("fromConverter", declarativeType.Data);
            }
        }
        public async Task TestManuallySetLocale()
        {
            var           resourceExplorer = new ResourceExplorer().LoadProject(GetProjectFolder(), monitorChanges: false);
            DialogManager dm = new DialogManager()
                               .UseResourceExplorer(resourceExplorer)
                               .UseLanguageGeneration("test.lg");

            dm.RootDialog = (AdaptiveDialog)resourceExplorer.LoadType <Dialog>("manuallySetLocale.dialog");
            await CreateFlow(async (turnContext, cancellationToken) =>
            {
                (turnContext as TurnContext).Locale = "en-US";
                await dm.OnTurnAsync(turnContext, cancellationToken: cancellationToken).ConfigureAwait(false);
            })
            .Send("hola")
            .AssertReply("1,122")
            .AssertReply("1,1235")
            .AssertReply("Samstag, 6. Januar 2018")
            .AssertReply("3,14159")
            .StartTestAsync();
        }
示例#4
0
        public static async Task RunTestScript(ResourceExplorer resourceExplorer, string resourceId = null, IConfiguration configuration = null, [CallerMemberName] string testName = null)
        {
            var storage    = new MemoryStorage();
            var convoState = new ConversationState(storage);
            var userState  = new UserState(storage);

            var adapter = (TestAdapter) new TestAdapter(Channels.Msteams)
                          .Use(new RegisterClassMiddleware <IConfiguration>(DefaultConfiguration))
                          .UseStorage(storage)
                          .UseBotState(userState, convoState)
                          .Use(new TranscriptLoggerMiddleware(new TraceTranscriptLogger(traceActivity: false)));

            adapter.OnTurnError += (context, err) => context.SendActivityAsync(err.Message);

            var script = resourceExplorer.LoadType <TestScript>(resourceId ?? $"{testName}.test.dialog");

            script.Configuration = configuration ?? new ConfigurationBuilder().AddInMemoryCollection().Build();
            script.Description ??= resourceId;
            await script.ExecuteAsync(adapter : adapter, testName : testName, resourceExplorer : resourceExplorer).ConfigureAwait(false);
        }
        public async Task TestLGInjection()
        {
            var           resourceExplorer = new ResourceExplorer().LoadProject(GetProjectFolder(), monitorChanges: false);
            DialogManager dm = new DialogManager()
                               .UseResourceExplorer(resourceExplorer)
                               .UseLanguageGeneration("inject.lg");

            dm.RootDialog = (AdaptiveDialog)resourceExplorer.LoadType <Dialog>("inject.dialog");

            await CreateFlow(async (turnContext, cancellationToken) =>
            {
                await dm.OnTurnAsync(turnContext, cancellationToken: cancellationToken).ConfigureAwait(false);
            })
            .Send("hello")
            .AssertReply("[{\"Id\":0,\"Topic\":\"car\"},{\"Id\":1,\"Topic\":\"washing\"},{\"Id\":2,\"Topic\":\"food\"},{\"Id\":3,\"Topic\":\"laundry\"}]")
            .AssertReply("This is an injected message")
            .AssertReply("Hi Jonathan")
            .AssertReply("Jonathan : 2003-03-20")
            .AssertReply("Jonathan, your tasks: car, washing, food and laundry")
            .StartTestAsync();
        }
        public async Task TestDateTimeFunctions()
        {
            var           resourceExplorer = new ResourceExplorer().LoadProject(GetProjectFolder(), monitorChanges: false);
            DialogManager dm = new DialogManager()
                               .UseResourceExplorer(resourceExplorer)
                               .UseLanguageGeneration("test.lg");

            dm.RootDialog = (AdaptiveDialog)resourceExplorer.LoadType <Dialog>("datetime.dialog");

            await CreateFlow(async (turnContext, cancellationToken) =>
            {
                await dm.OnTurnAsync(turnContext, cancellationToken: cancellationToken).ConfigureAwait(false);
            })
            .Send("hello")
            .AssertReply("2018-01-01T08:00:00.000Z")
            .AssertReply("2018-01-01T08:00:00.000Z")
            .AssertReply("2018-01-01T08:02:00.000Z")
            .AssertReply("2018-01-01T08:03:00.000Z")
            .AssertReply("2018-01-06T08:00:00.000Z")
            .AssertReply("2018-01-01T15:00:00.000Z")
            .AssertReply("2018-01-01T08:33:00.000Z")
            .AssertReply("1")
            .AssertReply("1")
            .AssertReply("1")
            .AssertReply("1")
            .AssertReply("1/01/2018")
            .AssertReply("2018")
            .AssertReply("2018-01-01T08:00:00.000Z")
            .AssertReply("2017-01-01T08:00:00.000Z")
            .AssertReply("morning")
            .AssertReply("tomorrow")
            .AssertReply("01-01-2018")
            .AssertReply("2018-01-01T16:00:00.000Z")
            .AssertReply("2018-01-20T00:00:00.000Z")
            .AssertReply("2018-01-20T08:00:00.000Z")
            .AssertReply("2018-01-01T00:00:00.000Z")
            .AssertReply("636503904000000000")
            .AssertReply("True")
            .StartTestAsync();
        }
        public static async Task RunTestScript(ResourceExplorer resourceExplorer, string resourceId = null, IConfiguration configuration = null, [CallerMemberName] string testName = null, IEnumerable <IMiddleware> middleware = null, string adapterChannel = Channels.Msteams)
        {
            var storage    = new MemoryStorage();
            var convoState = new ConversationState(storage);
            var userState  = new UserState(storage);

            var adapter = (TestAdapter) new TestAdapter(CreateConversation(adapterChannel, testName));

            if (middleware != null)
            {
                foreach (var m in middleware)
                {
                    adapter.Use(m);
                }
            }

            adapter.Use(new RegisterClassMiddleware <IConfiguration>(DefaultConfiguration))
            .UseStorage(storage)
            .UseBotState(userState, convoState)
            .Use(new TranscriptLoggerMiddleware(new TraceTranscriptLogger(traceActivity: false)));

            adapter.OnTurnError += async(context, err) =>
            {
                if (err.Message.EndsWith("MemoryAssertion failed"))
                {
                    throw err;
                }

                await context.SendActivityAsync(err.Message);
            };

            var script = resourceExplorer.LoadType <TestScript>(resourceId ?? $"{testName}.test.dialog");

            script.Configuration = configuration ?? new ConfigurationBuilder().AddInMemoryCollection().Build();
            script.Description ??= resourceId;
            await script.ExecuteAsync(adapter : adapter, testName : testName, resourceExplorer : resourceExplorer).ConfigureAwait(false);
        }
        public MainDialog(
            IServiceProvider serviceProvider,
            ResourceExplorer resourceExplorer)
            : base(nameof(MainDialog))
        {
            _services       = serviceProvider.GetService <BotServices>();
            _templateEngine = serviceProvider.GetService <LocaleTemplateManager>();

            var steps = new WaterfallStep[]
            {
                IntroStepAsync
            };

            AddDialog(new WaterfallDialog(nameof(MainDialog), steps));
            AddDialog(new TextPrompt(nameof(TextPrompt)));
            InitialDialogId = nameof(MainDialog);

            //from instructions: https://microsoft.github.io/botframework-solutions/skills/handbook/experimental-add-composer/
            var dialogResource = resourceExplorer.GetResource("Composer-With-Skill.dialog");
            var composerDialog = resourceExplorer.LoadType <AdaptiveDialog>(dialogResource);

            // Add the dialog
            AddDialog(composerDialog);
        }
示例#9
0
        public static void Main(string[] args)
        {
            var    secret = "profile";
            string luis   = null;

            if (args.Length == 0)
            {
                Help();
            }

            for (var i = 0; i < args.Length; ++i)
            {
                var arg = args[i];
                if (arg.StartsWith("-"))
                {
                    if (arg == "-secret")
                    {
                        if (++i < args.Length)
                        {
                            secret = args[i];
                        }
                        else
                        {
                            throw new System.ArgumentException("Missing --secret value");
                        }
                    }
                    else if (arg == "-luis")
                    {
                        if (++i < args.Length)
                        {
                            luis = args[i];
                        }
                        else
                        {
                            throw new System.ArgumentException("Missing --luis value");
                        }
                    }
                    else
                    {
                        Console.Error.WriteLine($"Unknown arg {arg}");
                        Help();
                    }
                }
                else
                {
                    var cd     = Directory.GetCurrentDirectory();
                    var dir    = Path.GetDirectoryName(arg);
                    var name   = Path.GetFileName(arg);
                    var config = new ConfigurationBuilder()
                                 .AddInMemoryCollection()
                                 .UseLuisSettings(luis ?? dir, secret)
                                 .Build();
                    var explorer = new ResourceExplorer().AddFolder(dir);
                    DeclarativeTypeLoader.Reset();
                    TypeFactory.Configuration = config;
                    DeclarativeTypeLoader.AddComponent(new DialogComponentRegistration());
                    DeclarativeTypeLoader.AddComponent(new AdaptiveComponentRegistration());
                    DeclarativeTypeLoader.AddComponent(new LanguageGenerationComponentRegistration());
                    DeclarativeTypeLoader.AddComponent(new QnAMakerComponentRegistration());
                    DeclarativeTypeLoader.AddComponent(new MockLuisComponentRegistration());
                    var script = explorer.LoadType <TestScript>(name);
                    var timer  = new System.Diagnostics.Stopwatch();
                    Console.Write($"Executing {arg}");
                    timer.Start();
                    script.ExecuteAsync(testName: name, configuration: config, resourceExplorer: explorer).Wait();
                    timer.Stop();
                    Console.WriteLine($" took {timer.ElapsedMilliseconds} ms");
                }
            }
        }
        private void LoadDialogs()
        {
            System.Diagnostics.Trace.TraceInformation("Loading resources...");

            // Create a non-used dialog just to make sure the target assembly is referred so that
            // the target assembly's component registration can be used to deserialize declarative components
            var qnaDialog = new QnAMakerDialog();

            System.Diagnostics.Trace.TraceInformation($"Touch ${qnaDialog.GetType().ToString()} to make sure assembly is referred.");

            var rootDialog = new AdaptiveDialog()
            {
                AutoEndDialog = false,
            };
            var choiceInput = new ChoiceInput()
            {
                Prompt       = new ActivityTemplate("What declarative sample do you want to run?"),
                Property     = "conversation.dialogChoice",
                AlwaysPrompt = true,
                Choices      = new ChoiceSet(new List <Choice>())
            };

            var handleChoice = new SwitchCondition()
            {
                Condition = "conversation.dialogChoice",
                Cases     = new List <Case>()
            };

            Dialog lastDialog = null;
            var    choices    = new ChoiceSet();
            var    dialogName = configuration["dialog"];

            foreach (var resource in this.resourceExplorer.GetResources(".dialog").Where(r => dialogName != null ? r.Id == dialogName : r.Id.EndsWith(".main.dialog")))
            {
                try
                {
                    var name = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(resource.Id));
                    choices.Add(new Choice(name));
                    var dialog = resourceExplorer.LoadType <Dialog>(resource);
                    lastDialog = dialog;
                    handleChoice.Cases.Add(new Case($"{name}", new List <Dialog>()
                    {
                        dialog
                    }));
                }
                catch (SyntaxErrorException err)
                {
                    Trace.TraceError($"{err.Source}: Error: {err.Message}");
                }
                catch (Exception err)
                {
                    Trace.TraceError(err.Message);
                }
            }

            if (handleChoice.Cases.Count() == 1)
            {
                rootDialog.Triggers.Add(new OnBeginDialog
                {
                    Actions = new List <Dialog>
                    {
                        lastDialog,
                        new RepeatDialog()
                    }
                });
            }
            else
            {
                choiceInput.Choices = choices;
                choiceInput.Style   = ListStyle.Auto;
                rootDialog.Triggers.Add(new OnBeginDialog()
                {
                    Actions = new List <Dialog>()
                    {
                        choiceInput,
                        new SendActivity("# Running ${conversation.dialogChoice}.main.dialog"),
                        handleChoice,
                        new RepeatDialog()
                    }
                });
            }

            this.dialogManager = new DialogManager(rootDialog)
                                 .UseResourceExplorer(this.resourceExplorer)
                                 .UseLanguageGeneration();

            Trace.TraceInformation("Done loading resources.");
        }
 public async Task TestDialogResourceModel()
 {
     var script = ResourceExplorer.LoadType <TestScript>("Lucy_TestRecognizer_Resource.test.dialog");
     await script.ExecuteAsync(ResourceExplorer);
 }
示例#12
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var context  = builder.GetContext();
            var services = builder.Services;

            // Adaptive component registration
            ComponentRegistration.Add(new DialogsComponentRegistration());
            ComponentRegistration.Add(new DeclarativeComponentRegistration());
            ComponentRegistration.Add(new AdaptiveComponentRegistration());
            ComponentRegistration.Add(new LanguageGenerationComponentRegistration());
            ComponentRegistration.Add(new GithubComponentRegistration());
            ComponentRegistration.Add(new LucyComponentRegistration());

            services.AddSingleton <Settings>((s) =>
            {
                var botSettings = new Settings();
                s.GetService <IConfiguration>().Bind(botSettings);
                return(botSettings);
            });
            services.AddLogging();
            services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>();
            services.AddSingleton <AuthenticationConfiguration>();
            services.AddSingleton <IStorage>((s) => new BlobsStorage(s.GetService <Settings>().AzureWebJobsStorage, s.GetService <Settings>().BotId.ToLower()));
            services.AddSingleton <UserState>(s => new UserState(s.GetService <IStorage>()));
            services.AddSingleton <ConversationState>(s => new ConversationState(s.GetService <IStorage>()));
            services.AddSingleton <QueueStorage>((s) => (QueueStorage) new AzureQueueStorage(s.GetService <Settings>().AzureWebJobsStorage, "activities"));

            // skill support
            // Register the skills client and skills request handler.
            //services.AddSingleton<SkillConversationIdFactoryBase, SkillConversationIdFactory>();
            //services.AddHttpClient<BotFrameworkClient, SkillHttpClient>();
            //services.AddSingleton<ChannelServiceHandler, SkillHandler>();

            // bot framework adapter defintion
            services.AddSingleton <BotFrameworkHttpAdapter>(s =>
            {
                // create botframework adapter for processing conversations with users.
                var adapter = new BotFrameworkHttpAdapter(s.GetService <ICredentialProvider>())
                              .Use(new RegisterClassMiddleware <IConfiguration>(s.GetService <IConfiguration>()))
                              .UseStorage(s.GetService <IStorage>())
                              .UseBotState(s.GetService <UserState>(), s.GetService <ConversationState>())
                              .UseDebugger(5001)
                              .Use(new RegisterClassMiddleware <QueueStorage>(s.GetService <QueueStorage>()))
                              .Use(new ShowTypingMiddleware());

                adapter.OnTurnError = async(turnContext, exception) =>
                {
                    await turnContext.SendActivityAsync(exception.Message).ConfigureAwait(false);
                    var conversationState = turnContext.TurnState.Get <ConversationState>();
                    await conversationState.ClearStateAsync(turnContext).ConfigureAwait(false);
                    await conversationState.SaveChangesAsync(turnContext).ConfigureAwait(false);
                };

                return((BotFrameworkHttpAdapter)adapter);
            });

            // add github adapter
            services.AddSingleton <GitHubAdapter>((s) =>
            {
                // create github adapter for processing webhooks
                return((GitHubAdapter) new GitHubAdapter(s.GetService <IConfiguration>())
                       .UseStorage(s.GetService <IStorage>())
                       .UseBotState(s.GetService <UserState>(), s.GetService <ConversationState>())
                       .Use(new RegisterClassMiddleware <QueueStorage>(s.GetService <QueueStorage>())));
            });

            // bot
            services.AddSingleton <IBot>((s) =>
            {
                // create bot using resourceexplorer and .dialog file
                var resourceExplorer = new ResourceExplorer()
                                       .AddFolder(context.ApplicationRootPath);

                var bot = new Bot()
                          .UseResourceExplorer(resourceExplorer)
                          .UseLanguageGeneration();

                bot.RootDialog            = resourceExplorer.LoadType <AdaptiveDialog>(resourceExplorer.GetResource("RepoBot.dialog"));
                resourceExplorer.Changed += (sender, e) => bot.RootDialog = resourceExplorer.LoadType <AdaptiveDialog>(resourceExplorer.GetResource("RepoBot.dialog"));
                return((IBot)bot);
            });
        }
 public async Task TestQluceneRecognizer_cached()
 {
     var script = ResourceExplorer.LoadType <TestScript>("QLucene_TestRecognizer_cached.test.dialog");
     await script.ExecuteAsync(ResourceExplorer);
 }
 public async Task TestQluceneRecognizerMultiLanguage()
 {
     var script = ResourceExplorer.LoadType <TestScript>("QLucene_TestMultiRecognizer.test.dialog");
     await script.ExecuteAsync(ResourceExplorer);
 }
示例#15
0
        public static async Task Main(string[] args)
        {
            var root        = ".";
            var region      = "westus";
            var environment = Environment.UserName;
            var userSecrets = "Runbot";

            for (var i = 0; i < args.Length; ++i)
            {
                var arg = args[i];
                switch (arg)
                {
                case "--root": root = NextArg(ref i, args); break;

                case "--region": region = NextArg(ref i, args); break;

                case "--environment": environment = NextArg(ref i, args); break;

                case "--userSecrets": userSecrets = NextArg(ref i, args); break;

                default: Usage(); break;
                }
            }

            ComponentRegistration.Add(new DeclarativeComponentRegistration());
            ComponentRegistration.Add(new AdaptiveComponentRegistration());
            ComponentRegistration.Add(new LanguageGenerationComponentRegistration());
            ComponentRegistration.Add(new AdaptiveTestingComponentRegistration());
            ComponentRegistration.Add(new LuisComponentRegistration());
            ComponentRegistration.Add(new QnAMakerComponentRegistration());

            var config = new ConfigurationBuilder()
                         .AddInMemoryCollection(new Dictionary <string, string> {
                { "root", root }, { "region", region }, { "environment", environment }
            })
                         .UseMockLuisSettings(root, userSecrets)
                         .AddUserSecrets(userSecrets)
                         .Build();
            var resourceExplorer = new ResourceExplorer().AddFolder(root, monitorChanges: false);

            resourceExplorer.RegisterType(LuisAdaptiveRecognizer.Kind, typeof(MockLuisRecognizer), new MockLuisLoader(config));

            var dialogs = resourceExplorer.GetResources(".dialog").ToList();

            foreach (var test in resourceExplorer.GetResources(".dialog").Where(r => r.Id.EndsWith(".test.dialog")))
            {
                try
                {
                    Console.WriteLine($"Running test {test.Id}");
                    var script = resourceExplorer.LoadType <TestScript>(test.Id);
                    script.Configuration = config;
                    script.Description ??= test.Id;
                    await script.ExecuteAsync(resourceExplorer, test.Id).ConfigureAwait(false);

                    Console.WriteLine("Passed\n");
                }
                catch (Exception e)
                {
                    Console.WriteLine($"*** Failed: {e.Message}\n");
                }
            }
        }
示例#16
0
        public static void Main(string[] args)
        {
            var    secret     = "profile";
            string luis       = null;
            var    iterations = 1;

            if (args.Length == 0)
            {
                Help();
            }

            for (var i = 0; i < args.Length; ++i)
            {
                var arg = args[i];
                if (arg.StartsWith("-"))
                {
                    if (arg == "-secret")
                    {
                        if (++i < args.Length)
                        {
                            secret = args[i];
                        }
                        else
                        {
                            throw new System.ArgumentException("Missing -secret value");
                        }
                    }
                    else if (arg == "-luis")
                    {
                        if (++i < args.Length)
                        {
                            luis = args[i];
                        }
                        else
                        {
                            throw new System.ArgumentException("Missing -luis value");
                        }
                    }
                    else if (arg == "-n")
                    {
                        if (++i < args.Length)
                        {
                            iterations = int.Parse(args[i]);
                        }
                        else
                        {
                            throw new System.ArgumentException("Missing -n value");
                        }
                    }
                    else
                    {
                        Console.Error.WriteLine($"Unknown arg {arg}");
                        Help();
                    }
                }
                else
                {
                    var cd     = Directory.GetCurrentDirectory();
                    var dir    = Path.GetDirectoryName(arg);
                    var name   = Path.GetFileName(arg);
                    var config = new ConfigurationBuilder()
                                 .AddInMemoryCollection()
                                 .UseMockLuisSettings(luis ?? dir, secret)
                                 .Build();

                    var explorer = new ResourceExplorer()
                                   .AddFolder(dir, monitorChanges: false)
                                   .RegisterType(LuisAdaptiveRecognizer.Kind, typeof(MockLuisRecognizer), new MockLuisLoader());
                    HostContext.Current.Set(config);
                    var script = explorer.LoadType <TestScript>(name);
                    var timer  = new System.Diagnostics.Stopwatch();
                    Console.WriteLine($"Executing {arg} for {iterations} iterations");
                    timer.Start();
                    var adapter = script.DefaultTestAdapter(testName: name, resourceExplorer: explorer);
                    timer.Stop();
                    var loading = timer.ElapsedMilliseconds;
                    Console.WriteLine($" loading took {loading} ms");

                    var iterationTime = 0L;
                    var firstTime     = 0l;
                    for (var iter = 0; iter < iterations; ++iter)
                    {
                        timer.Restart();
                        script.ExecuteAsync(explorer, adapter: adapter).Wait();
                        timer.Stop();
                        if (firstTime > 0)
                        {
                            iterationTime += timer.ElapsedMilliseconds;
                        }
                        else
                        {
                            firstTime = timer.ElapsedMilliseconds;
                        }

                        Console.WriteLine($"  {iter}: {timer.ElapsedMilliseconds} ms");
                    }

                    Console.Write($" Total time={loading + firstTime + iterationTime} ms");
                    if (iterations > 1)
                    {
                        Console.WriteLine($", per iteration after 1st={iterationTime / ((float)iterations - 1)} ms");
                    }
                }
            }
        }
示例#17
0
 private TestFlow BuildNoCycleTestFlow(string resourceName, string testName, bool sendTrace = false)
 {
     var adapter = InitializeAdapter(testName, sendTrace);
     var dialog = _noCycleResourceExplorer.LoadType<Dialog>(resourceName);
     return GetTestFlow(dialog, adapter, false);
 }
示例#18
0
        private void LoadDialogs()
        {
            System.Diagnostics.Trace.TraceInformation("Loading resources...");

            var rootDialog = new AdaptiveDialog()
            {
                AutoEndDialog = false,
            };
            var choiceInput = new ChoiceInput()
            {
                Prompt       = new ActivityTemplate("What declarative sample do you want to run?"),
                Property     = "conversation.dialogChoice",
                AlwaysPrompt = true,
                Choices      = new ChoiceSet(new List <Choice>())
            };

            var handleChoice = new SwitchCondition()
            {
                Condition = "conversation.dialogChoice",
                Cases     = new List <Case>()
            };

            Dialog lastDialog = null;
            var    choices    = new ChoiceSet();

            foreach (var resource in this.resourceExplorer.GetResources(".dialog").Where(r => r.Id.EndsWith(".main.dialog")))
            {
                try
                {
                    var name = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(resource.Id));
                    choices.Add(new Choice(name));
                    var dialog = resourceExplorer.LoadType <Dialog>(resource);
                    lastDialog = dialog;
                    handleChoice.Cases.Add(new Case($"{name}", new List <Dialog>()
                    {
                        dialog
                    }));
                }
                catch (SyntaxErrorException err)
                {
                    Trace.TraceError($"{err.Source}: Error: {err.Message}");
                }
                catch (Exception err)
                {
                    Trace.TraceError(err.Message);
                }
            }

            if (handleChoice.Cases.Count() == 1)
            {
                rootDialog.Triggers.Add(new OnBeginDialog()
                {
                    Actions = new List <Dialog>()
                    {
                        lastDialog,
                        new RepeatDialog()
                    }
                });
            }
            else
            {
                choiceInput.Choices = choices;
                choiceInput.Style   = ListStyle.Auto;
                rootDialog.Triggers.Add(new OnBeginDialog()
                {
                    Actions = new List <Dialog>()
                    {
                        choiceInput,
                        new SendActivity("# Running ${conversation.dialogChoice}.main.dialog"),
                        handleChoice,
                        new RepeatDialog()
                    }
                });
            }

            this.dialogManager = new DialogManager(rootDialog)
                                 .UseResourceExplorer(this.resourceExplorer)
                                 .UseLanguageGeneration();

            Trace.TraceInformation("Done loading resources.");
        }
示例#19
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var context       = builder.GetContext();
            var configuration = context.Configuration;
            var services      = builder.Services;
            var hostname      = configuration.GetValue <string>("WEBSITE_HOSTNAME");

            // Adaptive component registration
            ComponentRegistration.Add(new DialogsComponentRegistration());
            ComponentRegistration.Add(new DeclarativeComponentRegistration());
            ComponentRegistration.Add(new AdaptiveComponentRegistration());
            ComponentRegistration.Add(new LanguageGenerationComponentRegistration());
            ComponentRegistration.Add(new LucyComponentRegistration());

            services.AddLogging();
            services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>();
            services.AddSingleton(sp => new AuthenticationConfiguration {
                ClaimsValidator = new AllowedCallersClaimsValidator(configuration)
            });
            services.AddSingleton <IStorage>((s) => new BlobsStorage(configuration.GetValue <string>("AzureWebJobsStorage"), configuration.GetValue <string>("BotId").ToLower()));
            services.AddSingleton <UserState>(s => new UserState(s.GetService <IStorage>()));
            services.AddSingleton <ConversationState>(s => new ConversationState(s.GetService <IStorage>()));
            services.AddSingleton <QueueStorage>((s) => (QueueStorage) new AzureQueueStorage(configuration.GetValue <string>("AzureWebJobsStorage"), "activities"));

            // skill support
            // Register the skills client and skills request handler.
            services.AddSingleton <SkillConversationIdFactoryBase, SkillConversationIdFactory>();
            services.AddHttpClient <SkillHttpClient>();
            services.AddSingleton <SkillHandler>();

            // bot framework adapter defintion
            services.AddSingleton <BotFrameworkHttpAdapter>(s =>
            {
                // create botframework adapter for processing conversations with users.
                var adapter = new BotFrameworkHttpAdapter(s.GetService <ICredentialProvider>(), s.GetService <AuthenticationConfiguration>())
                              .Use(new RegisterClassMiddleware <IConfiguration>(s.GetService <IConfiguration>()))
                              .UseStorage(s.GetService <IStorage>())
                              .UseBotState(s.GetService <UserState>(), s.GetService <ConversationState>())
                              //.Use(new TranscriptLoggerMiddleware(s.GetService<ITranscriptStore>()))
                              .Use(new RegisterClassMiddleware <QueueStorage>(s.GetService <QueueStorage>()));

                if (hostname.StartsWith("localhost") && int.TryParse(hostname.Split(':')[1], out var port))
                {
                    adapter.UseDebugger(port + 1000);
                }

                adapter.OnTurnError = async(turnContext, exception) =>
                {
                    var log = s.GetService <ILogger>();
                    var conversationState = turnContext.TurnState.Get <ConversationState>();
                    await conversationState.ClearStateAsync(turnContext).ConfigureAwait(false);
                    await conversationState.SaveChangesAsync(turnContext).ConfigureAwait(false);

                    try
                    {
                        await turnContext.TraceActivityAsync("OnTurnError Trace", exception.ToString(), "https://www.botframework.com/schemas/error", "TurnError");
                        await turnContext.SendActivityAsync(exception.Message).ConfigureAwait(false);
                    }
                    catch (Exception err)
                    {
                        log?.LogError(err, err.Message);
                    }

                    log?.LogError(exception, exception.Message);
                };

                return((BotFrameworkHttpAdapter)adapter);
            });
            services.AddSingleton <BotAdapter>(s => (BotAdapter)s.GetService <BotFrameworkHttpAdapter>());
            services.AddSingleton <IBotFrameworkHttpAdapter>(s => (IBotFrameworkHttpAdapter)s.GetService <BotFrameworkHttpAdapter>());


            // bot
            services.AddSingleton <IBot>((s) =>
            {
                // create bot using resourceexplorer and .dialog file
                var config = s.GetService <IConfiguration>();
                string rootDialogFolder = "LucyBot";
                string rootDialog       = "LucyBot.dialog";
                string rootPath         = GetDialogsFolder(config, context.ApplicationRootPath, rootDialogFolder);
                var resourceExplorer    = new ResourceExplorer()
                                          .AddFolder(rootPath);

                var bot = new Bot()
                          .UseResourceExplorer(resourceExplorer)
                          .UseLanguageGeneration();

                bot.InitialTurnState.Set <BotFrameworkClient>(s.GetService <SkillHttpClient>());
                bot.InitialTurnState.Set(s.GetService <SkillConversationIdFactoryBase>());
                bot.InitialTurnState.Set <BotAdapter>(s.GetService <BotAdapter>());
                bot.InitialTurnState.Add(s.GetService <QueueStorage>());
                // bot.InitialTurnState.Add(s.GetService<ITranscriptStore>());

                bot.RootDialog            = resourceExplorer.LoadType <AdaptiveDialog>(resourceExplorer.GetResource(rootDialog));
                resourceExplorer.Changed += (sender, e) =>
                {
                    Console.WriteLine("Resources changed, reloading...");
                    bot.RootDialog = resourceExplorer.LoadType <AdaptiveDialog>(resourceExplorer.GetResource(rootDialog));
                };
                return((IBot)bot);
            });
        }