コード例 #1
0
        public async Task State_RememberPocoPrivateConversationState()
        {
            var privateConversationState = new PrivateConversationState(new MemoryStorage());
            var testPocoProperty         = privateConversationState.CreateProperty <TestPocoState>("testPoco");
            var adapter = new TestAdapter()
                          .Use(new AutoSaveStateMiddleware(privateConversationState));

            await new TestFlow(adapter,
                               async(context, cancellationToken) =>
            {
                var conversationState = await testPocoProperty.GetAsync(context, () => new TestPocoState());
                Assert.IsNotNull(conversationState, "state.conversation should exist");
                switch (context.Activity.AsMessageActivity().Text)
                {
                case "set value":
                    conversationState.Value = "test";
                    await context.SendActivityAsync("value saved");
                    break;

                case "get value":
                    await context.SendActivityAsync(conversationState.Value);
                    break;
                }
            }
                               )
            .Test("set value", "value saved")
            .Test("get value", "test")
            .StartTestAsync();
        }
コード例 #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            var secretKey   = Configuration.GetSection("botFileSecret")?.Value;
            var botFilePath = Configuration.GetSection("botFilePath")?.Value;

            // Loads .bot configuration file and adds a singleton that your Bot can access through dependency injection.
            BotConfiguration botConfig = null;

            try
            {
                botConfig = BotConfiguration.Load(botFilePath ?? @".\contoso-help-desk.bot", secretKey);
            }
            catch
            {
                var msg = @"Error reading bot file. Please ensure you have valid botFilePath and botFileSecret set for your environment.
                    - You can find the botFilePath and botFileSecret in the Azure App Service application settings.
                    - If you are running this bot locally, consider adding a appsettings.json file with botFilePath and botFileSecret.
                    - See https://aka.ms/about-bot-file to learn more about .bot file its use and bot configuration.
                    ";
                throw new InvalidOperationException(msg);
            }

            // Retrieve current endpoint.
            var endpointName = _isProduction ? "production" : "development";
            var service      = botConfig.Services.Where(s => s.Type == "endpoint" && s.Name == endpointName).FirstOrDefault();

            if (!(service is EndpointService endpointService))
            {
                throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{endpointName}'.");
            }

            // Create credential provider and add as singleton so it is available in the controller
            var credentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);

            services.AddSingleton <ICredentialProvider>(credentialProvider);

            // The Memory Storage used here is for local bot debugging only. When the bot
            // is restarted, everything stored in memory will be gone.
            IStorage dataStore = new MemoryStorage();

            // Create Conversation State object.
            // The Conversation State object is where we persist anything at the conversation-scope.
            var conversationState        = new ConversationState(dataStore);
            var userState                = new UserState(dataStore);
            var privateConversationState = new PrivateConversationState(dataStore);

            // Create the custom state accessor.
            // State accessors enable other components to read and write individual properties of state.
            // This bot only uses dialog state.
            BotAccessors accessors = new BotAccessors(conversationState)
            {
                DialogData       = conversationState.CreateProperty <DialogState>(nameof(DialogState)),
                ConversationData = conversationState.CreateProperty <BotDataBag>(nameof(BotDataBag))
            };

            services.AddSingleton(accessors);
        }
コード例 #3
0
        public BotAccessors(ConversationState conversationState, PrivateConversationState privateConversationState, UserState userState)
        {
            this.ConversationState        = conversationState;
            this.PrivateConversationState = privateConversationState;
            this.UserState = userState;

            BotStates = new BotState[] { ConversationState, PrivateConversationState, UserState };
        }
コード例 #4
0
        public async Task PrivateConversationState_BadActivityConversationThrows()
        {
            var dictionary = new Dictionary <string, JObject>();
            var userState  = new PrivateConversationState(new MemoryStorage(dictionary));
            var context    = TestUtilities.CreateEmptyContext();

            context.Activity.Conversation = null;
            var testProperty = userState.CreateProperty <TestPocoState>("test");
            var value        = await testProperty.GetAsync(context);
        }
コード例 #5
0
        public async Task PrivateConversationState_BadActivityFromThrows()
        {
            var dictionary = new Dictionary <string, JObject>();
            var userState  = new PrivateConversationState(new MemoryStorage(dictionary));
            var context    = TestUtilities.CreateEmptyContext();

            context.Activity.Conversation = null;
            context.Activity.From         = null;
            var testProperty = userState.CreateProperty <TestPocoState>("test");
            await Assert.ThrowsAsync <ArgumentNullException>(() => testProperty.GetAsync(context));
        }
