示例#1
0
    public AdapterWithErrorHandler(IConfiguration configuration,
                                   ILogger <BotFrameworkHttpAdapter> logger,
                                   ResourceExplorer resourceExplorer,
                                   ConversationState conversationState = null,
                                   UserState userState = null) : base(configuration, logger)
    {
        this.Use(new RegisterClassMiddleware <IConfiguration>(configuration));
        this.UseResourceExplorer(resourceExplorer);
        this.UseAdaptiveDialogs();
        this.UseLanguageGeneration(resourceExplorer);
        this.UseState(userState, conversationState);

        OnTurnError = async(turnContext, exception) =>
        {
            // Log any leaked exception from the application.
            logger.LogError(exception, $"[OnTurnError] unhandled error : {exception.Message}");

            // Send a message to the user
            await turnContext.SendActivityAsync("The bot encountered an error or bug.");

            await turnContext.SendActivityAsync("To continue to run this bot, please fix the bot source code.");

            if (conversationState != null)
            {
                try
                {
                    // Delete the conversationState for the current conversation to prevent the
                    // bot from getting stuck in a error-loop caused by being in a bad state.
                    // ConversationState should be thought of as similar to "cookie-state" in a Web pages.
                    await conversationState.DeleteAsync(turnContext);
                }
                catch (Exception e)
                {
                    logger.LogError(e, $"Exception caught on attempting to Delete ConversationState : {e.Message}");
                }
            }

            // Send a trace activity, which will be displayed in the Bot Framework Emulator
            await turnContext.TraceActivityAsync("OnTurnError Trace", exception.Message, "https://www.botframework.com/schemas/error", "TurnError");
        };
    }
示例#2
0
        public TestBotHttpAdapter(
            ICredentialProvider credentialProvider,
            IConfiguration configuration,
            ILogger <BotFrameworkHttpAdapter> logger,
            IStorage storage,
            UserState userState,
            ConversationState conversationState,
            ResourceExplorer resourceExplorer)
            : base(configuration, credentialProvider)
        {
            this.Use(new RegisterClassMiddleware <IConfiguration>(configuration));
            this.UseStorage(storage);
            this.UseBotState(userState, conversationState);
            this.UseDebugger(configuration.GetValue("debugport", 4712), logger: logger);

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

                // Send a catch-all apology to the user.
                await turnContext.SendActivityAsync("Sorry, it looks like something went wrong.");

                await turnContext.SendActivityAsync(exception.Message).ConfigureAwait(false);

                if (conversationState != null)
                {
                    try
                    {
                        // Delete the conversationState for the current conversation to prevent the
                        // bot from getting stuck in a error-loop caused by being in a bad state.
                        // ConversationState should be thought of as similar to "cookie-state" in a Web pages.
                        await conversationState.DeleteAsync(turnContext).ConfigureAwait(false);
                    }
                    catch (Exception e)
                    {
                        logger.LogError($"Exception caught on attempting to Delete ConversationState : {e.Message}");
                    }
                }
            };
        }
        public static async Task <T> LoadAsync <T>(IResource resource, ResourceExplorer resourceExplorer, ISourceMap sourceMap)
        {
            IRefResolver refResolver = new IdRefResolver(resourceExplorer, sourceMap);

            string id    = resource.Id;
            var    paths = new Stack <string>();

            if (resource is FileResource fileResource)
            {
                id = fileResource.FullName;
                paths.Push(fileResource.FullName);
            }

            string json = null;

            try
            {
                json = await resource.ReadTextAsync();

                var result = Load <T>(sourceMap, refResolver, paths, json);
                if (result is Dialog dlg)
                {
                    // dialog id's are resource ids
                    dlg.Id = resource.Id;
                }

                return(result);
            }
            catch (Exception err)
            {
                if (err.InnerException is SyntaxErrorException)
                {
                    throw new SyntaxErrorException(err.InnerException.Message)
                          {
                              Source = $"{id}{err.InnerException.Source}"
                          };
                }

                throw new Exception($"{id} error: {err.Message}\n{err.InnerException?.Message}");
            }
        }
