Exemple #1
0
        public Bot(BotAccessors accessors)
        {
            this.accessors = accessors ?? throw new ArgumentNullException(nameof(accessors));

            this.logger = accessors.LoggerFactory.CreateLogger <Bot>();
            this.logger.LogTrace("Starting bot");

            this.dialogs = new DialogSet(accessors.ConversationDialogState);
            this.dialogs.Add(new MainDialog(accessors));
        }
        public BotAppBot(BotAccessors accessors, ConversationState conversationState, UserState userState, ILogger <BotAppBot> logger)
        {
            _accessors         = accessors;
            _conversationState = conversationState;
            _userState         = userState;
            _logger            = logger;

            this.dialogs = new DialogSet(accessors.ConversationDialogState);
            this.dialogs.Add(new MainDialog(accessors));
            this.dialogs.Add(new LuisQnADialog(accessors));
        }
Exemple #3
0
        public FeedbackDialog(BotAccessors accessors) : base(dialogId)
        {
            this.accessors = accessors ?? throw new ArgumentNullException(nameof(accessors));
            _userState     = accessors.UserState;

            AddDialog(new WaterfallDialog(dialogId, new WaterfallStep[]
            {
                StartAsync,
                MessageReceivedAsync
            }));
        }
Exemple #4
0
        /// <summary>
        /// Access point to start bot
        /// </summary>
        /// <param name="accessors"></param>
        public MainDialog(BotAccessors accessors) : base(dialogId)
        {
            this.accessors = accessors ?? throw new ArgumentNullException(nameof(accessors));

            AddDialog(new WaterfallDialog(dialogId, new WaterfallStep[]
            {
                StartDialog
            }));
            // added dialogs
            AddDialog(new LuisQnADialog(accessors));
            AddDialog(new FeedbackDialog(accessors));
        }
        public AskForFaceImageDialog(BotAccessors accessors) : base(dialogId)
        {
            this.accessors = accessors ?? throw new ArgumentNullException(nameof(accessors));

            AddDialog(new WaterfallDialog(dialogId, new WaterfallStep[]
            {
                RequestImageDialog,
                EndAskForFaceImageDialog
            }));

            AddDialog(new AttachmentPrompt("AttachmentPromptValidator", validator));
        }
Exemple #6
0
        public LuisQnADialog(BotAccessors accessors) : base(dialogId)
        {
            this.accessors = accessors ?? throw new ArgumentNullException(nameof(accessors));
            _userState     = accessors.UserState;
            AddDialog(new WaterfallDialog(dialogId, new WaterfallStep[]
            {
                ProcessQuestionDialog,
                EndDialog
            }));

            AddDialog(new FeedbackDialog(accessors));
        }
Exemple #7
0
        public MainDialog(BotAccessors accessors) : base(dialogId)
        {
            this.accessors = accessors ?? throw new ArgumentNullException(nameof(accessors));

            AddDialog(new WaterfallDialog(dialogId, new WaterfallStep[]
            {
                LaunchIdentifyDialog,
                EndMainDialog
            }));

            AddDialog(new IdentifyDialog(accessors));
            AddDialog(new LuisQnADialog(accessors));
        }
Exemple #8
0
        public BotAppBot(BotAccessors accessors, LuisRouterAccessor luisRouterAccessor, QnAMakerAccessor qnaMakerAccessor, ConversationState conversationState, UserState userState, ILogger <BotAppBot> logger)
        {
            this.accessors          = accessors;
            this.conversationState  = conversationState;
            this.userState          = userState;
            this.logger             = logger;
            this.luisRouterAccessor = luisRouterAccessor;
            this.qnaMakerAccessor   = qnaMakerAccessor;

            this.dialogs = new DialogSet(accessors.ConversationDialogState);
            this.dialogs.Add(new MainDialog(accessors, luisRouterAccessor, qnaMakerAccessor));
            this.dialogs.Add(new LuisQnADialog(accessors, luisRouterAccessor, qnaMakerAccessor));
        }
