示例#1
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 Bot Framework Adapter with error handling enabled.
            services.AddSingleton <IBotFrameworkHttpAdapter, AdapterWithErrorHandler>();

            IStorage storage;

#if true
            // Use in-memory storage
            storage = new MemoryStorage();
#else
            // Use partitioned CosmosDB for storage, instead of in-memory storage.
            storage =
                new CosmosDbPartitionedStorage(
                    new CosmosDbPartitionedStorageOptions
            {
                CosmosDbEndpoint  = Configuration.GetValue <string>("CosmosDbEndpoint"),
                AuthKey           = Configuration.GetValue <string>("CosmosDbAuthKey"),
                DatabaseId        = Configuration.GetValue <string>("CosmosDbDatabaseId"),
                ContainerId       = Configuration.GetValue <string>("CosmosDbContainerId"),
                CompatibilityMode = false,
            });
#endif
            services.AddSingleton <IStorage>(storage);

            // Create the Conversation state passing in the storage layer.
            var conversationState = new ConversationState(storage);
            services.AddSingleton(conversationState);

            // Create the bot as a transient. In this case the ASP Controller is expecting an IBot.
            services.AddTransient <IBot, EchoBot>();
        }
示例#2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StateAccessors"/> class.
        /// Contains the state management and associated accessor objects.
        /// </summary>
        public static StateAccessors Create(IConfiguration configuration = null)
        {
            IStorage storage;

            if (configuration == null || string.IsNullOrEmpty(configuration.CosmosKey()))
            {
                // Use the in-memory storage provider.
                storage = new MemoryStorage();
            }
            else
            {
                // Use the Cosmos storage provider.
                storage = new CosmosDbPartitionedStorage(
                    new CosmosDbPartitionedStorageOptions
                {
                    CosmosDbEndpoint = configuration.CosmosEndpoint(),
                    AuthKey          = configuration.CosmosKey(),
                    DatabaseId       = configuration.CosmosDatabase(),
                    ContainerId      = configuration.CosmosConversationsCollection(),
                });
            }

            // Create the state management and accessors.
            return(new StateAccessors(new ConversationState(storage)));
        }
示例#3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

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

            //var storage = new MemoryStorage();



            /* COSMOSDB STORAGE - Uncomment the code in this section to use CosmosDB storage */

            var cosmosDbStorageOptions = new CosmosDbPartitionedStorageOptions()
            {
                CosmosDbEndpoint = "https://365db.documents.azure.com:443/",
                AuthKey          = "wprejZdl9ybqxTdb3SxESe1C6qTfNjPqsOiCFwU4E4YM5qf4GxDSCP2UJ6aFZGiwC3lY5RTDrZpVpqYY3THmQQ==",
                DatabaseId       = "365db",
                ContainerId      = "365container"
            };

            var storage = new CosmosDbPartitionedStorage(cosmosDbStorageOptions);

            var userState = new UserState(storage);

            services.AddSingleton(userState);

            var conversationState = new ConversationState(storage);

            services.AddSingleton(conversationState);


            // Create the bot as a transient. In this case the ASP Controller is expecting an IBot.
            services.AddTransient <IBot, StateBot>();
        }
