コード例 #1
0
ファイル: Program.cs プロジェクト: amyngb/HikingClimbingBot
        public static async Task Main(string[] args)
        {
            var root        = ".";
            var region      = "westus";
            var environment = Environment.UserName;

            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;

                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, root)
                         .AddUserSecrets("RunBot")
                         .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");
                }
            }
        }
コード例 #2
0
        public void TestFolderSource_Shallow()
        {
            var path = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, PathUtils.NormalizePath(@"..\..\..")));

            using (var explorer = new ResourceExplorer())
            {
                explorer.AddFolder(path, false);

                var resources = explorer.GetResources("dialog").ToArray();
                Assert.Empty(resources);

                resources = explorer.GetResources("schema").ToArray();
                Assert.True(resources.Length > 0, "shallow folder should list the root files");
            }
        }
コード例 #3
0
        public static void ClassInitialize(TestContext context)
        {
            // static field initialization
            var projectPath  = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, PathUtils.NormalizePath(@"..\..\..")));
            var testsPath    = Path.GetFullPath(Path.Combine(projectPath, ".."));
            var solutionPath = Path.GetFullPath(Path.Combine(projectPath, PathUtils.NormalizePath(@"..\..")));
            var schemaPath   = Path.Combine(testsPath, "tests.schema");

            var ignoreFolders = new string[]
            {
                PathUtils.NormalizePath(@"Microsoft.Bot.Builder.TestBot.Json\Samples\EmailBot"),
                PathUtils.NormalizePath(@"Microsoft.Bot.Builder.TestBot.Json\Samples\CalendarBot"),
                "bin"
            };

            ResourceExplorer = new ResourceExplorer()
                               .AddFolders(Path.Combine(solutionPath, "libraries"), monitorChanges: false)
                               .AddFolders(Path.Combine(solutionPath, "tests"), monitorChanges: false);

            Dialogs = ResourceExplorer.GetResources(".dialog")
                      .Cast <FileResource>()
                      .Where(r => !r.Id.EndsWith(".schema.dialog") && !ignoreFolders.Any(f => r.FullName.Contains(f)))
                      .Select(resource => new object[] { resource });

            try
            {
                ProcessStartInfo startInfo;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    startInfo = new ProcessStartInfo("cmd.exe", $"/C bf.cmd dialog:merge ../../libraries/**/*.schema ../**/*.schema -o {schemaPath}");
                    startInfo.WorkingDirectory      = projectPath;
                    startInfo.UseShellExecute       = false;
                    startInfo.CreateNoWindow        = false;
                    startInfo.RedirectStandardError = true;

                    // startInfo.RedirectStandardOutput = true;
                    // string output = process.StandardOutput.ReadToEnd();

                    var    process = Process.Start(startInfo);
                    string error   = process.StandardError.ReadToEnd();
                    process.WaitForExit();

                    if (!string.IsNullOrEmpty(error))
                    {
                        Trace.TraceError(error);
                    }
                }
            }
            catch (Exception err)
            {
                Trace.TraceError(err.Message);
            }

            if (File.Exists(schemaPath))
            {
                var json = File.ReadAllText(schemaPath);
                Schema = JSchema.Parse(json);
            }
        }