Exemple #9
0
        public MainDialog(BotAccessors accessors, LuisRouterAccessor luisRouterAccessor, QnAMakerAccessor qnaMakerAccessor) : base(dialogId)
        {
            this.accessors          = accessors ?? throw new ArgumentNullException(nameof(accessors));
            this.luisRouterAccessor = luisRouterAccessor ?? throw new ArgumentNullException(nameof(luisRouterAccessor));
            this.qnaMakerAccessor   = qnaMakerAccessor ?? throw new ArgumentNullException(nameof(qnaMakerAccessor));

            AddDialog(new WaterfallDialog(dialogId, new WaterfallStep[]
            {
                LaunchLuisQnADialog,
                EndMainDialog
            }));

            AddDialog(new LuisQnADialog(accessors, luisRouterAccessor, qnaMakerAccessor));
        }
        public MainDialog(BotAccessors accessors) : base(dialogId)
        {
            this.accessors = accessors ?? throw new ArgumentNullException(nameof(accessors));

            AddDialog(new WaterfallDialog(dialogId, new WaterfallStep[]
            {
                AskQuestionDialog,
                ProcessQuestionDialog,
                ProcessIfExampleIsRequiredDialog,
                EndDialog
            }));

            AddDialog(new TextPrompt("QuestionValidator", QuestionValidator));
            AddDialog(new ChoicePrompt("AskForExampleValidator", AskForExampleValidator)
            {
                Style = ListStyle.List
            });
        }
        public IdentifyDialog(BotAccessors accessors) : base(dialogId)
        {
            this.personDBHelper = new PersonDBHelper(DBConfiguration.GetMongoDbConnectionInfo());
            this.accessors      = accessors ?? throw new ArgumentNullException(nameof(accessors));

            AddDialog(new WaterfallDialog(dialogId, new WaterfallStep[]
            {
                IntroDialog,
                CheckAskForImageDialog,
                RequestPasscodeDialog,
                ResponsePasscodeDialog,
                SaveInformationIfNewDialog,
                EndIdentifyDialog
            }));

            AddDialog(new TextPrompt("TextPromptValidator", validator));
            AddDialog(new AskForFaceImageDialog(accessors));
            AddDialog(new ProfileDialog(accessors));
        }
Exemple #12
0
        public ProfileDialog(BotAccessors accessors) : base(dialogId)
        {
            this.accessors = accessors ?? throw new ArgumentNullException(nameof(accessors));

            AddDialog(new WaterfallDialog(dialogId, new WaterfallStep[]
            {
                AskFullnameDialog,
                GetFullnameDialog,
                ListCombinationsDialog,
                DecomposeNameLastnameDialog,
                EndProfileDialog
            }));

            AddDialog(new TextPrompt("TextPromptValidator", validator));
            AddDialog(new ChoicePrompt("ChoicePrompt")
            {
                Style = ListStyle.List
            });
        }
Exemple #13
0
        public LuisQnADialog(BotAccessors accessors, LuisRouterAccessor luisRouterAccessor, QnAMakerAccessor qnaMakerAccessor) : base(dialogId)
        {
            this.accessors          = accessors ?? throw new ArgumentNullException(nameof(accessors));
            this.luisRouterAccessor = luisRouterAccessor ?? throw new ArgumentNullException(nameof(luisRouterAccessor));
            this.qnaMakerAccessor   = qnaMakerAccessor ?? throw new ArgumentNullException(nameof(qnaMakerAccessor));

            AddDialog(new WaterfallDialog(dialogId, new WaterfallStep[]
            {
                AskQuestionDialog,
                ProcessQuestionDialog,
                ProcessIfExampleIsRequiredDialog,
                EndDialog
            }));

            AddDialog(new TextPrompt("QuestionValidator", QuestionValidator));
            AddDialog(new ChoicePrompt("AskForExampleValidator", AskForExampleValidator)
            {
                Style = ListStyle.List
            });
        }