示例#4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            // The following line enables Application Insights telemetry collection.
            services.AddApplicationInsightsTelemetry(_config);

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

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

            /* COSMOSDB STORAGE - Uncomment the code in this section to use CosmosDB storage */
            var cosmosDBIsConfigured = !string.IsNullOrEmpty(_config["CosmosDBStateStoreEndpoint"]) && !string.IsNullOrEmpty(_config["CosmosDBStateStoreKey"]) && !string.IsNullOrEmpty(_config["CosmosDBStateStoreDatabaseId"]) && !string.IsNullOrEmpty(_config["CosmosDBStateStoreCollectionId"]);

            if (cosmosDBIsConfigured)
            {
                var cosmosDbStorageOptions = new CosmosDbPartitionedStorageOptions()
                {
                    CosmosDbEndpoint = _config["CosmosDBStateStoreEndpoint"],
                    AuthKey          = _config["CosmosDBStateStoreKey"],
                    DatabaseId       = _config["CosmosDBStateStoreDatabaseId"],
                    ContainerId      = _config["CosmosDBStateStoreCollectionId"]
                };
                storage = new CosmosDbPartitionedStorage(cosmosDbStorageOptions);
            }
            else
            {
                storage = new MemoryStorage();
                Console.WriteLine("CosmosDB Storage not used!");
            }

            /* END COSMOSDB STORAGE */

            // Create the User state passing in the storage layer.
            var userState = new UserState(storage);

            services.AddSingleton(userState);

            // Create the Conversation state passing in the storage layer.
            var conversationState = new ConversationState(storage);

            services.AddSingleton(conversationState);

            // Register LUIS recognizer
            services.AddSingleton <AddressRecognizer>();

            // The MainDialog that will be run by the bot.
            services.AddSingleton <MainDialog>();

            // Create the bot as a transient. In this case the ASP Controller is expecting an IBot.
            services.AddTransient <IBot, DialogAndWelcomeBot <MainDialog> >();

            // Add Healthcheck module
            services.AddSingleton <Healthcheck>();
        }
        public IStorage ConfigureStorage(BotSettings settings)
        {
            IStorage storage;

            if (settings.Feature.UseCosmosDb && !string.IsNullOrEmpty(settings.CosmosDb.AuthKey))
            {
                storage = new CosmosDbPartitionedStorage(settings.CosmosDb);
            }
            else
            {
                storage = new MemoryStorage();
            }

            return(storage);
        }
示例#6
0
        public IStorage ConfigureStorage(BotSettings settings)
        {
            IStorage storage;

            if (ConfigSectionValid(settings.CosmosDb.AuthKey))
            {
                storage = new CosmosDbPartitionedStorage(settings.CosmosDb);
            }
            else
            {
                storage = new MemoryStorage();
            }

            return(storage);
        }
示例#7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

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

            var cosmosDbStorageOptions = new CosmosDbPartitionedStorageOptions()
            {
                CosmosDbEndpoint = "https://electioncosmos.documents.azure.com:443/",
                AuthKey          = "0zqSGejOcM7dqU603OFedsrfXf3HG6DBrwO0YZm85h2IlZrdyDY7la7tgfX0axd9ccNN4myrphorQMlxOuuBSw==",
                DatabaseId       = "BotStoage",
                ContainerId      = "Group4"
            };
            var storage = new CosmosDbPartitionedStorage(cosmosDbStorageOptions);

            services.AddSingleton <IStorage>(new CosmosDbPartitionedStorage(cosmosDbStorageOptions));

            // 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 LUIS recognizer
            services.AddSingleton <ConversationRecognizer>();

            // The MainDialog that will be run by the bot.
            services.AddSingleton <MainDialog>();
            services.AddSingleton <ElectionDialog>();
            services.AddSingleton <IssuesDialog>();
            services.AddSingleton <ConstituencyDialog>();
            services.AddSingleton <EndConversationDialog>();
            services.AddSingleton <PartyDialog>();
            services.AddSingleton <UserProfileDialog>();

            // Create the bot as a transient. In this case the ASP Controller is expecting an IBot.
            services.AddTransient <IBot, DialogAndWelcomeBot <MainDialog> >();
        }
示例#8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //儲存

            // Create the storage we'll be using for User and Conversation state.
            // (Memory is great for testing purposes - examples of implementing storage with
            // Azure Blob Storage or Cosmos DB are below).
            //var storage = new MemoryStorage();
            var storage = new CosmosDbPartitionedStorage(
                new CosmosDbPartitionedStorageOptions
            {
                CosmosDbEndpoint  = Configuration.GetValue <string>("CosmosDbEndpoint"),
                AuthKey           = Configuration.GetValue <string>("CosmosDbAuthKey"),
                DatabaseId        = Configuration.GetValue <string>("CosmosDbDatabaseId"),
                ContainerId       = Configuration.GetValue <string>("CosmosDbContainerId"),
                CompatibilityMode = false,
            });

            // Create the User state passing in the storage layer.
            var userState = new UserState(storage);

            services.AddSingleton(userState);

            // Create the Conversation state passing in the storage layer.
            var conversationState = new ConversationState(storage);

            services.AddSingleton(conversationState);

            services.AddSingleton <IStorage>(storage);

            services.AddSingleton <ConcurrentDictionary <string, ConversationReference> >();


            services.AddControllers().AddNewtonsoftJson();

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

            // Create the bot as a transient. In this case the ASP Controller is expecting an IBot.
            services.AddTransient <IBot, EchoBot>();
        }