示例#4
0
        public async Task TestFolderSource_WriteFiresChanged()
        {
            const string testId         = "WriteFiresChanged.dialog";
            var          testDialogFile = Path.Combine(Environment.CurrentDirectory, testId);

            File.Delete(testDialogFile);
            var contents = "{}";

            File.WriteAllText(testDialogFile, contents);

            var path = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, PathUtils.NormalizePath(@"..\..\..")));

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

                AssertResourceFound(explorer, testId);

                await AssertResourceContents(explorer, testId, contents);

                var changeFired = new TaskCompletionSource <bool>();

                explorer.Changed += (e, resources) =>
                {
                    if (resources.Any(res => res.Id == testId))
                    {
                        changeFired.SetResult(true);
                    }
                };

                // changed file
                contents = "{'foo':123 }";
                File.WriteAllText(testDialogFile, contents);

                await Task.WhenAny(changeFired.Task, Task.Delay(5000)).ConfigureAwait(false);

                AssertResourceFound(explorer, testId);

                await AssertResourceContents(explorer, testId, contents);
            }
        }
        /// <summary>
        /// Starts the execution of the test sequence.
        /// </summary>
        /// <remarks>This methods sends the activities from the user to the bot and
        /// checks the responses from the bot based on the TestActions.</remarks>
        /// <param name="testName">testName.</param>
        /// <param name="resourceExplorer">resource explorer.</param>
        /// <param name="callback">bot logic.</param>
        /// <param name="adapter">optional test adapter.</param>
        /// <param name="configuration">configuration.</param>
        /// <returns>Runs the exchange between the user and the bot.</returns>
        public async Task ExecuteAsync([CallerMemberName] string testName = null, ResourceExplorer resourceExplorer = null, BotCallbackHandler callback = null, TestAdapter adapter = null, IConfiguration configuration = null)
        {
            if (resourceExplorer == null)
            {
                resourceExplorer = new ResourceExplorer()
                                   .AddFolder(GetProjectPath());
            }

            if (adapter == null)
            {
                TypeFactory.Configuration = configuration ?? new ConfigurationBuilder().Build();
                var storage    = new MemoryStorage();
                var convoState = new ConversationState(storage);
                var userState  = new UserState(storage);
                adapter = (TestAdapter) new TestAdapter(TestAdapter.CreateConversation(testName))
                          .Use(new RegisterClassMiddleware <IConfiguration>(TypeFactory.Configuration))
                          .UseStorage(storage)
                          .UseState(userState, convoState)
                          .UseResourceExplorer(resourceExplorer)
                          .UseAdaptiveDialogs()
                          .UseLanguageGeneration(resourceExplorer)
                          .Use(new TranscriptLoggerMiddleware(new FileTranscriptLogger()));
            }

            adapter.EnableTrace = this.EnableTrace;
            adapter.Locale      = this.Locale;

            DialogManager dm = new DialogManager(this.Dialog);

            foreach (var testAction in this.Script)
            {
                if (callback != null)
                {
                    await testAction.ExecuteAsync(adapter, callback).ConfigureAwait(false);
                }
                else
                {
                    await testAction.ExecuteAsync(adapter, dm.OnTurnAsync).ConfigureAwait(false);
                }
            }
        }
        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"));
        }
        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();
        }