Exemple #14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Reading settings
            Settings.MicrosoftAppId       = Configuration.GetSection("MicrosoftAppId")?.Value;
            Settings.MicrosoftAppPassword = Configuration.GetSection("MicrosoftAppPassword")?.Value;

            Settings.BotConversationStorageConnectionString = Configuration.GetSection("BotConversationStorageConnectionString")?.Value;
            Settings.BotConversationStorageKey                    = Configuration.GetSection("BotConversationStorageKey")?.Value;
            Settings.BotConversationStorageDatabaseId             = Configuration.GetSection("BotConversationStorageDatabaseId")?.Value;
            Settings.BotConversationStorageUserCollection         = Configuration.GetSection("BotConversationStorageUserCollection")?.Value;
            Settings.BotConversationStorageConversationCollection = Configuration.GetSection("BotConversationStorageConversationCollection")?.Value;
            Settings.LuisAppId01        = Configuration.GetSection("LuisAppId01")?.Value;
            Settings.LuisName01         = Configuration.GetSection("LuisName01")?.Value;
            Settings.LuisAuthoringKey01 = Configuration.GetSection("LuisAuthoringKey01")?.Value;
            Settings.LuisEndpoint01     = Configuration.GetSection("LuisEndpoint01")?.Value;
            Settings.QnAKbId01          = Configuration.GetSection("QnAKbId01")?.Value;
            Settings.QnAName01          = Configuration.GetSection("QnAName01")?.Value;
            Settings.QnAEndpointKey01   = Configuration.GetSection("QnAEndpointKey01")?.Value;
            Settings.QnAHostname01      = Configuration.GetSection("QnAHostname01")?.Value;

            Settings.AzureWebJobsStorage     = Configuration.GetSection("AzureWebJobsStorage")?.Value;
            Settings.FaceAPIKey              = Configuration.GetSection("FaceAPIKey")?.Value;
            Settings.FaceAPIZone             = Configuration.GetSection("FaceAPIZone")?.Value;
            Settings.LargeFaceListId         = Configuration.GetSection("LargeFaceListId")?.Value;
            Settings.MongoDBConnectionString = Configuration.GetSection("MongoDBConnectionString")?.Value;
            Settings.MongoDBDatabaseId       = Configuration.GetSection("MongoDBDatabaseId")?.Value;
            Settings.PersonCollection        = Configuration.GetSection("PersonCollection")?.Value;

            APIReference.FaceAPIKey  = Settings.FaceAPIKey;
            APIReference.FaceAPIZone = Settings.FaceAPIZone;

            // Adding storage
            CosmosDbStorage userstorage = new CosmosDbStorage(new CosmosDbStorageOptions
            {
                AuthKey          = Settings.BotConversationStorageKey,
                CollectionId     = Settings.BotConversationStorageUserCollection,
                CosmosDBEndpoint = new Uri(Settings.BotConversationStorageConnectionString),
                DatabaseId       = Settings.BotConversationStorageDatabaseId,
            });

            CosmosDbStorage conversationstorage = new CosmosDbStorage(new CosmosDbStorageOptions
            {
                AuthKey          = Settings.BotConversationStorageKey,
                CollectionId     = Settings.BotConversationStorageConversationCollection,
                CosmosDBEndpoint = new Uri(Settings.BotConversationStorageConnectionString),
                DatabaseId       = Settings.BotConversationStorageDatabaseId,
            });

            var userState         = new UserState(userstorage);
            var conversationState = new ConversationState(conversationstorage);

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

            // Adding communication to discovery service
            services.AddSingleton <Microsoft.Extensions.Hosting.IHostedService, ConsulHostedService>();
            services.Configure <ConsulConfig>(Configuration.GetSection("ConsulConfig"));
            services.AddSingleton <IConsulClient, ConsulClient>(p => new ConsulClient(consulConfig =>
            {
                var address          = Configuration["ConsulConfig:address"];
                consulConfig.Address = new Uri(address);
            }));

            // Adding MVC compatibility
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

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

            // Adding the channel provider to be used with the Bot Framework Adapter
            services.AddSingleton <IChannelProvider, ConfigurationChannelProvider>();

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

            // Adding middlewares
            services.AddSingleton(new AutoSaveStateMiddleware(userState, conversationState));
            services.AddSingleton(new ShowTypingMiddleware());

            // Adding accessors
            services.AddSingleton(sp =>
            {
                // We need to grab the conversationState we added on the options in the previous step
                var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
                if (options == null)
                {
                    throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the State Accessors");
                }

                var luisServices = new Dictionary <string, LuisRecognizer>();
                var app          = new LuisApplication(Settings.LuisAppId01, Settings.LuisAuthoringKey01, Settings.LuisEndpoint01);
                var recognizer   = new LuisRecognizer(app);
                luisServices.Add(Settings.LuisName01, recognizer);

                var qnaEndpoint = new QnAMakerEndpoint()
                {
                    KnowledgeBaseId = Settings.QnAKbId01,
                    EndpointKey     = Settings.QnAEndpointKey01,
                    Host            = Settings.QnAHostname01,
                };

                var qnaOptions = new QnAMakerOptions
                {
                    ScoreThreshold = 0.3F
                };

                var qnaServices = new Dictionary <string, QnAMaker>();
                var qnaMaker    = new QnAMaker(qnaEndpoint, qnaOptions);
                qnaServices.Add(Settings.QnAName01, qnaMaker);

                // Create the custom state accessor.
                // State accessors enable other components to read and write individual properties of state.
                var accessors = new BotAccessors(loggerFactory, conversationState, userState, luisServices, qnaServices)
                {
                    ConversationDialogState   = conversationState.CreateProperty <DialogState>("DialogState"),
                    AskForExamplePreference   = conversationState.CreateProperty <bool>("AskForExamplePreference"),
                    DetectedFaceIdPreference  = conversationState.CreateProperty <string>("DetectedFaceIdPreference"),
                    ImageUriPreference        = conversationState.CreateProperty <string>("ImageUriPreference"),
                    HashPreference            = conversationState.CreateProperty <string>("HashPreference"),
                    IsNewPreference           = conversationState.CreateProperty <bool>("IsNewPreference"),
                    FullnamePreference        = userState.CreateProperty <string>("FullnamePreference"),
                    NamePreference            = userState.CreateProperty <string>("NamePreference"),
                    LastnamePreference        = userState.CreateProperty <string>("LastnamePreference"),
                    IsAuthenticatedPreference = userState.CreateProperty <bool>("IsAuthenticatedPreference")
                };

                return(accessors);
            });

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

            // Adding the bot as a transient. In this case the ASP Controller is expecting an IBot
            services.AddTransient <IBot, BotAppBot>();
        }
