public void ConfigureTranscriptLoggerMiddleware(BotFrameworkHttpAdapter adapter, BotSettings settings) { if (ConfigSectionValid(settings?.BlobStorage?.ConnectionString) && ConfigSectionValid(settings?.BlobStorage?.Container)) { adapter.Use(new TranscriptLoggerMiddleware(new BlobsTranscriptStore(settings?.BlobStorage?.ConnectionString, settings?.BlobStorage?.Container))); } }
public void ConfigureServices(IServiceCollection services) { services.AddCors(o => o.AddPolicy("AllowAllOrigins", builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); })); services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1); services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>(); services.AddSingleton <IBotFrameworkHttpAdapter, BotFrameworkHttpAdapter>((provider) => { var cred = provider.GetRequiredService <ICredentialProvider>(); var adpt = new BotFrameworkHttpAdapter(cred); adpt.Use(new ConversationSynchronizationMiddleware(new SampleUserConversationsStaticStorageProvider(), adpt, _configuration)); return(adpt); }); services.AddSingleton <IStorage, MemoryStorage>(); services.AddSingleton <UserState>(); services.AddSingleton <ConversationState>(); services.AddSingleton <RootDialog>(); services.AddTransient <IBot, MainBot <RootDialog> >(); }
/// <summary> /// Initializes a new instance of the <see cref="WebSocketEnabledHttpAdapter"/> class. /// An adapter meant for subclassing and injecting custom implementation of BotFrameworkHttpAdapter for handling Http requests. /// Throws <see cref="ArgumentNullException"/> if configure is null. /// </summary> /// <param name="configuration">The configuration for the adapter to use.</param> /// <param name="botFrameworkHttpAdapter">Optional http adapter to use for non-streaming extensions requests.</param> /// <param name="credentialProvider">Optional credential provider.</param> /// <param name="channelProvider">Optional channel provider.</param> /// <param name="loggerFactory">Optional logger factory.</param> protected WebSocketEnabledHttpAdapter(IConfiguration configuration, IBotFrameworkHttpAdapter botFrameworkHttpAdapter = null, ICredentialProvider credentialProvider = null, IChannelProvider channelProvider = null, ILoggerFactory loggerFactory = null) { if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } var openIdEndpoint = configuration.GetSection(AuthenticationConstants.BotOpenIdMetadataKey)?.Value; if (!string.IsNullOrEmpty(openIdEndpoint)) { // If an open ID endpoint is configured, use it. This enables Public and Sovereign clouds that require open id. ChannelValidation.OpenIdMetadataUrl = openIdEndpoint; GovernmentChannelValidation.OpenIdMetadataUrl = openIdEndpoint; } credentialProvider = credentialProvider ?? new ConfigurationCredentialProvider(configuration); channelProvider = channelProvider ?? new ConfigurationChannelProvider(configuration); _botFrameworkHttpAdapter = _botFrameworkHttpAdapter ?? new BotFrameworkHttpAdapter(credentialProvider, channelProvider, loggerFactory?.CreateLogger <BotFrameworkHttpAdapter>()); _webSocketConnector = new WebSocketConnector(credentialProvider, channelProvider); _ensureMiddlewareSet = new Lazy <bool>(() => { middlewares.ForEach(mw => _botFrameworkHttpAdapter.Use(mw)); _botFrameworkHttpAdapter.OnTurnError = OnTurnError; return(true); }); }
public IBotFrameworkHttpAdapter BindToAdapter(IServiceProvider e) { var ae = new BotFrameworkHttpAdapter(e.GetService <ICredentialProvider>()); ae.Use(new ShowTypingMiddleware(500, 2000)); return((IBotFrameworkHttpAdapter)ae); }
public BuggyAdapterBase(ICredentialProvider credentialProvider = null, IChannelProvider channelProvider = null, ILoggerFactory loggerFactory = null) { _botFrameworkHttpAdapter = new BotFrameworkHttpAdapter(credentialProvider, channelProvider, loggerFactory?.CreateLogger <BotFrameworkHttpAdapter>()); _ensureMiddlewareSet = new Lazy <bool>(() => { _botFrameworkHttpAdapter.Use(base.MiddlewareSet); return(true); }); }
public void ConfigureTranscriptLoggerMiddleware(BotFrameworkHttpAdapter adapter, BotSettings settings) { if (settings.Feature.UseTranscriptLoggerMiddleware) { if (!string.IsNullOrEmpty(settings.BlobStorage.ConnectionString) && !string.IsNullOrEmpty(settings.BlobStorage.Container)) { adapter.Use(new TranscriptLoggerMiddleware(new AzureBlobTranscriptStore(settings.BlobStorage.ConnectionString, settings.BlobStorage.Container))); } } }
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 ?? @".\automotiveskill.bot", 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")?.Get <Dictionary <string, object> >(); var supportedProviders = Configuration.GetSection("SupportedProviders")?.Get <string[]>(); var languageModels = Configuration.GetSection("languageModels").Get <Dictionary <string, Dictionary <string, string> > >(); var connectedServices = new SkillConfiguration(botConfig, languageModels, supportedProviders, parameters, configuration); services.AddSingleton <SkillConfigurationBase>(sp => connectedServices); var supportedLanguages = languageModels.Select(l => l.Key).ToArray(); var responseManager = new ResponseManager( supportedLanguages, new AutomotiveSkillMainResponses(), new AutomotiveSkillSharedResponses(), new VehicleSettingsResponses()); // Register bot responses for all supported languages. services.AddSingleton(sp => responseManager); // 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); // Initialize service client services.AddSingleton <IServiceManager, ServiceManager>(); // HttpContext required for path resolution services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); // Add the bot services.AddSingleton <IBot, AutomotiveSkill>(); // Add the http adapter to enable MVC style bot API services.AddTransient <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(responseManager.GetResponse(AutomotiveSkillSharedResponses.ErrorMessage)); await context.SendActivityAsync(new Activity(type: ActivityTypes.Trace, text: $"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); }); }
// 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); services.AddSingleton <IConfiguration>(this.Configuration); // Create the credential provider to be used with the Bot Framework Adapter. services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>(); services.AddSingleton <InspectionMiddleware>(); // Load settings var settings = new BotSettings(); Configuration.Bind(settings); IStorage storage = null; // Configure storage for deployment if (!string.IsNullOrEmpty(settings.CosmosDb.AuthKey)) { storage = new CosmosDbStorage(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 inspectionState = new InspectionState(storage); // Configure telemetry services.AddApplicationInsightsTelemetry(); var telemetryClient = new BotTelemetryClient(new TelemetryClient()); services.AddSingleton <IBotTelemetryClient>(telemetryClient); services.AddBotApplicationInsights(telemetryClient); var botFile = Configuration.GetSection("bot").Get <string>(); TypeFactory.Configuration = this.Configuration; // manage all bot resources var resourceExplorer = new ResourceExplorer().AddFolder(botFile); var credentials = new MicrosoftAppCredentials(this.Configuration["MicrosoftAppId"], this.Configuration["MicrosoftAppPassword"]); services.AddSingleton <IBotFrameworkHttpAdapter, BotFrameworkHttpAdapter>((s) => { var adapter = new BotFrameworkHttpAdapter(new ConfigurationCredentialProvider(this.Configuration)); adapter .UseStorage(storage) .UseState(userState, conversationState) .UseAdaptiveDialogs() .UseResourceExplorer(resourceExplorer) .UseLanguageGeneration(resourceExplorer, "common.lg") .Use(new RegisterClassMiddleware <IConfiguration>(Configuration)) .Use(new InspectionMiddleware(inspectionState, userState, conversationState, credentials)); 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); telemetryClient.TrackException(new Exception("Exceptions: " + exception.Message)); await conversationState.ClearStateAsync(turnContext).ConfigureAwait(false); await conversationState.SaveChangesAsync(turnContext).ConfigureAwait(false); }; return(adapter); }); services.AddSingleton <IBot, ComposerBot>((sp) => new ComposerBot("Main.dialog", conversationState, userState, resourceExplorer, DebugSupport.SourceMap, telemetryClient)); }
// 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 CosmosDbStorage(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 botFile = Configuration.GetSection("bot").Get <string>(); // manage all bot resources var resourceExplorer = new ResourceExplorer().AddFolder(botFile); 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, ComposerBot>(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => options.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddSingleton <IConfiguration>(this.Configuration); // Create the credential provider to be used with the Bot Framework Adapter. services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>(); // Load settings var settings = new BotSettings(); Configuration.Bind(settings); IStorage storage = null; // Configure storage for deployment if (!string.IsNullOrEmpty(settings.CosmosDb.AuthKey)) { storage = new CosmosDbStorage(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 botFile = Configuration.GetSection("bot").Get <string>(); // manage all bot resources var resourceExplorer = new ResourceExplorer().AddFolder(botFile); var credentials = new MicrosoftAppCredentials(this.Configuration["MicrosoftAppId"], this.Configuration["MicrosoftAppPassword"]); 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, ComposerBot>((sp) => new ComposerBot("Main.dialog", conversationState, userState, resourceExplorer, DebugSupport.SourceMap)); }
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, 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) 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); }); }