示例#9
0
        public IStorage ConfigureStorage(BotSettings settings)
        {
            if (string.IsNullOrEmpty(settings?.CosmosDb?.ContainerId))
            {
                if (!string.IsNullOrEmpty(this.Configuration["cosmosdb:collectionId"]))
                {
                    settings.CosmosDb.ContainerId = this.Configuration["cosmosdb:collectionId"];
                }
            }

            IStorage storage;
            if (ConfigSectionValid(settings?.CosmosDb?.AuthKey))
            {
                storage = new CosmosDbPartitionedStorage(settings?.CosmosDb);
            }
            else
            {
                storage = new MemoryStorage();
            }

            return storage;
        }
示例#10
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            // Get assets directory.
            var assetsDirectory = GetAssetsDirectory();

            // Build configuration with assets.
            var config = BuildConfiguration(assetsDirectory);

            var settings = new BotSettings();

            config.Bind(settings);

            var services = builder.Services;

            services.AddSingleton <IConfiguration>(config);

            services.AddLogging();

            // Create the credential provider to be used with the Bot Framework Adapter.
            services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>();
            services.AddSingleton <BotAdapter>(sp => (BotFrameworkHttpAdapter)sp.GetService <IBotFrameworkHttpAdapter>());

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

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

            // This is for custom action component registration.
            //ComponentRegistration.Add(new CustomActionComponentRegistration());

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

            // Register telemetry client, initializers and middleware
            services.AddApplicationInsightsTelemetry(settings?.ApplicationInsights?.InstrumentationKey ?? string.Empty);

            services.AddSingleton <ITelemetryInitializer, OperationCorrelationTelemetryInitializer>();
            services.AddSingleton <ITelemetryInitializer, TelemetryBotIdInitializer>();
            services.AddSingleton <IBotTelemetryClient, BotTelemetryClient>();
            services.AddSingleton <TelemetryLoggerMiddleware>(sp =>
            {
                var telemetryClient = sp.GetService <IBotTelemetryClient>();
                return(new TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: settings?.Telemetry?.LogPersonalInformation ?? false));
            });
            services.AddSingleton <TelemetryInitializerMiddleware>(sp =>
            {
                var httpContextAccessor       = sp.GetService <IHttpContextAccessor>();
                var telemetryLoggerMiddleware = sp.GetService <TelemetryLoggerMiddleware>();
                return(new TelemetryInitializerMiddleware(httpContextAccessor, telemetryLoggerMiddleware, settings?.Telemetry?.LogActivities ?? false));
            });

            // Storage
            IStorage storage;

            if (ConfigSectionValid(settings?.CosmosDb?.AuthKey))
            {
                storage = new CosmosDbPartitionedStorage(settings?.CosmosDb);
            }
            else
            {
                storage = new MemoryStorage();
            }

            services.AddSingleton(storage);
            var userState         = new UserState(storage);
            var conversationState = new ConversationState(storage);

            services.AddSingleton(userState);
            services.AddSingleton(conversationState);

            // Resource explorer to track declarative assets
            var resourceExplorer = new ResourceExplorer().AddFolder(assetsDirectory.FullName);

            services.AddSingleton(resourceExplorer);

            // Adapter
            services.AddSingleton <IBotFrameworkHttpAdapter, BotFrameworkHttpAdapter>(s =>
            {
                // Retrieve required dependencies
                IStorage storage    = s.GetService <IStorage>();
                UserState userState = s.GetService <UserState>();
                ConversationState conversationState = s.GetService <ConversationState>();
                TelemetryInitializerMiddleware telemetryInitializerMiddleware = s.GetService <TelemetryInitializerMiddleware>();

                var adapter = new BotFrameworkHttpAdapter(new ConfigurationCredentialProvider(config));

                adapter
                .UseStorage(storage)
                .UseBotState(userState, conversationState)
                .Use(new RegisterClassMiddleware <IConfiguration>(config))
                .Use(telemetryInitializerMiddleware);

                // Configure Middlewares
                ConfigureTranscriptLoggerMiddleware(adapter, settings);
                ConfigureInspectionMiddleWare(adapter, settings, s);
                ConfigureShowTypingMiddleWare(adapter, settings);

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

                return(adapter);
            });

            var defaultLocale = config.GetValue <string>(DefaultLanguageSetting) ?? EnglishLocale;

            var removeRecipientMention = settings?.Feature?.RemoveRecipientMention ?? false;

            // Bot
            services.AddSingleton <IBot>(s =>
                                         new ComposerBot(
                                             s.GetService <ConversationState>(),
                                             s.GetService <UserState>(),
                                             s.GetService <ResourceExplorer>(),
                                             s.GetService <BotFrameworkClient>(),
                                             s.GetService <SkillConversationIdFactoryBase>(),
                                             s.GetService <IBotTelemetryClient>(),
                                             GetRootDialog(assetsDirectory.FullName),
                                             defaultLocale,
                                             removeRecipientMention));
        }