Exemple #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Retrieve configuration from sections
            Settings.MicrosoftAppId       = Configuration.GetSection("MicrosoftAppId")?.Value;
            Settings.MicrosoftAppPassword = Configuration.GetSection("MicrosoftAppPassword")?.Value;
            Settings.BotVersion           = Configuration.GetSection("BotVersion")?.Value;
            Settings.TimeZone             = Configuration.GetSection("TimeZone")?.Value;
            Settings.BotConversationStorageConnectionString = Configuration.GetSection("BotConversationStorageConnectionString")?.Value;
            Settings.BotConversationStorageKey                    = Configuration.GetSection("BotConversationStorageKey")?.Value;
            Settings.BotConversationStorageDatabaseId             = Configuration.GetSection("BotConversationStorageDatabaseId")?.Value;
            Settings.BotConversationStorageUserCollection         = Configuration.GetSection("BotConversationStorageUserCollection")?.Value;
            Settings.BotConversationStorageConversationCollection = Configuration.GetSection("BotConversationStorageConversationCollection")?.Value;
            Settings.LuisAppId01        = Configuration.GetSection("LuisAppId01")?.Value;
            Settings.LuisName01         = Configuration.GetSection("LuisName01")?.Value;
            Settings.LuisAuthoringKey01 = Configuration.GetSection("LuisAuthoringKey01")?.Value;
            Settings.LuisEndpoint01     = Configuration.GetSection("LuisEndpoint01")?.Value;
            Settings.QnAKbId01          = Configuration.GetSection("QnAKbId01")?.Value;
            Settings.QnAName01          = Configuration.GetSection("QnAName01")?.Value;
            Settings.QnAEndpointKey01   = Configuration.GetSection("QnAEndpointKey01")?.Value;
            Settings.QnAHostname01      = Configuration.GetSection("QnAHostname01")?.Value;

            CosmosDbStorage userstorage = new CosmosDbStorage(new CosmosDbStorageOptions
            {
                AuthKey          = Settings.BotConversationStorageKey,
                CollectionId     = Settings.BotConversationStorageUserCollection,
                CosmosDBEndpoint = new Uri(Settings.BotConversationStorageConnectionString),
                DatabaseId       = Settings.BotConversationStorageDatabaseId,
            });

            CosmosDbStorage conversationstorage = new CosmosDbStorage(new CosmosDbStorageOptions
            {
                AuthKey          = Settings.BotConversationStorageKey,
                CollectionId     = Settings.BotConversationStorageConversationCollection,
                CosmosDBEndpoint = new Uri(Settings.BotConversationStorageConnectionString),
                DatabaseId       = Settings.BotConversationStorageDatabaseId,
            });

            var userState         = new UserState(userstorage);
            var conversationState = new ConversationState(conversationstorage);

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

            services.AddBot <Bot>(options =>
            {
                options.CredentialProvider = new SimpleCredentialProvider(Settings.MicrosoftAppId, Settings.MicrosoftAppPassword);

                // The BotStateSet middleware forces state storage to auto-save when the bot is complete processing the message.
                // Note: Developers may choose not to add all the state providers to this middleware if save is not required.
                options.Middleware.Add(new AutoSaveStateMiddleware(userState, conversationState));
                options.Middleware.Add(new ShowTypingMiddleware());

                // Creates a logger for the application to use.
                ILogger logger = loggerFactory.CreateLogger <Bot>();

                // Catches any errors that occur during a conversation turn and logs them.
                options.OnTurnError = async(context, exception) =>
                {
                    logger.LogError($"Exception caught : {exception}");
                    await context.SendActivityAsync("Sorry, it looks like something went wrong.");
                };
            });

            services.AddSingleton(sp =>
            {
                // We need to grab the conversationState we added on the options in the previous step
                var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
                if (options == null)
                {
                    throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the State Accessors");
                }

                var luisServices = new Dictionary <string, LuisRecognizer>();
                var app          = new LuisApplication(Settings.LuisAppId01, Settings.LuisAuthoringKey01, Settings.LuisEndpoint01);
                var recognizer   = new LuisRecognizer(app);
                luisServices.Add(Settings.LuisName01, recognizer);

                var qnaEndpoint = new QnAMakerEndpoint()
                {
                    KnowledgeBaseId = Settings.QnAKbId01,
                    EndpointKey     = Settings.QnAEndpointKey01,
                    Host            = Settings.QnAHostname01,
                };

                var qnaOptions = new QnAMakerOptions
                {
                    ScoreThreshold = 0.3F
                };

                var qnaServices = new Dictionary <string, QnAMaker>();
                var qnaMaker    = new QnAMaker(qnaEndpoint, qnaOptions);
                qnaServices.Add(Settings.QnAName01, qnaMaker);

                // Create the custom state accessor.
                // State accessors enable other components to read and write individual properties of state.
                var accessors = new BotAccessors(loggerFactory, conversationState, userState, luisServices, qnaServices)
                {
                    ConversationDialogState = conversationState.CreateProperty <DialogState>("DialogState"),
                    AskForExamplePreference = conversationState.CreateProperty <bool>("AskForExamplePreference")
                };

                return(accessors);
            });
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Reading settings
            Settings.MicrosoftAppId       = Configuration.GetSection("ApplicationSettings:MicrosoftAppId")?.Value;
            Settings.MicrosoftAppPassword = Configuration.GetSection("ApplicationSettings:MicrosoftAppPassword")?.Value;
            Settings.BotConversationStorageConnectionString = Configuration.GetSection("ApplicationSettings:BotConversationStorageConnectionString")?.Value;
            Settings.BotConversationStorageKey                    = Configuration.GetSection("ApplicationSettings:BotConversationStorageKey")?.Value;
            Settings.BotConversationStorageDatabaseId             = Configuration.GetSection("ApplicationSettings:BotConversationStorageDatabaseId")?.Value;
            Settings.BotConversationStorageUserCollection         = Configuration.GetSection("ApplicationSettings:BotConversationStorageUserCollection")?.Value;
            Settings.BotConversationStorageConversationCollection = Configuration.GetSection("ApplicationSettings:BotConversationStorageConversationCollection")?.Value;

            // Adding EncryptionKey and ApplicationCode
            using (KeyVaultHelper keyVaultHelper = new KeyVaultHelper(EnvironmentName, ContentRootPath))
            {
                Settings.KeyVaultEncryptionKey = Configuration.GetSection("ApplicationSettings:KeyVaultEncryptionKey")?.Value;
                EncryptionKey = keyVaultHelper.GetVaultKeyAsync(Settings.KeyVaultEncryptionKey).Result;

                Settings.KeyVaultApplicationCode = Configuration.GetSection("ApplicationSettings:KeyVaultApplicationCode")?.Value;
                ApplicationCode = keyVaultHelper.GetVaultKeyAsync(Settings.KeyVaultApplicationCode).Result;
            }

            // Adding CosmosDB user storage
            CosmosDbStorage userstorage = new CosmosDbStorage(new CosmosDbStorageOptions
            {
                AuthKey          = Settings.BotConversationStorageKey,
                CollectionId     = Settings.BotConversationStorageUserCollection,
                CosmosDBEndpoint = new Uri(Settings.BotConversationStorageConnectionString),
                DatabaseId       = Settings.BotConversationStorageDatabaseId,
            });

            var userState = new UserState(userstorage);

            services.AddSingleton(userState);

            // Adding CosmosDB conversation storage
            CosmosDbStorage conversationstorage = new CosmosDbStorage(new CosmosDbStorageOptions
            {
                AuthKey          = Settings.BotConversationStorageKey,
                CollectionId     = Settings.BotConversationStorageConversationCollection,
                CosmosDBEndpoint = new Uri(Settings.BotConversationStorageConnectionString),
                DatabaseId       = Settings.BotConversationStorageDatabaseId,
            });

            var conversationState = new ConversationState(conversationstorage);

            services.AddSingleton(conversationState);

            // Adding Consul hosted service
            using (ConsulHelper consulHelper = new ConsulHelper(EnvironmentName, ContentRootPath))
            {
                consulHelper.Initialize(services, Configuration);
            }

            // Adding MVC compatibility
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

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

            // Adding the channel provider to be used with the Bot Framework Adapter
            services.AddSingleton <IChannelProvider, ConfigurationChannelProvider>();

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

            // Adding middlewares
            services.AddSingleton(new AutoSaveStateMiddleware(userState, conversationState));
            services.AddSingleton(new ShowTypingMiddleware());

            // Add Application Insights services into service collection
            services.AddApplicationInsightsTelemetry();

            // Add the standard telemetry client
            services.AddSingleton <IBotTelemetryClient, BotTelemetryClient>();

            // Add ASP middleware to store the HTTP body, mapped with bot activity key, in the httpcontext.items
            // This will be picked by the TelemetryBotIdInitializer
            services.AddTransient <TelemetrySaveBodyASPMiddleware>();

            // Add telemetry initializer that will set the correlation context for all telemetry items
            services.AddSingleton <ITelemetryInitializer, OperationCorrelationTelemetryInitializer>();

            // Add telemetry initializer that sets the user ID and session ID (in addition to other
            // bot-specific properties, such as activity ID)
            services.AddSingleton <ITelemetryInitializer, TelemetryBotIdInitializer>();

            // Create the telemetry middleware to track conversation events
            services.AddSingleton <IMiddleware, TelemetryLoggerMiddleware>();

            // Adding LUIS Router accessor
            services.AddSingleton(sp =>
            {
                LuisRouterAccessor accessor = null;
                using (LuisRouterHelper luisRouterHelper = new LuisRouterHelper(EnvironmentName, ContentRootPath))
                {
                    accessor = luisRouterHelper.BuildAccessor(userState, sp.GetRequiredService <IBotTelemetryClient>());
                }
                return(accessor);
            });

            // Adding QnAMaker Router accessor
            services.AddSingleton(sp =>
            {
                QnAMakerAccessor accessor = null;
                using (QnAMakerHelper qnaMakerHelper = new QnAMakerHelper(EnvironmentName, ContentRootPath))
                {
                    accessor = qnaMakerHelper.BuildAccessor();
                }
                return(accessor);
            });

            // Adding accessors
            services.AddSingleton(sp =>
            {
                // We need to grab the conversationState we added on the options in the previous step
                var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
                if (options == null)
                {
                    throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the State Accessors");
                }

                // Create the custom state accessor.
                // State accessors enable other components to read and write individual properties of state.
                var accessors = new BotAccessors(loggerFactory, conversationState, userState)
                {
                    ConversationDialogState   = conversationState.CreateProperty <DialogState>("DialogState"),
                    AskForExamplePreference   = conversationState.CreateProperty <bool>("AskForExamplePreference"),
                    IsAuthenticatedPreference = userState.CreateProperty <bool>("IsAuthenticatedPreference")
                };

                return(accessors);
            });

            // Adding the bot as a transient. In this case the ASP Controller is expecting an IBot
            services.AddTransient <IBot, BotAppBot>();
        }
