private void LoadRootDialogAsync()
        {
            var rootFile = resourceExplorer.GetResource(RootDialogFile);

            rootDialog         = DeclarativeTypeLoader.Load <AdaptiveDialog>(rootFile, resourceExplorer, sourceMap);
            this.dialogManager = new DialogManager(rootDialog);
        }
Exemplo n.º 2
0
        public async Task DebugComposerBot()
        {
            // luis.settings.{environment}.{region}.json
            var environment = Environment.UserName;
            var region      = "westus";
            var botPath     = Path.Combine(TestUtils.GetProjectPath(), "Tests");
            var testScript  = "debug.test.dialog";
            var locale      = "en-US";

            var resourceExplorer = new ResourceExplorer()
                                   .AddFolder(botPath, monitorChanges: false);

            // add luis settings if there are luis assets
            var resource = resourceExplorer.GetResource($"luis.settings.{environment}.{region}.json") as FileResource;
            var builder  = new ConfigurationBuilder().AddInMemoryCollection();

            if (resource != null)
            {
                builder.AddJsonFile(resource.FullName);
            }

            var script = resourceExplorer.LoadType <TestScript>(testScript);

            script.Locale        = locale;
            script.Configuration = builder.Build();
            await script.ExecuteAsync(resourceExplorer : resourceExplorer).ConfigureAwait(false);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CoreBot"/> class.
        /// </summary>
        /// <param name="options">Configured options for the <see cref="CoreBot"/> instance.</param>
        /// <param name="conversationState"><see cref="ConversationState"/> for the bot.</param>
        /// <param name="userState"><see cref="UserState"/> instance for the bot.</param>
        /// <param name="resourceExplorer"><see cref="ResourceExplorer"/> instance to access declarative assets.</param>
        /// <param name="telemetryClient"><see cref="IBotTelemetryClient"/> for the bot.</param>
        /// <param name="botFrameworkClient"><see cref="BotFrameworkClient"/> instance for the bot.</param>
        /// <param name="conversationIdfactory"><see cref="SkillConversationIdFactoryBase"/> instance for the bot.</param>
        public CoreBot(
            IOptions <CoreBotOptions> options,
            ConversationState conversationState,
            UserState userState,
            ResourceExplorer resourceExplorer,
            IBotTelemetryClient telemetryClient,
            BotFrameworkClient botFrameworkClient,
            SkillConversationIdFactoryBase conversationIdfactory)
        {
            _conversationState = conversationState;
            _userState         = userState;

            Resource rootDialogResource = resourceExplorer.GetResource(options.Value.RootDialog);
            var      rootDialog         = resourceExplorer.LoadType <AdaptiveDialog>(rootDialogResource);

            _dialogManager = new DialogManager(rootDialog)
                             .UseResourceExplorer(resourceExplorer)
                             .UseLanguageGeneration()
                             .UseLanguagePolicy(new LanguagePolicy(options.Value.DefaultLocale ?? DefaultLocale));

            if (telemetryClient != null)
            {
                _dialogManager.UseTelemetry(telemetryClient);
            }

            _dialogManager.InitialTurnState.Set(botFrameworkClient);
            _dialogManager.InitialTurnState.Set(conversationIdfactory);
            _dialogManager.InitialTurnState.Set(_userState);
            _dialogManager.InitialTurnState.Set(_conversationState);
        }
Exemplo n.º 4
0
        public RootDialog(UserState userState) : base("root")
        {
            _userState = userState;

            AddDialog(new UserProfileDialog(userState));

            // The initial child Dialog to run.
            InitialDialogId = "waterfall";

            // Get Folder of dialogs.
            var resourceExplorer = new ResourceExplorer().AddFolder("Dialogs");

            // find the main composer dialog to start with
            var composerDialog = resourceExplorer.GetResource("Main.dialog");

            // hyrdate an Adaptive Dialogue
            AdaptiveDialog myComposerDialog = DeclarativeTypeLoader.Load <AdaptiveDialog>(composerDialog, resourceExplorer, DebugSupport.SourceMap);

            myComposerDialog.Id = "Main.dialog";

            // setup lanaguage generation for the dialogue
            myComposerDialog.Generator = new TemplateEngineLanguageGenerator(new TemplateEngine().AddFile(@"C:\Users\Jamie\source\repos\composer-adaptive-regular-hybrid\Dialogs\ComposerDialogs\Main\Main.lg"));

            // add to the ComponentDialog which Root dialogue inherits from
            AddDialog(myComposerDialog);

            AddDialog(new WaterfallDialog("waterfall", new WaterfallStep[] { StartDialogAsync, BeginComposerAdaptiveDialog }));
        }
Exemplo n.º 5
0
        public async Task TestMultiLanguageGenerator()
        {
            var lg = new MultiLanguageGenerator();

            lg.LanguageGenerators[string.Empty] = new TemplateEngineLanguageGenerator(resourceExplorer.GetResource("test.lg").ReadTextAsync().Result, "test.lg", resourceResolver);
            lg.LanguageGenerators["de"]         = new TemplateEngineLanguageGenerator(resourceExplorer.GetResource("test.de.lg").ReadTextAsync().Result, "test.de.lg", resourceResolver);
            lg.LanguageGenerators["en"]         = new TemplateEngineLanguageGenerator(resourceExplorer.GetResource("test.en.lg").ReadTextAsync().Result, "test.en.lg", resourceResolver);
            lg.LanguageGenerators["en-US"]      = new TemplateEngineLanguageGenerator(resourceExplorer.GetResource("test.en-US.lg").ReadTextAsync().Result, "test.en-US.lg", resourceResolver);
            lg.LanguageGenerators["en-GB"]      = new TemplateEngineLanguageGenerator(resourceExplorer.GetResource("test.en-GB.lg").ReadTextAsync().Result, "test.en-GB.lg", resourceResolver);
            lg.LanguageGenerators["fr"]         = new TemplateEngineLanguageGenerator(resourceExplorer.GetResource("test.fr.lg").ReadTextAsync().Result, "test.fr.lg", resourceResolver);

            // test targeted in each language
            Assert.AreEqual("english-us", await lg.Generate(GetTurnContext(locale: "en-us"), "[test]", null));
            Assert.AreEqual("english-gb", await lg.Generate(GetTurnContext(locale: "en-gb"), "[test]", null));
            Assert.AreEqual("english", await lg.Generate(GetTurnContext(locale: "en"), "[test]", null));
            Assert.AreEqual("default", await lg.Generate(GetTurnContext(locale: string.Empty), "[test]", null));
            Assert.AreEqual("default", await lg.Generate(GetTurnContext(locale: "foo"), "[test]", null));

            // test fallback for en-us -> en -> default
            Assert.AreEqual("default2", await lg.Generate(GetTurnContext(locale: "en-us"), "[test2]", null));
            Assert.AreEqual("default2", await lg.Generate(GetTurnContext(locale: "en-gb"), "[test2]", null));
            Assert.AreEqual("default2", await lg.Generate(GetTurnContext(locale: "en"), "[test2]", null));
            Assert.AreEqual("default2", await lg.Generate(GetTurnContext(locale: string.Empty), "[test2]", null));
            Assert.AreEqual("default2", await lg.Generate(GetTurnContext(locale: "foo"), "[test2]", null));
        }
        public async Task ResourceExplorer_LoadType_VerifyTokenRangeAndIdHonored()
        {
            var          path            = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, PathUtils.NormalizePath(@"..\..\..")));
            const string resourcesFolder = "resources";
            const string resourceId      = "testWithId.dialog";

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

                // Load file using resource explorer
                var resource = explorer.GetResource(resourceId);
                var dialog   = await explorer.LoadTypeAsync <Dialog>(resource).ConfigureAwait(false);

                // Verify correct range
                var expectedRange = new SourceRange
                {
                    StartPoint = new SourcePoint(1, 1),
                    EndPoint   = new SourcePoint(14, 1),
                    Path       = Path.Join(Path.Join(path, resourcesFolder), resourceId)
                };

                Assert.Equal(expectedRange, dialog.Source);

                // Verify that the correct id was set
                Assert.Equal("explicit-id", dialog.Id);
            }
        }
        /// <summary>
        /// Reads the JSON representation of a <see cref="DialogSet"/> object.
        /// </summary>
        /// <param name="reader">The <see cref="Newtonsoft.Json.JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of <see cref="DialogSet"/> being read. If there is no existing value then null will be used.</param>
        /// <param name="hasExistingValue">Indicates if existingValue has a value.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The interpreted <see cref="DialogSet"/> object.</returns>
        public override DialogSet ReadJson(JsonReader reader, Type objectType, DialogSet existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            var jToken = JToken.Load(reader);
            var result = new DialogSet();

            if (jToken is JArray arr)
            {
                foreach (var element in arr)
                {
                    if (element.Type == JTokenType.String)
                    {
                        string dialogName = element.ToObject <string>();
                        var    resourceId = resourceExplorer.GetResource($"{dialogName}.dialog");
                        var    dialog     = resourceExplorer.LoadType <Dialog>(resourceId);
                        result.Add(dialog);
                    }
                    else if (element.Type == JTokenType.Object)
                    {
                        var dialog = element.ToObject <AdaptiveDialog>(serializer);
                        result.Add(dialog);
                    }
                }
            }

            return(result);
        }
        public async Task ResourceExplorer_ReadTokenRangeAdvance_AssignId()
        {
            var          path            = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, PathUtils.NormalizePath(@"..\..\..")));
            var          sourceContext   = new ResourceSourceContext();
            const string resourcesFolder = "resources";
            const string resourceId      = "test.dialog";

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

                // Load file using resource explorer
                var resource = explorer.GetResource(resourceId);

                // Read token range using resource explorer
                var(jToken, range) = await explorer.ReadTokenRangeAsync(resource, sourceContext, true).ConfigureAwait(false);

                // Verify correct range
                var expectedRange = new SourceRange
                {
                    StartPoint = new SourcePoint(1, 1),
                    EndPoint   = new SourcePoint(13, 1),
                    Path       = Path.Join(Path.Join(path, resourcesFolder), resourceId)
                };

                Assert.Equal(expectedRange, range);

                // Verify ID was added
                Assert.Equal(resourceId, sourceContext.DefaultIdMap[jToken]);
            }
        }
        public static async Task ClassInitialize(TestContext context)
        {
            var parent = Environment.CurrentDirectory;

            while (!string.IsNullOrEmpty(parent))
            {
                if (System.IO.Directory.EnumerateFiles(parent, "*proj").Any())
                {
                    break;
                }
                else
                {
                    parent = System.IO.Path.GetDirectoryName(parent);
                }
            }

            ResourceExplorer = new ResourceExplorer();
            ResourceExplorer.AddFolder(parent, monitorChanges: false);

            var resource = ResourceExplorer.GetResource("test-ram.en-us.qna.json");

            Json = await resource.ReadTextAsync();

            IndexDirectory = new RAMDirectory();
            QLuceneEngine.CreateCatalog(Json, IndexDirectory);
        }