示例#9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            // Register dialog. This sets up memory paths for adaptive.
            ComponentRegistration.Add(new DialogsComponentRegistration());

            // Register adaptive component
            ComponentRegistration.Add(new AdaptiveComponentRegistration());

            // Register to use language generation.
            ComponentRegistration.Add(new LanguageGenerationComponentRegistration());

            // Register declarative components for adaptive dialogs.
            ComponentRegistration.Add(new DeclarativeComponentRegistration());

            ComponentRegistration.Add(new OrchestratorComponentRegistration());

            // Create the credential provider to be used with the Bot Framework Adapter.
            services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>();

            // Create the Bot Framework Adapter with error handling enabled.
            services.AddSingleton <IBotFrameworkHttpAdapter, DeclarativeBotAdapter>();

            // Create the storage we'll be using for User and Conversation state. (Memory is great for testing purposes.)
            services.AddSingleton <IStorage, MemoryStorage>();

            // Create the User state. (Used in this bot's Dialog implementation.)
            services.AddSingleton <UserState>();

            // Create the Conversation state. (Used by the Dialog system itself.)
            services.AddSingleton <ConversationState>();

            var resourceExplorer = new ResourceExplorer().LoadProject(this.HostingEnvironment.ContentRootPath);

            services.AddSingleton(resourceExplorer);

            // Create the bot  In this case the ASP Controller is expecting an IBot.
            services.AddSingleton <IBot, DeclarativeBot>();
        }
        public virtual IEnumerable <DeclarativeType> GetDeclarativeTypes(ResourceExplorer resourceExplorer)
        {
            // Conditionals
            yield return(new DeclarativeType <OnTeamsAppBasedLinkQuery>(OnTeamsAppBasedLinkQuery.Kind));

            yield return(new DeclarativeType <OnTeamsCardAction>(OnTeamsCardAction.Kind));

            yield return(new DeclarativeType <OnTeamsChannelCreated>(OnTeamsChannelCreated.Kind));

            yield return(new DeclarativeType <OnTeamsChannelDeleted>(OnTeamsChannelDeleted.Kind));

            yield return(new DeclarativeType <OnTeamsChannelRenamed>(OnTeamsChannelRenamed.Kind));

            yield return(new DeclarativeType <OnTeamsFileConsent>(OnTeamsFileConsent.Kind));

            yield return(new DeclarativeType <OnTeamsMessagingExtensionCardButtonClicked>(OnTeamsMessagingExtensionCardButtonClicked.Kind));

            yield return(new DeclarativeType <OnTeamsMessagingExtensionConfigurationQuerySettingUrl>(OnTeamsMessagingExtensionConfigurationQuerySettingUrl.Kind));

            yield return(new DeclarativeType <OnTeamsMessagingExtensionConfigurationSetting>(OnTeamsMessagingExtensionConfigurationSetting.Kind));

            yield return(new DeclarativeType <OnTeamsMessagingExtensionFetchTask>(OnTeamsMessagingExtensionFetchTask.Kind));

            yield return(new DeclarativeType <OnTeamsMessagingExtensionQuery>(OnTeamsMessagingExtensionQuery.Kind));

            yield return(new DeclarativeType <OnTeamsMessagingExtensionSelectItem>(OnTeamsMessagingExtensionSelectItem.Kind));

            yield return(new DeclarativeType <OnTeamsMessagingExtensionSubmitAction>(OnTeamsMessagingExtensionSubmitAction.Kind));

            yield return(new DeclarativeType <OnTeamsO365ConnectorCardAction>(OnTeamsO365ConnectorCardAction.Kind));

            yield return(new DeclarativeType <OnTeamsTaskModuleFetch>(OnTeamsTaskModuleFetch.Kind));

            yield return(new DeclarativeType <OnTeamsTaskModuleSubmit>(OnTeamsTaskModuleSubmit.Kind));

            yield return(new DeclarativeType <OnTeamsTeamRenamed>(OnTeamsTeamRenamed.Kind));

            yield break;
        }
