Beispiel #1
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_2);

            // add background task queue
            services.AddSingleton <IBackgroundTaskQueue, BackgroundTaskQueue>();
            services.AddHostedService <QueuedHostedService>();

            // Load the connected services from .bot file.
            var botFilePath   = Configuration.GetSection("botFilePath")?.Value;
            var botFileSecret = Configuration.GetSection("botFileSecret")?.Value;
            var botConfig     = BotConfiguration.Load(botFilePath, botFileSecret);

            services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot config file could not be loaded."));

            // Use Application Insights
            services.AddBotApplicationInsights(botConfig);

            // Initializes your bot service clients and adds a singleton that your Bot can access through dependency injection.
            var parameters    = Configuration.GetSection("parameters")?.Get <string[]>();
            var configuration = Configuration.GetSection("configuration")?.GetChildren()?.ToDictionary(x => x.Key, y => y.Value as object);

            var supportedProviders = Configuration.GetSection("SupportedProviders")?.Get <string[]>();
            var languageModels     = Configuration.GetSection("languageModels").Get <Dictionary <string, Dictionary <string, string> > >();
            SkillConfigurationBase connectedServices = new SkillConfiguration(botConfig, languageModels, supportedProviders, parameters, configuration);

            services.AddSingleton(sp => connectedServices);

            // Initialize Bot State
            var cosmosDbService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.CosmosDB) ?? throw new Exception("Please configure your CosmosDb service in your .bot file.");
            var cosmosDb        = cosmosDbService as CosmosDbService;
            var cosmosOptions   = new CosmosDbStorageOptions()
            {
                CosmosDBEndpoint = new Uri(cosmosDb.Endpoint),
                AuthKey          = cosmosDb.Key,
                CollectionId     = cosmosDb.Collection,
                DatabaseId       = cosmosDb.Database,
            };
            var dataStore         = new CosmosDbStorage(cosmosOptions);
            var userState         = new UserState(dataStore);
            var conversationState = new ConversationState(dataStore);
            var proactiveState    = new ProactiveState(dataStore);

            services.AddSingleton(dataStore);
            services.AddSingleton(userState);
            services.AddSingleton(conversationState);
            services.AddSingleton(proactiveState);
            services.AddSingleton(new BotStateSet(userState, conversationState));

            var environment = _isProduction ? "production" : "development";
            var service     = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.Endpoint && s.Name == environment);

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

            services.AddSingleton(endpointService);

            // Add the bot
            services.AddSingleton <IBot, NewsSkill>();

            // Add the http adapter to enable MVC style bot API
            services.AddSingleton <IBotFrameworkHttpAdapter>(sp =>
            {
                var credentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);

                // Telemetry Middleware (logs activity messages in Application Insights)
                var telemetryClient         = sp.GetService <IBotTelemetryClient>();
                var botFrameworkHttpAdapter = new BotFrameworkHttpAdapter(credentialProvider)
                {
                    OnTurnError = async(context, exception) =>
                    {
                        await context.SendActivityAsync(MainStrings.ERROR);
                        await context.SendActivityAsync(new Activity(type: ActivityTypes.Trace, text: $"News Skill Error: {exception.Message} | {exception.StackTrace}"));
                        telemetryClient.TrackExceptionEx(exception, context.Activity);
                    }
                };
                var appInsightsLogger = new TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: true);
                botFrameworkHttpAdapter.Use(appInsightsLogger);

                // Transcript Middleware (saves conversation history in a standard format)
                var storageService       = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.BlobStorage) ?? throw new Exception("Please configure your Azure Storage service in your .bot file.");
                var blobStorage          = storageService as BlobStorageService;
                var transcriptStore      = new AzureBlobTranscriptStore(blobStorage.ConnectionString, blobStorage.Container);
                var transcriptMiddleware = new TranscriptLoggerMiddleware(transcriptStore);
                botFrameworkHttpAdapter.Use(transcriptMiddleware);

                // Typing Middleware (automatically shows typing when the bot is responding/working)
                var typingMiddleware = new ShowTypingMiddleware();
                botFrameworkHttpAdapter.Use(typingMiddleware);

                botFrameworkHttpAdapter.Use(new AutoSaveStateMiddleware(userState, conversationState));

                return(botFrameworkHttpAdapter);
            });
        }
 public BotFrameworkAdapter(string appId, string appPassword, HttpClient httpClient = null) : base()
 {
     _httpClient         = httpClient ?? new HttpClient();
     _credentials        = new MicrosoftAppCredentials(appId, appPassword);
     _credentialProvider = new SimpleCredentialProvider(appId, appPassword);
 }