Exemplo n.º 10
0
        public async Task TestQLuceneRecognizerCode()
        {
            var resource = ResourceExplorer.GetResource("test-ram.en-us.qna.json");
            var json     = await resource.ReadTextAsync();

            await new TestScript()
            {
                Dialog = new AdaptiveDialog()
                {
                    Recognizer = new QLuceneRecognizer(resource.Id, json),
                    Triggers   = new List <OnCondition>()
                    {
                        new OnIntent()
                        {
                            Intent  = "QnAMatch",
                            Actions = new List <Dialog>()
                            {
                                new SendActivity("${turn.recognized.entities.answer[0]}")
                            }
                        }
                    }
                }
            }
            .Send("Do you have a boyfriend")
            .AssertReply("The only thing I'm committed to is being a great friend.")
            .Send("Who created you?")
            .AssertReply("People made me out of code and a dash of ingenuity.")
            .Send("Do you want to get married ?")
            .AssertReply("Definitely didn't see that coming!")
            .ExecuteAsync(ResourceExplorer);
        }
Exemplo n.º 11
0
        private TestFlow BuildTestFlow(bool sendTrace = false)
        {
            TypeFactory.Configuration = new ConfigurationBuilder().Build();
            var storage    = new MemoryStorage();
            var convoState = new ConversationState(storage);
            var userState  = new UserState(storage);
            var adapter    = new TestAdapter(TestAdapter.CreateConversation(TestContext.TestName), sendTrace);

            adapter
            .UseStorage(storage)
            .UseState(userState, convoState)
            .UseLanguageGeneration(resourceExplorer)
            .UseResourceExplorer(resourceExplorer)
            .Use(new TranscriptLoggerMiddleware(new FileTranscriptLogger()));

            var           resource = resourceExplorer.GetResource("Main.dialog");
            var           dialog   = DeclarativeTypeLoader.Load <IDialog>(resource, resourceExplorer, DebugSupport.SourceRegistry);
            DialogManager dm       = new DialogManager(dialog);

            return(new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                if (dialog is AdaptiveDialog planningDialog)
                {
                    await dm.OnTurnAsync(turnContext, null, cancellationToken).ConfigureAwait(false);
                }
            }));
        }
        private TestFlow BuildTestFlow(string folderPath, bool sendTrace = false)
        {
            var storage          = new MemoryStorage();
            var convoState       = new ConversationState(storage);
            var userState        = new UserState(storage);
            var adapter          = new TestAdapter(TestAdapter.CreateConversation(TestContext.TestName), sendTrace);
            var resourceExplorer = new ResourceExplorer();

            resourceExplorer.AddFolder(folderPath);
            adapter
            .UseStorage(storage)
            .UseState(userState, convoState)
            .Use(new TranscriptLoggerMiddleware(new FileTranscriptLogger()));

            var           resource = resourceExplorer.GetResource("actionssample.dialog");
            var           dialog   = resourceExplorer.LoadType <Dialog>(resource);
            DialogManager dm       = new DialogManager(dialog)
                                     .UseResourceExplorer(resourceExplorer)
                                     .UseLanguageGeneration();;

            return(new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                if (dialog is AdaptiveDialog planningDialog)
                {
                    await dm.OnTurnAsync(turnContext, cancellationToken).ConfigureAwait(false);
                }
            }));
        }