Exemple #17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Reading settings
            Settings.MicrosoftAppId       = Configuration.GetSection("MicrosoftAppId")?.Value;
            Settings.MicrosoftAppPassword = Configuration.GetSection("MicrosoftAppPassword")?.Value;

            Settings.BotConversationStorageConnectionString = Configuration.GetSection("BotConversationStorageConnectionString")?.Value;
            Settings.BotConversationStorageKey                    = Configuration.GetSection("BotConversationStorageKey")?.Value;
            Settings.BotConversationStorageDatabaseId             = Configuration.GetSection("BotConversationStorageDatabaseId")?.Value;
            Settings.BotConversationStorageUserCollection         = Configuration.GetSection("BotConversationStorageUserCollection")?.Value;
            Settings.BotConversationStorageConversationCollection = Configuration.GetSection("BotConversationStorageConversationCollection")?.Value;
            Settings.LuisAppId01               = Configuration.GetSection("LuisAppId01")?.Value;
            Settings.LuisName01                = Configuration.GetSection("LuisName01")?.Value;
            Settings.LuisAuthoringKey01        = Configuration.GetSection("LuisAuthoringKey01")?.Value;
            Settings.LuisEndpoint01            = Configuration.GetSection("LuisEndpoint01")?.Value;
            Settings.QnAKbId01                 = Configuration.GetSection("QnAKbId01")?.Value;
            Settings.QnAName01                 = Configuration.GetSection("QnAName01")?.Value;
            Settings.QnAEndpointKey01          = Configuration.GetSection("QnAEndpointKey01")?.Value;
            Settings.QnAHostname01             = Configuration.GetSection("QnAHostname01")?.Value;
            Settings.TotalBestNextAnswers      = Configuration.GetSection("TotalBestNextAnswers")?.Value;
            Settings.HighConfidenceThreshold   = Configuration.GetSection("threshold1")?.Value.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
            Settings.MediumConfidenceThreshold = Configuration.GetSection("threshold2")?.Value.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
            Settings.LowConfidenceThreshold    = Configuration.GetSection("threshold3")?.Value.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
            Settings.TotalBestNextAnswers      = Configuration.GetSection("TotalBestNextAnswers")?.Value;


            // Add Application Insights services into service collection
            services.AddApplicationInsightsTelemetry();

            // Add the standard telemetry client
            services.AddSingleton <IBotTelemetryClient, BotTelemetryClient>();

            // Add ASP middleware to store the HTTP body, mapped with bot activity key, in the httpcontext.items
            // This will be picked by the TelemetryBotIdInitializer
            services.AddTransient <TelemetrySaveBodyASPMiddleware>();

            // Add telemetry initializer that will set the correlation context for all telemetry items
            services.AddSingleton <ITelemetryInitializer, OperationCorrelationTelemetryInitializer>();

            // Add telemetry initializer that sets the user ID and session ID (in addition to other
            // bot-specific properties, such as activity ID)
            services.AddSingleton <ITelemetryInitializer, TelemetryBotIdInitializer>();

            // Adding storage
            CosmosDbStorage userstorage = new CosmosDbStorage(new CosmosDbStorageOptions
            {
                AuthKey          = Settings.BotConversationStorageKey,
                CollectionId     = Settings.BotConversationStorageUserCollection,
                CosmosDBEndpoint = new Uri(Settings.BotConversationStorageConnectionString),
                DatabaseId       = Settings.BotConversationStorageDatabaseId,
            });

            CosmosDbStorage conversationstorage = new CosmosDbStorage(new CosmosDbStorageOptions
            {
                AuthKey          = Settings.BotConversationStorageKey,
                CollectionId     = Settings.BotConversationStorageConversationCollection,
                CosmosDBEndpoint = new Uri(Settings.BotConversationStorageConnectionString),
                DatabaseId       = Settings.BotConversationStorageDatabaseId,
            });

            var userState         = new UserState(userstorage);
            var conversationState = new ConversationState(conversationstorage);

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


            // Adding MVC compatibility
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

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

            // Adding the channel provider to be used with the Bot Framework Adapter
            services.AddSingleton <IChannelProvider, ConfigurationChannelProvider>();

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

            // Adding middlewares
            services.AddSingleton(new AutoSaveStateMiddleware(userState, conversationState));
            services.AddSingleton(new ShowTypingMiddleware());

            // Adding accessors
            services.AddSingleton(sp =>
            {
                // We need to grab the conversationState we added on the options in the previous step
                var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
                if (options == null)
                {
                    throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the State Accessors");
                }

                var luisServices = new Dictionary <string, LuisRecognizer>();
                var app          = new LuisApplication(Settings.LuisAppId01, Settings.LuisAuthoringKey01, Settings.LuisEndpoint01);
                var recognizer   = new LuisRecognizer(app);
                luisServices.Add(Settings.LuisName01, recognizer);

                var qnaEndpoint = new QnAMakerEndpoint()
                {
                    KnowledgeBaseId = Settings.QnAKbId01,
                    EndpointKey     = Settings.QnAEndpointKey01,
                    Host            = Settings.QnAHostname01,
                };

                var qnaOptions = new QnAMakerOptions
                {
                    ScoreThreshold = 0.3F
                };

                var qnaServices = new Dictionary <string, QnAMaker>();
                var qnaMaker    = new QnAMaker(qnaEndpoint, qnaOptions);
                qnaServices.Add(Settings.QnAName01, qnaMaker);

                // Create the custom state accessor.
                // State accessors enable other components to read and write individual properties of state.
                var accessors = new BotAccessors(loggerFactory, conversationState, userState, luisServices, qnaServices)
                {
                    ConversationDialogState   = conversationState.CreateProperty <DialogState>("DialogState"),
                    LastSearchPreference      = userState.CreateProperty <string>("LastSearchPreference"),
                    LastAnswerPreference      = userState.CreateProperty <string>("LastAnswerPreference"),
                    IsAuthenticatedPreference = userState.CreateProperty <bool>("IsAu`thenticatedPreference")
                };

                return(accessors);
            });

            services.AddTransient <IBot, BotAppBot>();
        }