Beispiel #3
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_2);

            // add background task queue
            services.AddSingleton <IBackgroundTaskQueue, BackgroundTaskQueue>();
            services.AddHostedService <QueuedHostedService>();

            // Load the connected services from .bot file.
            var botFilePath   = Configuration.GetSection("botFilePath")?.Value;
            var botFileSecret = Configuration.GetSection("botFileSecret")?.Value;
            var botConfig     = BotConfiguration.Load(botFilePath ?? throw new Exception("Please configure your bot file path in appsettings.json."), botFileSecret);

            // Use Application Insights
            services.AddBotApplicationInsights(botConfig);

            // Initializes your bot service clients and adds a singleton that your Bot can access through dependency injection.
            var languageModels            = Configuration.GetSection("languageModels").Get <Dictionary <string, Dictionary <string, string> > >();
            var skills                    = Configuration.GetSection("skills").Get <List <SkillDefinition> >();
            List <SkillEvent> skillEvents = null;
            var skillEventsConfig         = Configuration.GetSection(SkillEventsConfigName);

            if (skillEventsConfig != null)
            {
                skillEvents = skillEventsConfig.Get <List <SkillEvent> >();
            }

            var connectedServices = new BotServices(botConfig, languageModels, skills, skillEvents);

            services.AddSingleton(sp => connectedServices);

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

            // Initialize Bot State
            var cosmosDbService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.CosmosDB) ?? throw new Exception("Please configure your CosmosDb service in your .bot file.");
            var cosmosDb        = cosmosDbService as CosmosDbService;
            var cosmosOptions   = new CosmosDbStorageOptions()
            {
                CosmosDBEndpoint = new Uri(cosmosDb.Endpoint),
                AuthKey          = cosmosDb.Key,
                CollectionId     = cosmosDb.Collection,
                DatabaseId       = cosmosDb.Database,
            };
            var dataStore         = new CosmosDbStorage(cosmosOptions);
            var userState         = new UserState(dataStore);
            var conversationState = new ConversationState(dataStore);
            var proactiveState    = new ProactiveState(dataStore);

            services.AddSingleton(dataStore);
            services.AddSingleton(userState);
            services.AddSingleton(conversationState);
            services.AddSingleton(proactiveState);
            services.AddSingleton(new BotStateSet(userState, conversationState));

            var environment = _isProduction ? "production" : "development";
            var service     = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.Endpoint && s.Name == environment);

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

            services.AddSingleton(endpointService);

            services.AddSingleton <IBot, VirtualAssistant>();

            // Add the http adapter to enable MVC style bot API
            services.AddSingleton <IBotFrameworkHttpAdapter>((sp) =>
            {
                var credentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);

                var telemetryClient         = sp.GetService <IBotTelemetryClient>();
                var botFrameworkHttpAdapter = new BotFrameworkHttpAdapter(credentialProvider)
                {
                    OnTurnError = async(context, exception) =>
                    {
                        CultureInfo.CurrentUICulture = new CultureInfo(context.Activity.Locale);
                        var responseBuilder          = new MainResponses();
                        await responseBuilder.ReplyWith(context, MainResponses.ResponseIds.Error);
                        await context.SendActivityAsync(new Activity(type: ActivityTypes.Trace, text: $"Virtual Assistant Error: {exception.Message} | {exception.StackTrace}"));
                        telemetryClient.TrackExceptionEx(exception, context.Activity);
                    }
                };

                // Telemetry Middleware (logs activity messages in Application Insights)
                var appInsightsLogger = new TelemetryLoggerMiddleware(telemetryClient);
                botFrameworkHttpAdapter.Use(appInsightsLogger);

                // Transcript Middleware (saves conversation history in a standard format)
                var storageService       = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.BlobStorage) ?? throw new Exception("Please configure your Azure Storage service in your .bot file.");
                var blobStorage          = storageService as BlobStorageService;
                var transcriptStore      = new AzureBlobTranscriptStore(blobStorage.ConnectionString, blobStorage.Container);
                var transcriptMiddleware = new TranscriptLoggerMiddleware(transcriptStore);
                botFrameworkHttpAdapter.Use(transcriptMiddleware);

                // Typing Middleware (automatically shows typing when the bot is responding/working)
                botFrameworkHttpAdapter.Use(new ShowTypingMiddleware());
                botFrameworkHttpAdapter.Use(new SetLocaleMiddleware(defaultLocale ?? "en-us"));
                botFrameworkHttpAdapter.Use(new EventDebuggerMiddleware());
                botFrameworkHttpAdapter.Use(new AutoSaveStateMiddleware(userState, conversationState));
                botFrameworkHttpAdapter.Use(new ProactiveStateMiddleware(proactiveState));

                return(botFrameworkHttpAdapter);
            });
        }