Exemplo n.º 13
0
        public async Task TestMultiLangImport()
        {
            // use LG file as entrance
            var lgResourceGroup = LGResourceLoader.GroupByLocale(resourceExplorer);

            var resource  = resourceExplorer.GetResource("a.en-US.lg") as FileResource;
            var generator = new TemplateEngineLanguageGenerator(resource.FullName, lgResourceGroup);
            var result    = await generator.Generate(GetTurnContext(), "@{templatea()}", null);

            Assert.AreEqual("from a.en-us.lg", result);

            // import b.en-us.lg
            result = await generator.Generate(GetTurnContext(), "@{templateb()}", null);

            Assert.AreEqual("from b.en-us.lg", result);

            // fallback to c.en.lg
            result = await generator.Generate(GetTurnContext(), "@{templatec()}", null);

            Assert.AreEqual("from c.en.lg", result);

            // there is no 'greeting' template in b.en-us.lg, no more fallback to b.lg
            var ex = await Assert.ThrowsExceptionAsync <Exception>(async() => await generator.Generate(GetTurnContext(), "@{greeting()}", null));

            Assert.IsTrue(ex.Message.Contains("greeting does not have an evaluator"));

            resource  = resourceExplorer.GetResource("a.lg") as FileResource;
            generator = new TemplateEngineLanguageGenerator(resource.FullName, lgResourceGroup);

            result = await generator.Generate(GetTurnContext(), "@{templatea()}", null);

            Assert.AreEqual("from a.lg", result);

            result = await generator.Generate(GetTurnContext(), "@{templateb()}", null);

            Assert.AreEqual("from b.lg", result);

            // ignore the "en" in c.en.lg, just load c.lg
            result = await generator.Generate(GetTurnContext(), "@{templatec()}", null);

            Assert.AreEqual("from c.lg", result);

            result = await generator.Generate(GetTurnContext(), "@{greeting()}", null);

            Assert.AreEqual("hi", result);
        }