コード例 #6
0
        private BotAccessors GetAccessors()
        {
            IStorage dataStore = new MemoryStorage();

            var conversationState        = new ConversationState(dataStore);
            var userState                = new UserState(dataStore);
            var privateConversationState = new PrivateConversationState(dataStore);

            // Create the custom state accessor.
            // State accessors enable other components to read and write individual properties of state.
            return(new BotAccessors(conversationState, privateConversationState, userState)
            {
                UserData = userState.CreateProperty <BotDataBag>(BotAccessors.UserDataPropertyName),
                ConversationData = conversationState.CreateProperty <BotDataBag>(BotAccessors.ConversationDataPropertyName),
                PrivateConversationData = privateConversationState.CreateProperty <BotDataBag>(BotAccessors.PrivateConversationDataPropertyName),
                DialogData = conversationState.CreateProperty <DialogState>(nameof(DialogState))
            });
        }
コード例 #7
0
        /// <summary>
        /// Register the bot framework with Asp.net.
        /// </summary>
        /// <param name="config">Represents the configuration of the HttpServer.</param>
        public static void Register(HttpConfiguration config)
        {
            BotAccessors accessors = null;

            var builder = new ContainerBuilder();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            var credentialProvider = new SimpleCredentialProvider(ConfigurationManager.AppSettings[MicrosoftAppCredentials.MicrosoftAppIdKey],
                                                                  ConfigurationManager.AppSettings[MicrosoftAppCredentials.MicrosoftAppPasswordKey]);

            builder.RegisterInstance(credentialProvider).As <ICredentialProvider>();

            // The Memory Storage used here is for local bot debugging only. When the bot
            // is restarted, everything stored in memory will be gone.
            IStorage dataStore = new MemoryStorage();

            // Create Conversation State object.
            // The Conversation State object is where we persist anything at the conversation-scope.
            var conversationState        = new ConversationState(dataStore);
            var userState                = new UserState(dataStore);
            var privateConversationState = new PrivateConversationState(dataStore);

            // Create the custom state accessor.
            // State accessors enable other components to read and write individual properties of state.
            accessors = new BotAccessors(conversationState, privateConversationState, userState)
            {
                UserData                = userState.CreateProperty <BotDataBag>(BotAccessors.UserDataPropertyName),
                ConversationData        = conversationState.CreateProperty <BotDataBag>(BotAccessors.ConversationDataPropertyName),
                PrivateConversationData = privateConversationState.CreateProperty <BotDataBag>(BotAccessors.PrivateConversationDataPropertyName),
                DialogData              = conversationState.CreateProperty <DialogState>(nameof(DialogState))
            };

            builder.RegisterInstance(accessors).As <BotAccessors>();
            var container = builder.Build();

            var resolver = new AutofacWebApiDependencyResolver(container);

            config.DependencyResolver = resolver;
        }
コード例 #8
0
            public static void Register(HttpConfiguration config)
            {
                var builder = new ContainerBuilder();

                builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

                // The ConfigurationCredentialProvider will retrieve the MicrosoftAppId and
                // MicrosoftAppPassword from Web.config
                builder.RegisterType <ConfigurationCredentialProvider>().As <ICredentialProvider>().SingleInstance();

                // Create the Bot Framework Adapter with error handling enabled.
                builder.RegisterType <AdapterWithErrorHandler>().As <IBotFrameworkHttpAdapter>().SingleInstance();

                // The Memory Storage used here is for local bot debugging only. When the bot
                // is restarted, everything stored in memory will be gone.
                IStorage dataStore = new MemoryStorage();

                // Create Conversation State object.
                // The Conversation State object is where we persist anything at the conversation-scope.
                var conversationState       = new ConversationState(dataStore);
                var userState               = new UserState(dataStore);
                var privateConversationData = new PrivateConversationState(dataStore);

                builder.RegisterInstance(conversationState).As <ConversationState>().SingleInstance();
                builder.RegisterInstance(userState).As <UserState>().SingleInstance();
                builder.RegisterInstance(privateConversationData).As <PrivateConversationState>().SingleInstance();

                // Register the main dialog, which is injected into the DialogBot class
                builder.RegisterType <RootDialog>().SingleInstance();

                // Register the DialogBot with RootDialog as the IBot interface
                builder.RegisterType <DialogBot <RootDialog> >().As <IBot>();

                var container = builder.Build();
                var resolver  = new AutofacWebApiDependencyResolver(container);

                config.DependencyResolver = resolver;
            }