Beispiel #4
0
 public void SimpleCredentialProvider_Constructor_ThrowsOnNullCredentials()
 {
     var credProvider = new SimpleCredentialProvider(null);
 }
 public BotFrameworkAdapter(IConfiguration configuration, HttpClient httpClient = null) : base()
 {
     _httpClient         = httpClient ?? new HttpClient();
     _credentialProvider = new ConfigurationCredentialProvider(configuration);
     _credentials        = new MicrosoftAppCredentials(_credentialProvider.AppId, _credentialProvider.Password);
 }
Beispiel #6
0
        /// <summary>
        /// Configure the DI container for the application.
        /// </summary>
        /// <param name="services">The stub DI container.</param>
        /// <remarks>
        /// This is the composition root of the application.
        /// For more information see: https://go.microsoft.com/fwlink/?LinkID=398940.
        /// </remarks>
        public void ConfigureServices(IServiceCollection services)
        {
            // Don't remap the claims
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            // Application Insights
            services.AddApplicationInsightsTelemetry();

            // Authentication - Identity.Web, Graph SDK
            services
            .AddMicrosoftIdentityWebApiAuthentication(this.configuration)
            .EnableTokenAcquisitionToCallDownstreamApi()
            .AddMicrosoftGraph(this.configuration.GetSection("GraphApiBeta"))
            .AddInMemoryTokenCaches();

            // Authorization
            services.AddCustomAuthorization(this.configuration);

            // Controllers
            services.AddControllers()
            .AddNewtonsoftJson(options =>
                               options.SerializerSettings.Converters
                               .Add(new StringEnumConverter(new DefaultNamingStrategy(), false)));

            services.AddScoped <ErrorResponseFilterAttribute>();

            // Localization
            services.AddResources(this.configuration);

            // Register the Swagger generater.
            services.AddSwaggerGen(configuration =>
            {
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.XML";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                configuration.IncludeXmlComments(xmlPath);
            });

            // Bot dependencies
            var appId         = this.configuration.GetValue <string>("AzureAd:ClientId");
            var baseUrl       = this.configuration.GetValue <string>("BaseUrl");
            var tenantId      = this.configuration.GetValue <string>("AzureAd:TenantId");
            var botName       = this.configuration.GetValue <string>("TeamsBot:AppName");
            var botAppId      = this.configuration.GetValue <string>("TeamsBot:AppId");
            var manifestAppId = this.configuration.GetValue <string>("TeamsBot:ManifestAppid");
            var botCertName   = this.configuration.GetValue <string>("TeamsBot:KeyVaultCertificateName");

            var appSettings = new AppSettings
            {
                BaseUrl            = baseUrl,
                GraphAppId         = appId,
                TenantId           = tenantId,
                BotName            = botName,
                BotAppId           = botAppId,
                BotCertificateName = botCertName,
                ManifestAppId      = manifestAppId,
            };

            var credentialProvider = new SimpleCredentialProvider()
            {
                AppId = botAppId,
            };

            services.AddSingleton <IAppSettings>(appSettings);
            services.AddSingleton <ICredentialProvider>(credentialProvider);
            services.AddTransient <BotAuthMiddleware>();
            services.AddTransient <IUrlProvider, UrlProvider>();
            services.AddTransient <IQBotTeamInfo, QBotTeamInfo>();
            services.AddTransient <IBot, BotActivityHandler>();
            services.AddTransient <BotFrameworkHttpAdapter, BotHttpAdapter>();

            // Infrastructure
            services.AddSqlServerStorage(this.configuration);
            services.AddTeamsServices();
            services.AddQnAService(this.configuration);
            services.AddBackgroundServices(this.configuration);
            services.AddSecretsProvider(this.configuration);

            // Domain
            services.AddDomainServices();

            // SPA
            services.Configure <SpaHostConfiguration>(opts =>
            {
                opts.ApplicationInsightsInstrumentationKey = this.configuration.GetValue <string>("ApplicationInsights:InstrumentationKey");
                opts.BotAppName = this.configuration.GetValue <string>("TeamsBot:AppName");
            });

            // In production, the React files will be served from this directory
            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });
        }
 public BotFrameworkAdapter(string appId, string appPassword) : base()
 {
     _credentials        = new MicrosoftAppCredentials(appId, appPassword);
     _credentialProvider = new SimpleCredentialProvider(appId, appPassword);
 }
 public BotFrameworkAdapter(IConfiguration configuration) : base()
 {
     _credentialProvider = new ConfigurationCredentialProvider(configuration);
     _credentials        = new MicrosoftAppCredentials(this._credentialProvider.AppId, _credentialProvider.Password);
 }