Exemplo n.º 14
0
        private async Task <ITurnContext> GetTurnContext(string lgFile)
        {
            var context = new TurnContext(new TestAdapter(), new Activity());
            var lgText  = await resourceExplorer.GetResource(lgFile).ReadTextAsync();

            context.TurnState.Add <ILanguageGenerator>(new TemplateEngineLanguageGenerator(lgText, "test", MultiLanguageResourceLoader.Load(resourceExplorer)));
            return(context);
        }
Exemplo n.º 15
0
        public RootDialog(UserState userState, ResourceExplorer resourceExplorer)
            : base("root")
        {
            _userStateAccessor = userState.CreateProperty <JObject>("result");

            // Rather than explicitly coding a Waterfall we have only to declare what properties we want collected.
            // In this example we will want two text prompts to run, one for the first name and one for the last.
            var fullname_slots = new List <SlotDetails>
            {
                new SlotDetails("first", "text", "Please enter your first name."),
                new SlotDetails("last", "text", "Please enter your last name."),
            };

            // This defines an address dialog that collects street, city and zip properties.
            var address_slots = new List <SlotDetails>
            {
                new SlotDetails("street", "text", "Please enter the street."),
                new SlotDetails("city", "text", "Please enter the city."),
                new SlotDetails("zip", "text", "Please enter the zip."),
            };

            // Dialogs can be nested and the slot filling dialog makes use of that. In this example some of the child
            // dialogs are slot filling dialogs themselves.
            var slots = new List <SlotDetails>
            {
                new SlotDetails("address", "address"),
            };

            // Add the various dialogs that will be used to the DialogSet.
            AddDialog(new SlotFillingDialog("address", address_slots));
            AddDialog(new SlotFillingDialog("fullname", fullname_slots));
            AddDialog(new TextPrompt("text"));
            AddDialog(new NumberPrompt <int>("number", defaultLocale: Culture.English));
            AddDialog(new NumberPrompt <float>("shoesize", ShoeSizeAsync, defaultLocale: Culture.English));
            AddDialog(new SlotFillingDialog("slot-dialog", slots));

            // Defines a simple two step Waterfall to test the slot dialog.
            AddDialog(new WaterfallDialog(
                          "waterfall",
                          new WaterfallStep[]
            {
                StartDialogAsync,
                DoComposerDialogAsync,
                DoSlotDialogAsync,
                ProcessResultsAsync
            }));

            // Load and add adaptive dialog produced by composer.
            // Name of the dialog (.dialog file name) to find
            var dialogResource = resourceExplorer.GetResource("main-without-luis.dialog");
            var composerDialog = resourceExplorer.LoadType <AdaptiveDialog>(dialogResource);

            // Add the dialog
            AddDialog(composerDialog);

            // The initial child Dialog to run.
            InitialDialogId = "waterfall";
        }