コード例 #4
0
        public static Dictionary <string, IList <Resource> > GroupByLocale(ResourceExplorer resourceExplorer)
        {
            var resourceMapping = new Dictionary <string, IList <Resource> >();
            var allResources    = resourceExplorer.GetResources("lg");
            var languagePolicy  = new LanguagePolicy();

            foreach (var item in languagePolicy)
            {
                var locale     = item.Key;
                var suffixs    = item.Value;
                var existNames = new HashSet <string>();
                foreach (var suffix in suffixs)
                {
                    if (string.IsNullOrEmpty(locale) || !string.IsNullOrEmpty(suffix))
                    {
                        var resourcesWithSuchSuffix = allResources.Where(u => ParseLGFileName(u.Id).language == suffix);
                        foreach (var resourceWithSuchSuffix in resourcesWithSuchSuffix)
                        {
                            var resourceName = resourceWithSuchSuffix.Id;
                            var length       = string.IsNullOrEmpty(suffix) ? 3 : 4;
                            var prefixName   = resourceName.Substring(0, resourceName.Length - suffix.Length - length);
                            if (!existNames.Contains(prefixName))
                            {
                                existNames.Add(prefixName);
                                if (!resourceMapping.ContainsKey(locale))
                                {
                                    resourceMapping.Add(locale, new List <Resource> {
                                        resourceWithSuchSuffix
                                    });
                                }
                                else
                                {
                                    resourceMapping[locale].Add(resourceWithSuchSuffix);
                                }
                            }
                        }
                    }
                    else
                    {
                        if (resourceMapping.ContainsKey(locale))
                        {
                            var resourcesWithEmptySuffix = allResources.Where(u => ParseLGFileName(u.Id).language.Length == 0);
                            foreach (var resourceWithEmptySuffix in resourcesWithEmptySuffix)
                            {
                                var resourceName = resourceWithEmptySuffix.Id;
                                var prefixName   = resourceName.Substring(0, resourceName.Length - 3);
                                if (!existNames.Contains(prefixName))
                                {
                                    existNames.Add(prefixName);
                                    resourceMapping[locale].Add(resourceWithEmptySuffix);
                                }
                            }
                        }
                    }
                }
            }

            return(FallbackMultiLangResource(resourceMapping));
        }
コード例 #5
0
        public void TestFolderSource()
        {
            var path = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, PathUtils.NormalizePath(@"..\..\..")));

            using (var explorer = new ResourceExplorer())
            {
                explorer.AddResourceProvider(new FolderResourceProvider(explorer, path));

                var resources = explorer.GetResources(".dialog").ToArray();

                Assert.Equal(4, resources.Length);
                Assert.Equal($".dialog", Path.GetExtension(resources[0].Id));

                resources = explorer.GetResources("foo").ToArray();
                Assert.Empty(resources);
            }
        }
コード例 #6
0
        private static async Task AssertResourceType(string path, ResourceExplorer explorer, string resourceType)
        {
            var resources = explorer.GetResources(resourceType).ToArray();

            Assert.AreEqual(1, resources.Length);
            Assert.AreEqual($".{resourceType}", Path.GetExtension(resources[0].Id));
            await Task.FromResult <object>(null);
        }
コード例 #7
0
        private static void AssertResourceFound(ResourceExplorer explorer, string id)
        {
            var dialog = explorer.GetResource(id);

            Assert.NotNull(dialog);
            var dialogs = explorer.GetResources("dialog");

            Assert.True(dialogs.Any(d => d.Id == id), $"getResources({id}) should return resource");
        }
コード例 #8
0
        /// <summary>
        /// Find all foo.function.js resources and mount as expression functions
        /// </summary>
        /// <param name="resourceExplorer"></param>
        /// <returns></returns>
        public static void AddJavascriptFunctions(ResourceExplorer resourceExplorer)
        {
            resourceExplorer.AddResourceType("js");

            foreach (var resource in resourceExplorer.GetResources("js").Where(res => res.Id.EndsWith(".function.js")))
            {
                AddFunctions(resource);
            }

            resourceExplorer.Changed -= ResourceExplorer_Changed;
            resourceExplorer.Changed += ResourceExplorer_Changed;
        }
コード例 #9
0
        private async Task AssertResourceContents(ResourceExplorer explorer, string id, string contents)
        {
            var resource = explorer.GetResource(id);

            var text = await resource.ReadTextAsync();

            Assert.Equal(contents, text);
            resource = explorer.GetResources("dialog").Single(d => d.Id == id);

            text = await resource.ReadTextAsync();

            Assert.Equal(contents, text);
        }
コード例 #10
0
        private async Task AssertResourceContents(ResourceExplorer explorer, string id, string contents)
        {
            var resource = explorer.GetResource(id);

            var text = await resource.ReadTextAsync();

            Assert.AreEqual(contents, text, $"getResource({id}) contents not the same ");
            resource = explorer.GetResources("dialog").Where(d => d.Id == id).Single();

            text = await resource.ReadTextAsync();

            Assert.AreEqual(contents, text, $"getResources({id}) contents not the same");
        }
コード例 #11
0
        public async Task TestFolderSource()
        {
            var path = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, PathUtils.NormalizePath(@"..\..\..")));

            using (var explorer = new ResourceExplorer())
            {
                explorer.AddResourceProvider(new FolderResourceProvider(explorer, path));

                await AssertResourceType(path, explorer, "dialog");

                var resources = explorer.GetResources("foo").ToArray();
                Assert.AreEqual(0, resources.Length);
            }
        }