Beispiel #9
0
 public MessagesController(IConfiguration configuration)
 {
     this.credentials = new ConfigurationCredentialProvider(configuration);
     httpClient       = new HttpClient();
 }
        /// <summary>
        /// Configure the composition root for the application.
        /// </summary>
        /// <param name="services">The stub composition root.</param>
        /// <remarks>
        /// For more information see: https://go.microsoft.com/fwlink/?LinkID=398940.
        /// </remarks>
#pragma warning disable CA1506 // Composition root expected to have coupling with many components.
        public void ConfigureServices(IServiceCollection services)
        {
            string appId       = this.configuration.GetValue <string>("App:Id");
            string appPassword = this.configuration.GetValue <string>("App:Password");

            ICredentialProvider credentialProvider = new SimpleCredentialProvider(
                appId: appId,
                password: appPassword);

            services.Configure <RedditOptions>(options =>
            {
                options.BotFrameworkConnectionName = this.configuration.GetValue <string>("BotFramework:ConnectionName");
                options.ClientUserAgent            = this.configuration.GetValue <string>("UserAgent");
                options.AppId       = this.configuration.GetValue <string>("Reddit:AppId");
                options.AppPassword = this.configuration.GetValue <string>("Reddit:AppPassword");
            });

            services
            .AddApplicationInsightsTelemetry();

            services.Configure <ApplicationInsightsServiceOptions>(options =>
            {
                options.InstrumentationKey = this.configuration.GetValue <string>("ApplicationInsights:InstrumentationKey");
            });

            services
            .AddApplicationInsightsTelemetry();

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

            services
            .AddSingleton(credentialProvider);

            services
            .AddTransient <IBotFrameworkHttpAdapter, BotFrameworkHttpAdapter>();

            services
            .AddHttpClient <IRedditAuthenticator, RedditAppAuthenticator>();

            services
            .AddTransient <IBot, RLUTeamsActivityHandler>();

            services
            .AddDistributedMemoryCache();

            services
            .AddHttpClient <RedditHttpClient>();

            // Add i8n
            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.Configure <RequestLocalizationOptions>(options =>
            {
                var defaultCulture    = CultureInfo.GetCultureInfo(this.configuration.GetValue <string>("I8n:DefaultCulture"));
                var supportedCultures = this.configuration.GetValue <string>("I8n:SupportedCultures").Split(',')
                                        .Select(culture => CultureInfo.GetCultureInfo(culture))
                                        .ToList();

                options.DefaultRequestCulture = new RequestCulture(defaultCulture);
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;

                options.RequestCultureProviders = new List <IRequestCultureProvider>
                {
                    new BotLocalizationCultureProvider(),
                };
            });
        }