示例#11
0
        private TestFlow CreateFlow(string locale, Dialog dialog)
        {
            TypeFactory.Configuration = this.Configuration;

            var resourceExplorer = new ResourceExplorer();

            var adapter = new TestAdapter(TestAdapter.CreateConversation(TestContext.TestName))
                          .Use(new RegisterClassMiddleware <ResourceExplorer>(resourceExplorer))
                          .Use(new RegisterClassMiddleware <IStorage>(new MemoryStorage()))
                          .UseAdaptiveDialogs()
                          .UseLanguageGeneration(resourceExplorer)
                          .Use(new RegisterClassMiddleware <IConfiguration>(this.Configuration))
                          .UseState(new UserState(new MemoryStorage()), new ConversationState(new MemoryStorage()))
                          .Use(new TranscriptLoggerMiddleware(new FileTranscriptLogger()));

            DialogManager dm = new DialogManager(dialog);

            return(new TestFlow((TestAdapter)adapter, async(turnContext, cancellationToken) =>
            {
                await dm.OnTurnAsync(turnContext, cancellationToken: cancellationToken).ConfigureAwait(false);
            }));
        }
        public async Task TestLocaleInExpression()
        {
            var           resourceExplorer = new ResourceExplorer().LoadProject(GetProjectFolder(), monitorChanges: false);
            DialogManager dm = new DialogManager()
                               .UseResourceExplorer(resourceExplorer)
                               .UseLanguageGeneration("test.lg");

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

            await CreateFlow(
                async (turnContext, cancellationToken) =>
            {
                await dm.OnTurnAsync(turnContext, cancellationToken: cancellationToken).ConfigureAwait(false);
            },
                locale : "de-DE")
            .Send("hola")
            .AssertReply("1,122")
            .AssertReply("1,1235")
            .AssertReply("Samstag, 6. Januar 2018")
            .AssertReply("3,14159")
            .StartTestAsync();
        }
示例#13
0
        private void CreateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                ToolStripMenuItem item = sender as ToolStripMenuItem;
                if (item == null)
                {
                    return;
                }
                switch (item.Text)
                {
                case "Description":
                    try
                    {
                        var Subform = new NewDescriptionForm();
                        if (Subform.ShowDialog(this) != DialogResult.OK)
                        {
                            return;
                        }
                        Description.Create(Subform.Root, Subform.Name);
                        OpenDescription(Path.Combine(Subform.Root, Subform.Name, Subform.Name + "." + Description.Extension));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.ToString(), "Can not create description.",
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;

                default: ResourceExplorer.CreateResource(Resource.StringToType(item.Text)); break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.ToString(), "Error: Can not create resource.",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
示例#14
0
        public AdapterWithErrorHandler(ICredentialProvider credentialProvider, ILogger <BotFrameworkHttpAdapter> logger, ConversationState conversationState = null)
            : base(credentialProvider)
        {
            // manage all bot resources
            var resourceExplorer = ResourceExplorer
                                   .LoadProject(Directory.GetCurrentDirectory(), ignoreFolders: new string[] { "models" });

            //resourceExplorer.AddFolder(luisModelsFolder);

            var lg = new LGLanguageGenerator(resourceExplorer);

            Use(new RegisterClassMiddleware <ILanguageGenerator>(lg));
            Use(new RegisterClassMiddleware <IMessageActivityGenerator>(new TextMessageActivityGenerator(lg)));

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

                // Send a catch-all apology to the user.
                await turnContext.SendActivityAsync("Sorry, it looks like something went wrong.");

                if (conversationState != null)
                {
                    try
                    {
                        // Delete the conversationState for the current conversation to prevent the
                        // bot from getting stuck in a error-loop caused by being in a bad state.
                        // ConversationState should be thought of as similar to "cookie-state" in a Web pages.
                        await conversationState.DeleteAsync(turnContext);
                    }
                    catch (Exception e)
                    {
                        logger.LogError($"Exception caught on attempting to Delete ConversationState : {e.Message}");
                    }
                }
            };
        }
        /// <inheritdoc/>
        public virtual IEnumerable <DeclarativeType> GetDeclarativeTypes(ResourceExplorer resourceExplorer)
        {
            // Actions for within normal bot flow
            yield return(new DeclarativeType <AssertCondition>(AssertCondition.Kind));

            // Test script actions
            yield return(new DeclarativeType <TestScript>(TestScript.Kind));

            yield return(new DeclarativeType <UserSays>(UserSays.Kind));

            yield return(new DeclarativeType <UserTyping>(UserTyping.Kind));

            yield return(new DeclarativeType <UserConversationUpdate>(UserConversationUpdate.Kind));

            yield return(new DeclarativeType <UserActivity>(UserActivity.Kind));

            yield return(new DeclarativeType <UserDelay>(UserDelay.Kind));

            yield return(new DeclarativeType <AssertReply>(AssertReply.Kind));

            yield return(new DeclarativeType <AssertReplyOneOf>(AssertReplyOneOf.Kind));

            yield return(new DeclarativeType <AssertReplyActivity>(AssertReplyActivity.Kind));

            yield return(new DeclarativeType <AssertNoActivity>(AssertNoActivity.Kind));

            yield return(new DeclarativeType <MemoryAssertions>(MemoryAssertions.Kind));

            yield return(new DeclarativeType <HttpRequestSequenceMock>(HttpRequestSequenceMock.Kind));

            yield return(new DeclarativeType <UserTokenBasicMock>(UserTokenBasicMock.Kind));

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

            yield return(new DeclarativeType <SettingStringMock>(SettingStringMock.Kind));

            yield return(new DeclarativeType <CustomEvent>(CustomEvent.Kind));
        }
示例#16
0
        public async Task TestNoResourceExplorerLanguageGeneration()
        {
            var           resourceExplorer = new ResourceExplorer().LoadProject(GetProjectFolder(), monitorChanges: false);
            DialogManager dm = new DialogManager()
                               .UseResourceExplorer(resourceExplorer)
                               .UseLanguageGeneration();

            await CreateNoResourceExplorerFlow(async (turnContext, cancellationToken) =>
            {
                var lg     = dm.TurnState.Get <ILanguageGenerator>();
                var result = await lg.Generate(turnContext, "This is ${test.name}", new
                {
                    test = new
                    {
                        name = "Tom"
                    }
                });
                await turnContext.SendActivityAsync(result);
            })
            .Send("hello")
            .AssertReply("This is Tom")
            .StartTestAsync();
        }
示例#17
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");
                }
            }
        }