Exemplo n.º 16
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");
        }
        private void LoadRootDialogAsync()
        {
            var rootFile   = resourceExplorer.GetResource(rootDialogFile);
            var rootDialog = resourceExplorer.LoadType <Dialog>(rootFile);

            this.dialogManager = new DialogManager(rootDialog)
                                 .UseResourceExplorer(resourceExplorer)
                                 .UseLanguageGeneration();
        }
        private async Task <ITurnContext> GetTurnContext(string lgFile)
        {
            var context    = new TurnContext(new TestAdapter(), new Activity());
            var lgresource = resourceExplorer.GetResource(lgFile) as FileResource;

            context.TurnState.Add <ILanguageGenerator>(new TemplateEngineLanguageGenerator(lgresource.FullName, MultiLanguageResourceLoader.Load(resourceExplorer)));

            return(context);
        }
Exemplo n.º 19
0
        public async Task <JToken> ResolveAsync(JToken refToken)
        {
            var refTarget = GetRefTarget(refToken);

            if (string.IsNullOrEmpty(refTarget))
            {
                throw new InvalidOperationException("Failed to resolve reference, $copy property not present");
            }

            var resource = resourceExplorer.GetResource($"{refTarget}.dialog");

            if (resource == null)
            {
                throw new FileNotFoundException($"Failed to find resource named {refTarget}.dialog");
            }

            string text = await resource.ReadTextAsync().ConfigureAwait(false);

            var json = JToken.Parse(text);

            foreach (JProperty prop in refToken.Children <JProperty>())
            {
                if (prop.Name != "$ref")
                {
                    // JToken is an object, so we merge objects
                    if (json[prop.Name] != null && json[prop.Name].Type == JTokenType.Object)
                    {
                        JObject targetProperty = json[prop.Name] as JObject;
                        targetProperty.Merge(prop.Value);
                    }

                    // JToken is an object, so we merge objects
                    else if (json[prop.Name] != null && json[prop.Name].Type == JTokenType.Array)
                    {
                        JArray targetArray = json[prop.Name] as JArray;
                        targetArray.Merge(prop.Value);
                    }

                    // JToken is a value, simply assign
                    else
                    {
                        json[prop.Name] = prop.Value;
                    }
                }
            }

            // if we have a source path for the resource, then make it available to InterfaceConverter
            if (resource is FileResource fileResource)
            {
                sourceMap.Add(json, new SourceRange()
                {
                    Path = fileResource.FullName
                });
            }

            return(json);
        }
        public static ImportResolverDelegate ResourceResolver(ResourceExplorer resourceExplorer) =>
        (string source, string id) =>
        {
            var resourceName = Path.GetFileName(PathUtils.NormalizePath(id));
            var res          = resourceExplorer.GetResource(resourceName);

            var content = res?.ReadTextAsync().GetAwaiter().GetResult();

            return(content, resourceName);
        };