コード例 #12
0
        private static void AssertResourceNull(ResourceExplorer explorer, string id)
        {
            try
            {
                var dialog = explorer.GetResource(id);
                Assert.Fail($"GetResource({id}) should throw");
            }
            catch (ArgumentException err)
            {
                Assert.AreEqual(err.ParamName, id, "Should throw error with resource id in it");
            }

            var dialogs = explorer.GetResources("dialog");

            Assert.IsFalse(dialogs.Where(d => d.Id == id).Any(), $"getResources({id}) should not return resource");
        }
コード例 #13
0
        private static void AssertResourceNull(ResourceExplorer explorer, string id)
        {
            try
            {
                explorer.GetResource(id);
                throw new XunitException($"GetResource({id}) should throw");
            }
            catch (ArgumentException err)
            {
                Assert.Equal(err.ParamName, id);
            }

            var dialogs = explorer.GetResources("dialog");

            Assert.False(dialogs.Any(d => d.Id == id), $"getResources({id}) should not return resource");
        }
コード例 #14
0
        public async Task EmbeddedResource_Tests()
        {
            var resource = ResourceExplorer.GetResource("foo.en-us.lg");

            Assert.IsNotNull(resource);

            var contents = await resource.ReadTextAsync();

            Assert.IsTrue(contents.Contains("Hi"));

            var lgResources = ResourceExplorer.GetResources("lg").ToList <Resource>();

            Assert.IsTrue(lgResources.Any(r => r.Id == "foo.en-us.lg"));
            Assert.IsTrue(lgResources.Any(r => r.Id == "common.en-us.lg"));

            lgResources = ResourceExplorer.GetResources("dialog").ToList <Resource>();
            Assert.IsTrue(lgResources.Any(r => r.Id == "Test.dialog"));

            lgResources = ResourceExplorer.GetResources("yaml").ToList <Resource>();
            Assert.IsTrue(lgResources.Any(r => r.Id == "foo.en.lucy.yaml"));
        }
コード例 #15
0
        /// <summary>
        /// Initializes static members of the <see cref="SchemaMergeTests"/> class.
        /// </summary>
        /// <remarks>
        /// This constructor  loads the dialogs to be tested in a static <see cref="Dialogs"/> property so they can be used in theory tests.
        /// </remarks>
        static SchemaMergeTests()
        {
            var ignoreFolders = new[]
            {
                PathUtils.NormalizePath(@"Microsoft.Bot.Builder.TestBot.Json\Samples\EmailBot"),
                PathUtils.NormalizePath(@"Microsoft.Bot.Builder.TestBot.Json\Samples\CalendarBot"),
                "bin"
            };

            var resourceExplorer = new ResourceExplorer()
                                   .AddFolders(Path.Combine(SchemaTestsFixture.SolutionPath, "libraries"), monitorChanges: false)
                                   .AddFolders(Path.Combine(SchemaTestsFixture.SolutionPath, "tests"), monitorChanges: false);

            // Store the dialog list in the Dialogs property.
            Dialogs = resourceExplorer.GetResources(".dialog")
                      .Cast <FileResource>()
                      .Where(r => !r.Id.EndsWith(".schema.dialog") && !ignoreFolders.Any(f => r.FullName.Contains(f)))
                      .Select(resource => new object[]
            {
                resource.Id,
                resource.FullName
            });
        }
コード例 #16
0
        /// <summary>
        /// Populates the <see cref="LanguageGenerators"/> property with <see cref="Lazy{LaguageGenerator}" /> instances.
        /// </summary>
        /// <remarks>
        /// If the resource contains exports, this method also ensure the LanguageGenerator instance is loaded and ready to use.
        /// </remarks>
        private void PopulateLanguageGenerators()
        {
            var resources = _resourceExplorer.GetResources("lg");

            // Create one LanguageGenerator for each resource.
            foreach (var resource in resources)
            {
                LanguageGenerators[resource.Id] = new Lazy <LanguageGenerator>(() =>
                {
                    // Creates the generator when requested and loads it.
                    var generator = new TemplateEngineLanguageGenerator(resource, _multilanguageResources);
                    generator.LoadAsync().GetAwaiter().GetResult();
                    return(generator);
                });

                // Check if the file contains exports.
                if (ContainsExport(resource))
                {
                    // Force lazy creation for lg files that contain exports
                    // Exports need to be available globally and need to be parsed at startup
                    _ = LanguageGenerators[resource.Id].Value;
                }
            }
        }