示例#18
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
            });
        }
示例#19
0
        public async Task TestLanguageGeneratorMiddleware()
        {
            var resourceExplorer = new ResourceExplorer().LoadProject(GetProjectFolder(), monitorChanges: false);
            var dm = new DialogManager()
                     .UseResourceExplorer(resourceExplorer)
                     .UseLanguageGeneration("test.lg");

            await CreateFlow(async (turnContext, cancellationToken) =>
            {
                foreach (var pair in dm.TurnState)
                {
                    turnContext.TurnState.Set(pair.Key, pair.Value);
                }

                var lg = turnContext.TurnState.Get <ILanguageGenerator>();
                Assert.IsNotNull(lg, "ILanguageGenerator should not be null");
                Assert.IsNotNull(turnContext.TurnState.Get <ResourceExplorer>(), "ResourceExplorer should not be null");
                var text = await lg.Generate(turnContext, "${test()}", null);
                Assert.AreEqual("english-us", text, "template should be there");
            })
            .Send("hello")
            .StartTestAsync();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

            // Create the credential provider to be used with the Bot Framework Adapter.
            services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>();

            // Create the Bot Framework Adapter with error handling enabled.
            services.AddSingleton <IBotFrameworkHttpAdapter, AdaptiveBotAdapter>();

            // Create the storage we'll be using for User and Conversation state. (Memory is great for testing purposes.)
            services.AddSingleton <IStorage, MemoryStorage>();

            // Create the User state. (Used in this bot's Dialog implementation.)
            services.AddSingleton <UserState>();

            // Create the Conversation state. (Used by the Dialog system itself.)
            services.AddSingleton <ConversationState>();

            var resourceExplorer = ResourceExplorer.LoadProject(this.HostingEnvironment.ContentRootPath);

            services.AddSingleton(resourceExplorer);

            // Create the bot  In this case the ASP Controller is expecting an IBot.
            services.AddSingleton <IBot, AdaptiveBot>();

            // Add this so settings memory scope is populated correctly.
            services.AddSingleton <IConfiguration>(this.Configuration);

            //services.AddSingleton<IAlexaHttpAdapter>(new AlexaHttpAdapter(false));
            services.Configure <KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });
        }
        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);
        }