Exemplo n.º 21
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");
        }
Exemplo n.º 22
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);
        }
Exemplo n.º 23
0
        private void LoadRootDialogAsync()
        {
            var rootFile   = resourceExplorer.GetResource(rootDialogFile);
            var rootDialog = resourceExplorer.LoadType <AdaptiveDialog>(rootFile);

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

            if (telemetryClient != null)
            {
                dialogManager.UseTelemetry(this.telemetryClient);
            }
        }
Exemplo n.º 24
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");
        }
Exemplo n.º 25
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");
        }
Exemplo n.º 26
0
        public async Task ResourceExplorer_LoadType_VerifyAdaptiveDialogIdAssigned()
        {
            var          path       = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, PathUtils.NormalizePath(@"..\..\..")));
            const string resourceId = "test.dialog";

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

                // Load file using resource explorer
                var resource = explorer.GetResource(resourceId);
                var dialog   = await explorer.LoadTypeAsync <AdaptiveDialog>(resource).ConfigureAwait(false);

                // Verify that the correct id was assigned
                Assert.Equal(resourceId, dialog.Id);
            }
        }
        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"));
        }
Exemplo n.º 28
0
        public void TestMissingResourceThrows()
        {
            var path = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, PathUtils.NormalizePath(@"..\..\..")));

            using (var explorer = new ResourceExplorer())
            {
                explorer.AddResourceProvider(new FolderResourceProvider(explorer, path));
                try
                {
                    explorer.GetResource("bogus.dialog");
                    throw new XunitException("should have thrown exception");
                }
                catch (ArgumentException err)
                {
                    Assert.Contains("bogus", err.Message);
                    Assert.Equal("bogus.dialog", err.ParamName);
                }
                catch (Exception err2)
                {
                    throw new XunitException($"Unknown exception {err2.GetType().Name} thrown");
                }
            }
        }
Exemplo n.º 29
0
        public RootDialog(UserState userState) : base("root")
        {
            _userState = userState;

            // Get Folder of dialogs.
            var resourceExplorer = new ResourceExplorer().AddFolder(@"Dialogs");

            // find the main composer dialog to start with
            var composerDialog = resourceExplorer.GetResource("Main.dialog");

            // hyrdate an Adaptive Dialogue
            AdaptiveDialog myComposerDialog = DeclarativeTypeLoader.Load <AdaptiveDialog>(composerDialog, resourceExplorer, DebugSupport.SourceMap);

            myComposerDialog.Id = "Main.dialog";

            // setup lanaguage generation for the dialogue
            myComposerDialog.Generator = new TemplateEngineLanguageGenerator(new TemplateEngine().AddFile(@"Dialogs\ComposerDialogs\Main\Main.lg"));

            // add to the ComponentDialog which Root dialogue inherits from
            AddDialog(myComposerDialog);

            // create a waterfall dialogue and begin our adaptive dialogue
            AddDialog(new WaterfallDialog("waterfall", new WaterfallStep[] { BeginComposerAdaptiveDialog }));
        }
        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);
        }