コード例 #9
0
ファイル: Startup.cs プロジェクト: micbelgique/Proxicall
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// <param name="services">Specifies the contract for a <see cref="IServiceCollection"/> of service descriptors.</param>
        /// </summary>
        public void ConfigureServices(IServiceCollection services)
        {
            // Memory Storage is for local bot debugging only. When the bot
            // is restarted, everything stored in memory will be gone.
            IStorage dataStore = new MemoryStorage();

            // For production bots use the Azure Blob or
            // Azure CosmosDB storage providers. For the Azure
            // based storage providers, add the Microsoft.Bot.Builder.Azure
            // Nuget package to your solution. That package is found at:
            // https://www.nuget.org/packages/Microsoft.Bot.Builder.Azure/
            // Un-comment the following lines to use Azure Blob Storage
            // // Storage configuration name or ID from the .bot file.
            // const string StorageConfigurationId = "<STORAGE-NAME-OR-ID-FROM-BOT-FILE>";
            // var blobConfig = botConfig.FindServiceByNameOrId(StorageConfigurationId);
            // if (!(blobConfig is BlobStorageService blobStorageConfig))
            // {
            //    throw new InvalidOperationException($"The .bot file does not contain an blob storage with name '{StorageConfigurationId}'.");
            // }
            // // Default container name.
            // const string DefaultBotContainer = "<DEFAULT-CONTAINER>";
            // var storageContainer = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container;
            // IStorage dataStore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.ConnectionString, storageContainer);

            // Create and add conversation state.
            var conversationState = new ConversationState(dataStore);

            services.AddSingleton(conversationState);

            var userState = new UserState(dataStore);

            services.AddSingleton(userState);

            var privateConversationState = new PrivateConversationState(dataStore);

            services.AddSingleton(privateConversationState);

            services.AddSingleton <StateAccessors>(sp => new StateAccessors(userState, conversationState, privateConversationState)
            {
                DialogStateAccessor = conversationState.CreateProperty <DialogState>(nameof(DialogState)),
                LoggedUserAccessor  = privateConversationState.CreateProperty <LoggedUserState>(nameof(LoggedUserState)),
                LuisStateAccessor   = userState.CreateProperty <LuisState>(nameof(LuisState)),
                CRMStateAccessor    = userState.CreateProperty <CRMState>(nameof(CRMState))
            });

            services.AddOptions();

            // Load settings from appsettings.json
            services.Configure <BotConfig>(Configuration.GetSection("BotConfig"));
            services.Configure <LuisConfig>(Configuration.GetSection("LuisConfig"));
            services.Configure <ServicesConfig>(Configuration.GetSection("ServicesConfig"));

            services.AddSingleton <BotServices>(sp => ActivatorUtilities.CreateInstance <BotServices>(sp));

            services.AddBot <ProxiCallBot>(options =>
            {
                options.CredentialProvider = new SimpleCredentialProvider(Configuration.GetSection("BotConfig")["MicrosoftAppId"], Configuration.GetSection("BotConfig")["MicrosoftAppPassword"]);

                // Catches any errors that occur during a conversation turn and logs them to currently
                // configured ILogger.
                ILogger logger = _loggerFactory.CreateLogger <ProxiCallBot>();

                options.OnTurnError = async(context, exception) =>
                {
                    var errorMessage = ExceptionHandler(exception);
                    logger.LogError($"Exception caught : {exception}");

                    var activity    = MessageFactory.Text(errorMessage, errorMessage, InputHints.AcceptingInput);
                    activity.Locale = CulturedBot.Culture?.Name;
                    await context.SendActivityAsync(activity);
                };

                //Adding Teams middleware
                options.Middleware.Add(
                    new TeamsMiddleware(
                        new ConfigurationCredentialProvider(this.Configuration)
                        )
                    );
            });

            services.AddHttpClient <AccountService>();
            services.AddHttpClient <CompanyService>();
            services.AddHttpClient <LeadService>();
            services.AddHttpClient <OpportunityService>();
            services.AddHttpClient <ProductService>();

            services.AddLocalization(options => options.ResourcesPath = "Resources");
        }
コード例 #10
0
 public StateAccessors(UserState userState, ConversationState conversationState, PrivateConversationState privateConversationState)
 {
     UserState                = userState ?? throw new ArgumentNullException(nameof(userState));
     ConversationState        = conversationState ?? throw new ArgumentNullException(nameof(conversationState));;
     PrivateConversationState = privateConversationState ?? throw new ArgumentNullException(nameof(privateConversationState));;
 }