示例#22
0
        public RootDialog(UserState userState) : base("root")
        {
            _userState = userState;

            AddDialog(new UserProfileDialog(userState));
            AddDialog(new LocationDialog());

            // 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-and-adaptive\SharingState\Dialogs\ComposerDialogs\Main\Main.lg"));
            // add to the ComponentDialog which Root dialogue inherits from
            AddDialog(myComposerDialog);

            var composerLocationDialog = resourceExplorer.GetResource("ProcessLocation.dialog");
            // hyrdate an Adaptive Dialogue
            AdaptiveDialog myComposerLocationDialog = DeclarativeTypeLoader.Load <AdaptiveDialog>(composerLocationDialog, resourceExplorer, DebugSupport.SourceMap);

            myComposerLocationDialog.Id = "ProcessLocation.dialog";
            // setup lanaguage generation for the dialogue
            myComposerLocationDialog.Generator = new TemplateEngineLanguageGenerator(new TemplateEngine().AddFile(@"C:\Users\Jamie\source\repos\composer-and-adaptive\SharingState\Dialogs\ComposerDialogs\ProcessLocation\ProcessLocation.lg"));
            // add to the ComponentDialog which Root dialogue inherits from
            AddDialog(myComposerLocationDialog);

            AddDialog(new WaterfallDialog("waterfall", new WaterfallStep[] { StartDialogAsync, BeginComposerAdaptiveDialog, BeginComposerLocationAdaptiveDialog, ReadLocationFromComposerDialog }));
        }
        public virtual IEnumerable <DeclarativeType> GetDeclarativeTypes(ResourceExplorer resourceExplorer)
        {
            // Action
            yield return(new DeclarativeType <AssertCondition>(AssertCondition.Kind));

            // test actions
            yield return(new DeclarativeType <TestScript>(TestScript.Kind));

            yield return(new DeclarativeType <UserSays>(UserSays.Kind));

            yield return(new DeclarativeType <UserTyping>(UserTyping.Kind));

            yield return(new DeclarativeType <UserConversationUpdate>(UserConversationUpdate.Kind));

            yield return(new DeclarativeType <UserActivity>(UserActivity.Kind));

            yield return(new DeclarativeType <UserDelay>(UserDelay.Kind));

            yield return(new DeclarativeType <AssertReply>(AssertReply.Kind));

            yield return(new DeclarativeType <AssertReplyOneOf>(AssertReplyOneOf.Kind));

            yield return(new DeclarativeType <AssertReplyActivity>(AssertReplyActivity.Kind));
        }
示例#24
0
        private TestFlow CreateFlow(AdaptiveDialog dialog, bool sendTrace = false)
        {
            TypeFactory.Configuration = new ConfigurationBuilder().Build();
            var resourceExplorer = new ResourceExplorer();
            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)
            .UseResourceExplorer(resourceExplorer)
            .UseLanguageGeneration(resourceExplorer)
            .UseAdaptiveDialogs()
            .Use(new TranscriptLoggerMiddleware(new FileTranscriptLogger()));

            DialogManager dm = new DialogManager(dialog);

            return(new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                await dm.OnTurnAsync(turnContext, cancellationToken: cancellationToken).ConfigureAwait(false);
            }));
        }
        private TestFlow CreateFlow(string locale)
        {
            var convoState = new ConversationState(new MemoryStorage());
            var userState  = new UserState(new MemoryStorage());
            var dialog     = new AdaptiveDialog();

            dialog.Triggers.AddRange(new List <OnCondition>()
            {
                new OnUnknownIntent(actions:
                                    new List <Dialog>()
                {
                    new SendActivity()
                    {
                        Activity = new ActivityTemplate("{settings.ApplicationInsights.InstrumentationKey}")
                    },
                }),
            });

            var resourceExplorer = new ResourceExplorer();

            var adapter = new TestAdapter(TestAdapter.CreateConversation(TestContext.TestName))
                          .Use(new RegisterClassMiddleware <ResourceExplorer>(resourceExplorer))
                          .Use(new RegisterClassMiddleware <IStorage>(new MemoryStorage()))
                          .UseAdaptiveDialogs()
                          .UseLanguageGeneration(resourceExplorer)
                          .Use(new RegisterClassMiddleware <IConfiguration>(this.Configuration))
                          .Use(new AutoSaveStateMiddleware(convoState, userState))
                          .Use(new TranscriptLoggerMiddleware(new FileTranscriptLogger()));

            DialogManager dm = new DialogManager(dialog);

            return(new TestFlow((TestAdapter)adapter, async(turnContext, cancellationToken) =>
            {
                await dm.OnTurnAsync(turnContext, cancellationToken: cancellationToken).ConfigureAwait(false);
            }));
        }