示例#11
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();

            services.AddSingleton <IConfiguration>(this.Configuration);

            // Create the credential provider to be used with the Bot Framework Adapter.
            services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>();
            services.AddSingleton <BotAdapter>(sp => (BotFrameworkHttpAdapter)sp.GetService <IBotFrameworkHttpAdapter>());

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

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

            // Load settings
            var settings = new BotSettings();

            Configuration.Bind(settings);

            IStorage storage = null;

            // Configure storage for deployment
            if (!string.IsNullOrEmpty(settings.CosmosDb.AuthKey))
            {
                storage = new CosmosDbPartitionedStorage(settings.CosmosDb);
            }
            else
            {
                Console.WriteLine("The settings of CosmosDbStorage is incomplete, please check following settings: settings.CosmosDb");
                storage = new MemoryStorage();
            }

            services.AddSingleton(storage);
            var userState         = new UserState(storage);
            var conversationState = new ConversationState(storage);

            var botDir = Configuration.GetSection("bot").Get <string>();

            // manage all bot resources
            var resourceExplorer = new ResourceExplorer().AddFolder(botDir);
            var rootDialog       = GetRootDialog(botDir);

            var defaultLocale = Configuration.GetValue <string>("defaultLocale") ?? "en-us";

            services.AddSingleton(userState);
            services.AddSingleton(conversationState);
            services.AddSingleton(resourceExplorer);

            services.AddSingleton <IBotFrameworkHttpAdapter, BotFrameworkHttpAdapter>((s) =>
            {
                HostContext.Current.Set <IConfiguration>(Configuration);

                var adapter = new BotFrameworkHttpAdapter(new ConfigurationCredentialProvider(this.Configuration));
                adapter
                .UseStorage(storage)
                .UseState(userState, conversationState);

                if (!string.IsNullOrEmpty(settings.BlobStorage.ConnectionString) && !string.IsNullOrEmpty(settings.BlobStorage.Container))
                {
                    adapter.Use(new TranscriptLoggerMiddleware(new AzureBlobTranscriptStore(settings.BlobStorage.ConnectionString, settings.BlobStorage.Container)));
                }
                else
                {
                    Console.WriteLine("The settings of TranscriptLoggerMiddleware is incomplete, please check following settings: settings.BlobStorage.ConnectionString, settings.BlobStorage.Container");
                }

                adapter.OnTurnError = async(turnContext, exception) =>
                {
                    await turnContext.SendActivityAsync(exception.Message).ConfigureAwait(false);
                    await conversationState.ClearStateAsync(turnContext).ConfigureAwait(false);
                    await conversationState.SaveChangesAsync(turnContext).ConfigureAwait(false);
                };
                return(adapter);
            });

            services.AddSingleton <IBot>(s =>
                                         new ComposerBot(
                                             s.GetService <ConversationState>(),
                                             s.GetService <UserState>(),
                                             s.GetService <ResourceExplorer>(),
                                             s.GetService <BotFrameworkClient>(),
                                             s.GetService <SkillConversationIdFactoryBase>(),
                                             rootDialog,
                                             defaultLocale));
        }