コード例 #17
0
        public virtual IEnumerable <DeclarativeType> GetDeclarativeTypes(ResourceExplorer resourceExplorer)
        {
            // Conditionals
            yield return(new DeclarativeType <OnCondition>(OnCondition.DeclarativeType));

            yield return(new DeclarativeType <OnError>(OnError.DeclarativeType));

            yield return(new DeclarativeType <OnDialogEvent>(OnDialogEvent.DeclarativeType));

            yield return(new DeclarativeType <OnCustomEvent>(OnCustomEvent.DeclarativeType));

            yield return(new DeclarativeType <OnBeginDialog>(OnBeginDialog.DeclarativeType));

            yield return(new DeclarativeType <OnCancelDialog>(OnCancelDialog.DeclarativeType));

            yield return(new DeclarativeType <OnRepromptDialog>(OnRepromptDialog.DeclarativeType));

            yield return(new DeclarativeType <OnIntent>(OnIntent.DeclarativeType));

            yield return(new DeclarativeType <OnUnknownIntent>(OnUnknownIntent.DeclarativeType));

            yield return(new DeclarativeType <OnActivity>(OnActivity.DeclarativeType));

            yield return(new DeclarativeType <OnMessageActivity>(OnMessageActivity.DeclarativeType));

            yield return(new DeclarativeType <OnMessageUpdateActivity>(OnMessageUpdateActivity.DeclarativeType));

            yield return(new DeclarativeType <OnMessageDeleteActivity>(OnMessageDeleteActivity.DeclarativeType));

            yield return(new DeclarativeType <OnMessageReactionActivity>(OnMessageReactionActivity.DeclarativeType));

            yield return(new DeclarativeType <OnEventActivity>(OnEventActivity.DeclarativeType));

            yield return(new DeclarativeType <OnInvokeActivity>(OnInvokeActivity.DeclarativeType));

            yield return(new DeclarativeType <OnConversationUpdateActivity>(OnConversationUpdateActivity.DeclarativeType));

            yield return(new DeclarativeType <OnEndOfConversationActivity>(OnEndOfConversationActivity.DeclarativeType));

            yield return(new DeclarativeType <OnTypingActivity>(OnTypingActivity.DeclarativeType));

            yield return(new DeclarativeType <OnHandoffActivity>(OnHandoffActivity.DeclarativeType));

            yield return(new DeclarativeType <OnChooseIntent>(OnChooseIntent.DeclarativeType));

            yield return(new DeclarativeType <OnEndOfActions>(OnEndOfActions.DeclarativeType));

            yield return(new DeclarativeType <OnChooseProperty>(OnChooseProperty.DeclarativeType));

            yield return(new DeclarativeType <OnChooseEntity>(OnChooseEntity.DeclarativeType));

            yield return(new DeclarativeType <OnClearProperty>(OnClearProperty.DeclarativeType));

            yield return(new DeclarativeType <OnAssignEntity>(OnAssignEntity.DeclarativeType));

            // Actions
            yield return(new DeclarativeType <BeginDialog>(BeginDialog.DeclarativeType));

            yield return(new DeclarativeType <CancelAllDialogs>(CancelAllDialogs.DeclarativeType));

            yield return(new DeclarativeType <DebugBreak>(DebugBreak.DeclarativeType));

            yield return(new DeclarativeType <DeleteProperty>(DeleteProperty.DeclarativeType));

            yield return(new DeclarativeType <DeleteProperties>(DeleteProperties.DeclarativeType));

            yield return(new DeclarativeType <EditArray>(EditArray.DeclarativeType));

            yield return(new DeclarativeType <EditActions>(EditActions.DeclarativeType));

            yield return(new DeclarativeType <EmitEvent>(EmitEvent.DeclarativeType));

            yield return(new DeclarativeType <EndDialog>(EndDialog.DeclarativeType));

            yield return(new DeclarativeType <EndTurn>(EndTurn.DeclarativeType));

            yield return(new DeclarativeType <Foreach>(Foreach.DeclarativeType));

            yield return(new DeclarativeType <ForeachPage>(ForeachPage.DeclarativeType));

            yield return(new DeclarativeType <HttpRequest>(HttpRequest.DeclarativeType));

            yield return(new DeclarativeType <IfCondition>(IfCondition.DeclarativeType));

            yield return(new DeclarativeType <LogAction>(LogAction.DeclarativeType));

            yield return(new DeclarativeType <RepeatDialog>(RepeatDialog.DeclarativeType));

            yield return(new DeclarativeType <ReplaceDialog>(ReplaceDialog.DeclarativeType));

            yield return(new DeclarativeType <SendActivity>(SendActivity.DeclarativeType));

            yield return(new DeclarativeType <SetProperty>(SetProperty.DeclarativeType));

            yield return(new DeclarativeType <SetProperties>(SetProperties.DeclarativeType));

            yield return(new DeclarativeType <SwitchCondition>(SwitchCondition.DeclarativeType));

            yield return(new DeclarativeType <TraceActivity>(TraceActivity.DeclarativeType));

            yield return(new DeclarativeType <GotoAction>(GotoAction.DeclarativeType));

            yield return(new DeclarativeType <BreakLoop>(BreakLoop.DeclarativeType));

            yield return(new DeclarativeType <ContinueLoop>(ContinueLoop.DeclarativeType));

            yield return(new DeclarativeType <UpdateActivity>(UpdateActivity.DeclarativeType));

            yield return(new DeclarativeType <DeleteActivity>(DeleteActivity.DeclarativeType));

            yield return(new DeclarativeType <GetActivityMembers>(GetActivityMembers.DeclarativeType));

            yield return(new DeclarativeType <GetConversationMembers>(GetConversationMembers.DeclarativeType));

            yield return(new DeclarativeType <SignOutUser>(SignOutUser.DeclarativeType));

            // Inputs
            yield return(new DeclarativeType <AttachmentInput>(AttachmentInput.DeclarativeType));

            yield return(new DeclarativeType <ConfirmInput>(ConfirmInput.DeclarativeType));

            yield return(new DeclarativeType <NumberInput>(NumberInput.DeclarativeType));

            yield return(new DeclarativeType <TextInput>(TextInput.DeclarativeType));

            yield return(new DeclarativeType <ChoiceInput>(ChoiceInput.DeclarativeType));

            yield return(new DeclarativeType <DateTimeInput>(DateTimeInput.DeclarativeType));

            yield return(new DeclarativeType <OAuthInput>(OAuthInput.DeclarativeType));

            yield return(new DeclarativeType <Ask>(Ask.DeclarativeType));

            // Recognizers
            yield return(new DeclarativeType <RegexRecognizer>(RegexRecognizer.DeclarativeType));

            yield return(new DeclarativeType <MultiLanguageRecognizer>(MultiLanguageRecognizer.DeclarativeType));

            yield return(new DeclarativeType <RecognizerSet>(RecognizerSet.DeclarativeType));

            yield return(new DeclarativeType <CrossTrainedRecognizerSet>(CrossTrainedRecognizerSet.DeclarativeType));

            yield return(new DeclarativeType <ValueRecognizer>(ValueRecognizer.DeclarativeType));

            // Entity recognizers
            yield return(new DeclarativeType <AgeEntityRecognizer>(AgeEntityRecognizer.DeclarativeType));

            yield return(new DeclarativeType <ConfirmationEntityRecognizer>(ConfirmationEntityRecognizer.DeclarativeType));

            yield return(new DeclarativeType <CurrencyEntityRecognizer>(CurrencyEntityRecognizer.DeclarativeType));

            yield return(new DeclarativeType <DateTimeEntityRecognizer>(DateTimeEntityRecognizer.DeclarativeType));

            yield return(new DeclarativeType <DimensionEntityRecognizer>(DimensionEntityRecognizer.DeclarativeType));

            yield return(new DeclarativeType <EmailEntityRecognizer>(EmailEntityRecognizer.DeclarativeType));

            yield return(new DeclarativeType <EntityRecognizerSet>(EntityRecognizerSet.DeclarativeType));

            yield return(new DeclarativeType <GuidEntityRecognizer>(GuidEntityRecognizer.DeclarativeType));

            yield return(new DeclarativeType <HashtagEntityRecognizer>(HashtagEntityRecognizer.DeclarativeType));

            yield return(new DeclarativeType <IpEntityRecognizer>(IpEntityRecognizer.DeclarativeType));

            yield return(new DeclarativeType <MentionEntityRecognizer>(MentionEntityRecognizer.DeclarativeType));

            yield return(new DeclarativeType <NumberEntityRecognizer>(NumberEntityRecognizer.DeclarativeType));

            yield return(new DeclarativeType <NumberRangeEntityRecognizer>(NumberRangeEntityRecognizer.DeclarativeType));

            yield return(new DeclarativeType <OrdinalEntityRecognizer>(OrdinalEntityRecognizer.DeclarativeType));

            yield return(new DeclarativeType <PercentageEntityRecognizer>(PercentageEntityRecognizer.DeclarativeType));

            yield return(new DeclarativeType <PhoneNumberEntityRecognizer>(PhoneNumberEntityRecognizer.DeclarativeType));

            yield return(new DeclarativeType <RegexEntityRecognizer>(RegexEntityRecognizer.DeclarativeType));

            yield return(new DeclarativeType <TemperatureEntityRecognizer>(TemperatureEntityRecognizer.DeclarativeType));

            yield return(new DeclarativeType <UrlEntityRecognizer>(UrlEntityRecognizer.DeclarativeType));

            // selectors
            yield return(new DeclarativeType <ConditionalSelector>(ConditionalSelector.DeclarativeType));

            yield return(new DeclarativeType <FirstSelector>(FirstSelector.DeclarativeType));

            yield return(new DeclarativeType <MostSpecificSelector>(MostSpecificSelector.DeclarativeType));

            yield return(new DeclarativeType <RandomSelector>(RandomSelector.DeclarativeType));

            yield return(new DeclarativeType <TrueSelector>(TrueSelector.DeclarativeType));

            // Generators
            yield return(new DeclarativeType <ResourceMultiLanguageGenerator>(ResourceMultiLanguageGenerator.DeclarativeType));

            yield return(new DeclarativeType <MultiLanguageGenerator>(MultiLanguageGenerator.DeclarativeType));

            yield return(new DeclarativeType <TemplateEngineLanguageGenerator>(TemplateEngineLanguageGenerator.DeclarativeType));

            // Dialogs
            yield return(new DeclarativeType <AdaptiveDialog>(AdaptiveDialog.DeclarativeType));

            yield return(new DeclarativeType <AdaptiveSkillDialog>(AdaptiveSkillDialog.DeclarativeType));

            // register x.dialog.schema/x.dialog as DynamicBeginDialog $kind="x" => DynamicBeginDialog(x.dialog) resource.
            foreach (var schema in resourceExplorer.GetResources(".schema").Where(s => resourceExplorer.GetTypeForKind(Path.GetFileNameWithoutExtension(s.Id)) == null))
            {
                // x.dialog.schema => resourceType=dialog resourceId=x.dialog $kind=x
                var resourceId   = Path.GetFileNameWithoutExtension(schema.Id);
                var resourceType = Path.GetExtension(resourceId).TrimStart('.').ToLowerInvariant();
                var kind         = Path.GetFileNameWithoutExtension(resourceId);

                // load dynamic dialogs
                switch (resourceType)
                {
                case "dialog":
                    yield return(new DeclarativeType <DynamicBeginDialog>(kind)
                    {
                        CustomDeserializer = new DynamicBeginDialogDeserializer(resourceExplorer, resourceId)
                    });

                    break;
                }
            }
        }
コード例 #18
0
ファイル: RunBot.cs プロジェクト: amyngb/HikingClimbingBot
        private void LoadDialogs()
        {
            System.Diagnostics.Trace.TraceInformation("Loading resources...");

            var rootDialog = new AdaptiveDialog()
            {
                AutoEndDialog = false,
            };
            var choiceInput = new ChoiceInput()
            {
                Prompt       = new ActivityTemplate("What dialog 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 _resourceExplorer.GetResources(".dialog").Where(r => dialogName != null ? r.Id == dialogName : r.Id.Count(c => c == '.') == 1))
            {
                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}.dialog"),
                        handleChoice,
                        new RepeatDialog()
                    }
                });
            }

            _dialogManager = new DialogManager(rootDialog)
                             .UseResourceExplorer(_resourceExplorer)
                             .UseLanguageGeneration();

            Trace.TraceInformation("Done loading resources.");
        }