示例#26
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 }));
        }
示例#27
0
        /// <summary>
        /// Starts the execution of the test sequence.
        /// </summary>
        /// <remarks>This methods sends the activities from the user to the bot and
        /// checks the responses from the bot based on the TestActions.</remarks>
        /// <param name="resourceExplorer">The resource explorer to use.</param>
        /// <param name="testName">Name of the test.</param>
        /// <param name="callback">The bot logic.</param>
        /// <param name="adapter">optional test adapter.</param>
        /// <returns>Runs the exchange between the user and the bot.</returns>
        public async Task ExecuteAsync(ResourceExplorer resourceExplorer, [CallerMemberName] string testName = null, BotCallbackHandler callback = null, TestAdapter adapter = null)
        {
            if (adapter == null)
            {
                adapter = DefaultTestAdapter(resourceExplorer, testName);
            }

            adapter.EnableTrace = this.EnableTrace;
            adapter.Locale      = this.Locale;
            adapter.Use(new MockHttpRequestMiddleware(HttpRequestMocks));
            adapter.Use(new MockSettingsMiddleware(PropertyMocks));

            foreach (var userToken in UserTokenMocks)
            {
                userToken.Setup(adapter);
            }

            if (callback != null)
            {
                foreach (var testAction in this.Script)
                {
                    await testAction.ExecuteAsync(adapter, callback).ConfigureAwait(false);
                }
            }
            else
            {
                var dm = new DialogManager(WrapDialogForPropertyMocks(this.Dialog))
                         .UseResourceExplorer(resourceExplorer)
                         .UseLanguageGeneration();

                foreach (var testAction in this.Script)
                {
                    await testAction.ExecuteAsync(adapter, dm.OnTurnAsync).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);
        }
示例#29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddNewtonsoftJson();

            // Create the credential provider to be used with the Bot Framework Adapter.
            services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>();

            // Register AuthConfiguration to enable custom claim validation.
            services.AddSingleton <AuthenticationConfiguration>();

            // Create the Bot Framework Adapter with error handling enabled.
            // Note: some classes use the base BotAdapter so we add an extra registration that pulls the same instance.
            services.AddSingleton <IBotFrameworkHttpAdapter, TestBotHttpAdapter>();
            services.AddSingleton <BotAdapter>(sp => (BotFrameworkHttpAdapter)sp.GetService <IBotFrameworkHttpAdapter>());

            // Create the storage we'll be using for User and Conversation state. (Memory is great for testing purposes.)
            services.AddSingleton <IStorage, MemoryStorage>();

            // Create the User state. (Used in this bot's Dialog implementation.)
            services.AddSingleton <UserState>();

            // Create the Conversation state. (Used by the Dialog system itself.)
            services.AddSingleton <ConversationState>();

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

            var resourceExplorer = new ResourceExplorer().AddFolder(this.Configuration.GetValue <string>("BotRoot"));

            services.AddSingleton(resourceExplorer);

            // Create the bot  In this case the ASP Controller is expecting an IBot.
            services.AddSingleton <IBot, RunBot>();
        }
示例#30
0
 public static void ClassInitialize(TestContext context)
 {
     ResourceExplorer = new ResourceExplorer()
                        .AddFolder(Path.Combine(TestUtils.GetProjectPath(), "Tests", nameof(RecognizerSetTests)), monitorChanges: false);
 }