Ejemplo n.º 1
0
        public void Connection_Policy_Configurator_Should_Be_Called_If_Present()
        {
            var wasCalled = false;

            var optionsWithConfigurator = new CosmosDbStorageOptions
            {
                AuthKey          = "test",
                CollectionId     = "testId",
                DatabaseId       = "testDb",
                CosmosDBEndpoint = new Uri("https://test.com"),

                // Make sure the Callback is called.
                ConnectionPolicyConfigurator = (ConnectionPolicy p) => wasCalled = true,
            };

            var storage = new CosmosDbStorage(optionsWithConfigurator);

            Assert.True(wasCalled, "The Connection Policy Configurator was not called.");
        }
Ejemplo n.º 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var config = new CosmosDbStorageOptions
            {
                AuthKey          = CosmosDBKey,
                CollectionId     = CosmosDBCollectionName,
                CosmosDBEndpoint = new Uri(CosmosServiceEndpoint),
                DatabaseId       = CosmosDBDatabaseName,
            };


            var transcriptMiddleware = new TranscriptLoggerMiddleware(new CosmosTranscriptStore(config));

            services.AddBot <CustomPromptBot>(options =>
            {
                var middleware = options.Middleware;
                middleware.Add(transcriptMiddleware);
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddSingleton(transcriptMiddleware);
            // 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.)
            services.AddSingleton <IStorage, MemoryStorage>();

            // Create the User state.
            services.AddSingleton <UserState>();

            // Create the Conversation state.
            services.AddSingleton <ConversationState>();

            // Create the bot as a transient. In this case the ASP Controller is expecting an IBot.
            services.AddTransient <IBot, CustomPromptBot>();
        }
Ejemplo n.º 3
0
 public CosmosTranscriptStore(CosmosDbStorageOptions config)
 {
     _storage = new CosmosDbStorage(config);
 }
Ejemplo n.º 4
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            var builder = new ContainerBuilder();

            services.AddHttpClient();

            var endpointUrl  = Configuration.GetValue <string>("cosmosDB:endpointUrl");
            var primaryKey   = Configuration.GetValue <string>("cosmosDB:primaryKey");
            var databaseName = Configuration.GetValue <string>("cosmosDB:databaseName");

            IStorage dataStore;
            bool     isProduction = true;

#if DEBUG
            isProduction = false;
#endif

            if (isProduction)
            {
                var cosmosDbOptions = new CosmosDbStorageOptions();
                cosmosDbOptions.CosmosDBEndpoint = new Uri(endpointUrl);
                cosmosDbOptions.AuthKey          = primaryKey;
                cosmosDbOptions.DatabaseId       = databaseName;
                cosmosDbOptions.CollectionId     = databaseName;
                dataStore = new CosmosDbStorage(cosmosDbOptions);

                builder.RegisterType <CosmosDBStoryStorage>()
                .As <IStoryStorage>()
                .WithParameter("endpointUrl", endpointUrl)
                .WithParameter("primaryKey", primaryKey)
                .WithParameter("databaseName", databaseName)
                .InstancePerLifetimeScope();

                builder.RegisterType <CosmosDBUserStorage>()
                .As <IUserStorage>()
                .WithParameter("endpointUrl", endpointUrl)
                .WithParameter("primaryKey", primaryKey)
                .WithParameter("databaseName", databaseName)
                .InstancePerLifetimeScope();

                builder.RegisterType <CosmosDBUserStoryNotificationStorage>()
                .As <IUserStoryNotificationStorage>()
                .WithParameter("endpointUrl", endpointUrl)
                .WithParameter("primaryKey", primaryKey)
                .WithParameter("databaseName", databaseName)
                .InstancePerLifetimeScope();
            }
            else
            {
                dataStore = new MemoryStorage();

                builder.RegisterType <MemoryStoryStorage>()
                .As <IStoryStorage>()
                .InstancePerLifetimeScope();

                builder.RegisterType <MemoryUserStorage>()
                .As <IUserStorage>()
                .InstancePerLifetimeScope();

                builder.RegisterType <MemoryUserStoryNotificationStorage>()
                .As <IUserStoryNotificationStorage>()
                .InstancePerLifetimeScope();
            }

            var hNTopStoriesUrl = Configuration.GetValue <string>("hNTopStoriesUrl");

            builder.RegisterType <HNStoryProvider>()
            .As <IHNStoryProvider>()
            .WithParameter("hNTopStoriesUrl", hNTopStoriesUrl)
            .InstancePerLifetimeScope();

            builder.RegisterType <UserUnreadStorySender>()
            .As <IUserUnreadStorySender>()
            .InstancePerLifetimeScope();

            builder.RegisterType <StoryUpdater>()
            .As <IStoryUpdater>()
            .InstancePerLifetimeScope();

            builder.RegisterType <UserMessageSender>()
            .As <IUserMessageSender>()
            .InstancePerLifetimeScope();

            var cleanStorageCron             = Configuration.GetValue <string>("scheduler:timers:cleanStorageCron");
            var sendUnreadStoriesToUsersCron = Configuration.GetValue <string>("scheduler:timers:sendUnreadStoriesToUsersCron");
            var updateStoriesCron            = Configuration.GetValue <string>("scheduler:timers:updateStoriesCron");

            builder.RegisterType <UserStoryScheduler>()
            .As <IUserStoryScheduler>()
            .WithParameter("cleanStorageCron", cleanStorageCron)
            .WithParameter("sendUnreadStoriesToUsersCron", sendUnreadStoriesToUsersCron)
            .WithParameter("updateStoriesCron", updateStoriesCron)
            .InstancePerLifetimeScope();

            builder.RegisterType <CleanStorageJob>();
            builder.RegisterType <SendUnreadStoriesToUsersJob>();
            builder.RegisterType <UpdateStoriesJob>();

            services.AddBot <HNSkypeBot>(options =>
            {
                var secretKey   = Configuration.GetSection("botFileSecret")?.Value;
                var botFilePath = Configuration.GetSection("botFilePath")?.Value;

                var botConfig = BotConfiguration.Load(botFilePath ?? @".\BotConfiguration.bot", secretKey);
                services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot config file could not be loaded. ({botConfig})"));

                var environment = _isProduction ? "production" : "development";
                var service     = botConfig.Services.Where(s => s.Type == "endpoint" && s.Name == environment).FirstOrDefault();
                if (!(service is EndpointService endpointService))
                {
                    throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{environment}'.");
                }

                options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);

                ILogger logger      = _loggerFactory.CreateLogger <HNSkypeBot>();
                options.OnTurnError = async(context, exception) =>
                {
                    logger.LogError($"Exception caught : {exception}");
                    await context.SendActivityAsync("Sorry, it looks like something went wrong.");
                };

                var conversationState = new ConversationState(dataStore);

                options.State.Add(conversationState);
            });

            services.AddSingleton <UserDataAccessors>(sp =>
            {
                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 conversationState = options.State.OfType <ConversationState>().FirstOrDefault();
                if (conversationState == null)
                {
                    throw new InvalidOperationException("ConversationState must be defined and added before adding conversation-scoped state accessors.");
                }

                var accessors = new UserDataAccessors(conversationState)
                {
                    UserData = conversationState.CreateProperty <UserData>(UserDataAccessors.UserDataName),
                };

                return(accessors);
            });

            builder.Populate(services);
            _container = builder.Build();

            return(new AutofacServiceProvider(_container));
        }
Ejemplo n.º 5
0
        public void ConfigureServices(IServiceCollection services)
        {
            var secretKey   = Configuration.GetSection("botFileSecret")?.Value;
            var botFilePath = Configuration.GetSection("botFilePath")?.Value;

            if (!File.Exists(botFilePath))
            {
                throw new FileNotFoundException($"The .bot configuration file was not found. botFilePath: {botFilePath}");
            }

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

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

            services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot configuration file could not be loaded. botFilePath: {botFilePath}"));

            // Add BotServices singleton.
            // Create the connected services from .bot file.
            services.AddSingleton(sp => new BotServices(botConfig));

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

            if (service == null && _isProduction)
            {
                // Attempt to load development environment
                service = botConfig.Services.FirstOrDefault(s => s.Type == "endpoint" && s.Name == "development");
            }

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

            // Use persistent storage and create state management objects.
            var cosmosSettings         = Configuration.GetSection("CosmosDB");
            var cosmosDbStorageOptions = new CosmosDbStorageOptions
            {
                DatabaseId       = cosmosSettings["DatabaseID"],
                CollectionId     = cosmosSettings["CollectionID"],
                CosmosDBEndpoint = new Uri(cosmosSettings["EndpointUri"]),
                AuthKey          = cosmosSettings["AuthenticationKey"]
            };

            services.AddSingleton(cosmosDbStorageOptions);

            IStorage dataStore = new CosmosDbStorage(cosmosDbStorageOptions);

            // Register state models
            var conversationState = new ConversationState(dataStore);

            services.AddSingleton(conversationState);

            var userState = new UserState(dataStore);

            services.AddSingleton(userState);

            // Register repositories
            services.AddSingleton(new OrderRepository(cosmosDbStorageOptions));
            services.AddSingleton <CardConfigurationRepository>();

            // Register services
            services.AddSingleton <ICardConfigurationService, CardConfigurationService>();
            services.AddSingleton <ICardService, CardService>();

            services.AddBot <WomanDayBotBot>(options =>
            {
                options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);

                options.OnTurnError = async(context, exception) =>
                {
                    _logger.LogError(exception, "Unhandled exception");
                    await context.SendActivityAsync("Черт, эти программисты опять налажали! Неведома ошибка");
                };
            });

            services.AddSingleton <WomanDayBotAccessors>(sp =>
            {
                return(new WomanDayBotAccessors(userState, conversationState)
                {
                    UserDataAccessor = userState.CreateProperty <UserData>("WomanDayBot.UserData"),
                    DialogStateAccessor = conversationState.CreateProperty <DialogState>("WomanDayBot.DialogState")
                });
            });

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

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });
        }
        /// <summary>
        /// Enables to attach Azure Cosmos DB to Hangfire
        /// </summary>
        /// <param name="configuration">The IGlobalConfiguration object</param>
        /// <param name="url">The url string to Cosmos Database</param>
        /// <param name="authSecret">The secret key for the Cosmos Database</param>
        /// <param name="database">The name of the database to connect with</param>
        /// <param name="collection">The name of the collection on the database</param>
        /// <param name="option"></param>
        /// <param name="storageOptions">The CosmosDbStorage object to override any of the options</param>
        /// <returns></returns>
        public static IGlobalConfiguration <CosmosDbStorage> UseAzureCosmosDbStorage(this IGlobalConfiguration configuration, string url, string authSecret, string database, string collection, CosmosClientOptions option = null, CosmosDbStorageOptions storageOptions = null)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException(nameof(url));
            }
            if (string.IsNullOrEmpty(authSecret))
            {
                throw new ArgumentNullException(nameof(authSecret));
            }

            CosmosDbStorage storage = new CosmosDbStorage(url, authSecret, database, collection, option, storageOptions);

            return(configuration.UseStorage(storage));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BotServices"/> class.
        /// </summary>
        /// <param name="botConfiguration">The <see cref="BotConfiguration"/> instance for the bot.</param>
        public BotServices(BotConfiguration botConfiguration, List <SkillDefinition> skills)
        {
            foreach (var service in botConfiguration.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.AppInsights:
                {
                    var appInsights     = service as AppInsightsService;
                    var telemetryConfig = new TelemetryConfiguration(appInsights.InstrumentationKey);
                    TelemetryClient = new TelemetryClient(telemetryConfig);
                    break;
                }

                case ServiceTypes.Dispatch:
                {
                    var dispatch    = service as DispatchService;
                    var dispatchApp = new LuisApplication(dispatch.AppId, dispatch.SubscriptionKey, dispatch.GetEndpoint());
                    DispatchRecognizer = new TelemetryLuisRecognizer(dispatchApp);
                    break;
                }

                case ServiceTypes.Luis:
                {
                    var luis    = service as LuisService;
                    var luisApp = new LuisApplication(luis.AppId, luis.SubscriptionKey, luis.GetEndpoint());
                    LuisServices.Add(service.Id, new TelemetryLuisRecognizer(luisApp));
                    break;
                }

                case ServiceTypes.QnA:
                {
                    var qna         = service as QnAMakerService;
                    var qnaEndpoint = new QnAMakerEndpoint()
                    {
                        KnowledgeBaseId = qna.KbId,
                        EndpointKey     = qna.EndpointKey,
                        Host            = qna.Hostname,
                    };
                    var qnaMaker = new TelemetryQnAMaker(qnaEndpoint);
                    QnAServices.Add(qna.Id, qnaMaker);
                    break;
                }

                case ServiceTypes.Generic:
                {
                    if (service.Name == "Authentication")
                    {
                        var authentication = service as GenericService;
                        AuthenticationConnections = authentication.Configuration;
                    }

                    break;
                }

                case ServiceTypes.CosmosDB:
                {
                    var cosmos = service as CosmosDbService;

                    CosmosDbOptions = new CosmosDbStorageOptions
                    {
                        AuthKey          = cosmos.Key,
                        CollectionId     = cosmos.Collection,
                        DatabaseId       = cosmos.Database,
                        CosmosDBEndpoint = new Uri(cosmos.Endpoint),
                    };

                    break;
                }
                }
            }

            foreach (var skill in skills)
            {
                var skillConfig = new SkillConfiguration()
                {
                    CosmosDbOptions = CosmosDbOptions,
                    TelemetryClient = TelemetryClient,
                    LuisServices    = LuisServices.Where(l => skill.LuisServiceIds.Contains(l.Key) == true).ToDictionary(l => l.Key, l => l.Value as IRecognizer),
                };

                if (skill.SupportedProviders != null)
                {
                    foreach (var provider in skill.SupportedProviders)
                    {
                        var matches = AuthenticationConnections.Where(x => x.Value == provider);

                        foreach (var match in matches)
                        {
                            skillConfig.AuthenticationConnections.Add(match.Key, match.Value);
                        }
                    }
                }

                foreach (var set in skill.Configuration)
                {
                    skillConfig.Properties.Add(set.Key, set.Value);
                }

                SkillDefinitions.Add(skill);
                SkillConfigurations.Add(skill.Id, skillConfig);
            }
        }
Ejemplo n.º 8
0
Archivo: Startup.cs Proyecto: munip/AI
        public void ConfigureServices(IServiceCollection services)
        {
            // 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);

            // Add the bot with options
            services.AddBot <VirtualAssistant>(options =>
            {
                // Load the connected services from .bot file.
                options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);

                // Telemetry Middleware (logs activity messages in Application Insights)
                var sp = services.BuildServiceProvider();
                var telemetryClient   = sp.GetService <IBotTelemetryClient>();
                var appInsightsLogger = new TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: true);
                options.Middleware.Add(appInsightsLogger);

                // Catches any errors that occur during a conversation turn and logs them to AppInsights.
                options.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);
                };

                // 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);
                options.Middleware.Add(transcriptMiddleware);

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

                //// Translator is an optional component for scenarios when an Assistant needs to work beyond native language support
                // var translatorKey = Configuration.GetValue<string>("translatorKey");
                // if (!string.IsNullOrEmpty(translatorKey))
                // {
                //     options.Middleware.Add(new TranslationMiddleware(new string[] { "en", "fr", "it", "de", "es" }, translatorKey, false));
                // }
                // else
                // {
                //     throw new InvalidOperationException("Microsoft Text Translation API key is missing. Please add your translation key to the 'translatorKey' setting.");
                // }
            });
        }
Ejemplo n.º 9
0
        public void ConfigureServices(IServiceCollection services)
        {
            // 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 ?? @".\PointOfInterestSkill.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")?.GetChildren()?.ToDictionary(x => x.Key, y => y.Value as object);
            var languageModels = Configuration.GetSection("languageModels").Get<Dictionary<string, Dictionary<string, string>>>();
            var connectedServices = new SkillConfiguration(botConfig, languageModels, null, parameters, configuration);
            services.AddSingleton<SkillConfigurationBase>(sp => connectedServices);

            var supportedLanguages = languageModels.Select(l => l.Key).ToArray();
            var responses = new IResponseIdCollection[]
            {
                new CancelRouteResponses(),
                new FindPointOfInterestResponses(),
                new POIMainResponses(),
                new RouteResponses(),
                new POISharedResponses(),
            };

            var responseManager = new ResponseManager(responses, supportedLanguages);

            // 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);

            services.AddSingleton<IServiceManager, ServiceManager>();

            // Add the bot with options
            services.AddBot<PointOfInterestSkill>(options =>
            {
                options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);

                // Telemetry Middleware (logs activity messages in Application Insights)
                var sp = services.BuildServiceProvider();
                var telemetryClient = sp.GetService<IBotTelemetryClient>();
                var appInsightsLogger = new TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: true);
                options.Middleware.Add(appInsightsLogger);

                // Catches any errors that occur during a conversation turn and logs them to AppInsights.
                options.OnTurnError = async (context, exception) =>
                {
                    CultureInfo.CurrentUICulture = new CultureInfo(context.Activity.Locale);
                    await context.SendActivityAsync(responseManager.GetResponse(POISharedResponses.PointOfInterestErrorMessage));
                    await context.SendActivityAsync(new Activity(type: ActivityTypes.Trace, text: $"PointOfInterestSkill Error: {exception.Message} | {exception.StackTrace}"));
                    telemetryClient.TrackExceptionEx(exception, context.Activity);
                };

                // 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);
                options.Middleware.Add(transcriptMiddleware);

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

                options.Middleware.Add(new EventDebuggerMiddleware());
                options.Middleware.Add(new AutoSaveStateMiddleware(userState, conversationState));
            });
        }
Ejemplo n.º 10
0
 // We need access to Settings in order to prime the CosmosDb Storage and avoid having to store in local state
 public SkillDialog(CosmosDbStorageOptions cosmosDbOptions, TelemetryClient telemetryClient)
     : base(nameof(SkillDialog))
 {
     _cosmosDbOptions = cosmosDbOptions;
     _telemetryClient = telemetryClient;
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BotServices"/> class.
        /// </summary>
        /// <param name="botConfiguration">The <see cref="BotConfiguration"/> instance for the bot.</param>
        public BotServices(BotConfiguration botConfiguration)
        {
            foreach (var service in botConfiguration.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.AppInsights:
                {
                    var appInsights     = service as AppInsightsService;
                    var telemetryConfig = new TelemetryConfiguration(appInsights.InstrumentationKey);
                    TelemetryClient = new TelemetryClient(telemetryConfig);
                    break;
                }

                case ServiceTypes.Dispatch:
                {
                    var dispatch    = service as DispatchService;
                    var dispatchApp = new LuisApplication(dispatch.AppId, dispatch.SubscriptionKey, dispatch.GetEndpoint());
                    DispatchRecognizer = new TelemetryLuisRecognizer(dispatchApp);
                    break;
                }

                case ServiceTypes.Luis:
                {
                    var luis    = service as LuisService;
                    var luisApp = new LuisApplication(luis.AppId, luis.SubscriptionKey, luis.GetEndpoint());
                    LuisServices.Add(service.Id, new TelemetryLuisRecognizer(luisApp));
                    break;
                }

                case ServiceTypes.QnA:
                {
                    var qna         = service as QnAMakerService;
                    var qnaEndpoint = new QnAMakerEndpoint()
                    {
                        KnowledgeBaseId = qna.KbId,
                        EndpointKey     = qna.EndpointKey,
                        Host            = qna.Hostname,
                    };
                    var qnaMaker = new TelemetryQnAMaker(qnaEndpoint);
                    QnAServices.Add(qna.Id, qnaMaker);
                    break;
                }

                case ServiceTypes.Generic:
                {
                    if (service.Name == "Authentication")
                    {
                        var authentication = service as GenericService;

                        if (!string.IsNullOrEmpty(authentication.Configuration["Azure Active Directory v2"]))
                        {
                            AuthConnectionName = authentication.Configuration["Azure Active Directory v2"];
                        }
                    }

                    break;
                }

                case ServiceTypes.CosmosDB:
                {
                    var cosmos = service as CosmosDbService;

                    CosmosDbOptions = new CosmosDbStorageOptions
                    {
                        AuthKey          = cosmos.Key,
                        CollectionId     = cosmos.Collection,
                        DatabaseId       = cosmos.Database,
                        CosmosDBEndpoint = new Uri(cosmos.Endpoint),
                    };

                    break;
                }
                }
            }
        }
Ejemplo n.º 12
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, 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);
            });
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BotServices"/> class.
        /// </summary>
        /// <param name="botConfiguration">The <see cref="BotConfiguration"/> instance for the bot.</param>
        /// <param name="skills">List of <see cref="SkillDefinition"/> for loading skill configurations.</param>
        /// <param name="languageModels">The locale specifc language model configs for each supported language.</param>
        public BotServices(BotConfiguration botConfiguration, Dictionary <string, Dictionary <string, string> > languageModels, List <SkillDefinition> skills)
        {
            // Create service clients for each service in the .bot file.
            foreach (var service in botConfiguration.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.AppInsights:
                {
                    var appInsights     = service as AppInsightsService;
                    var telemetryConfig = new TelemetryConfiguration(appInsights.InstrumentationKey);
                    TelemetryClient = new TelemetryClient(telemetryConfig);
                    break;
                }

                case ServiceTypes.CosmosDB:
                {
                    var cosmos = service as CosmosDbService;

                    CosmosDbOptions = new CosmosDbStorageOptions
                    {
                        AuthKey          = cosmos.Key,
                        CollectionId     = cosmos.Collection,
                        DatabaseId       = cosmos.Database,
                        CosmosDBEndpoint = new Uri(cosmos.Endpoint),
                    };

                    break;
                }

                case ServiceTypes.Generic:
                {
                    if (service.Name == "Authentication")
                    {
                        var authentication = service as GenericService;
                        AuthenticationConnections = authentication.Configuration;
                    }

                    break;
                }
                }
            }

            // Create locale configuration object for each language config in appsettings.json
            foreach (var language in languageModels)
            {
                var localeConfig = new LocaleConfiguration
                {
                    Locale = language.Key
                };

                var path   = language.Value["botFilePath"];
                var secret = language.Value["botFileSecret"];
                var config = BotConfiguration.Load(path, !string.IsNullOrEmpty(secret) ? secret : null);

                foreach (var service in config.Services)
                {
                    switch (service.Type)
                    {
                    case ServiceTypes.Dispatch:
                    {
                        var dispatch    = service as DispatchService;
                        var dispatchApp = new LuisApplication(dispatch.AppId, dispatch.SubscriptionKey, dispatch.GetEndpoint());
                        localeConfig.DispatchRecognizer = new TelemetryLuisRecognizer(dispatchApp);
                        break;
                    }

                    case ServiceTypes.Luis:
                    {
                        var luis    = service as LuisService;
                        var luisApp = new LuisApplication(luis.AppId, luis.SubscriptionKey, luis.GetEndpoint());
                        localeConfig.LuisServices.Add(service.Id, new TelemetryLuisRecognizer(luisApp));
                        break;
                    }

                    case ServiceTypes.QnA:
                    {
                        var qna         = service as QnAMakerService;
                        var qnaEndpoint = new QnAMakerEndpoint()
                        {
                            KnowledgeBaseId = qna.KbId,
                            EndpointKey     = qna.EndpointKey,
                            Host            = qna.Hostname,
                        };
                        var qnaMaker = new TelemetryQnAMaker(qnaEndpoint);
                        localeConfig.QnAServices.Add(qna.Id, qnaMaker);
                        break;
                    }
                    }
                }

                LocaleConfigurations.Add(language.Key, localeConfig);
            }

            // Create a skill configurations for each skill in appsettings.json
            foreach (var skill in skills)
            {
                var skillConfig = new SkillConfiguration()
                {
                    CosmosDbOptions = CosmosDbOptions,
                    TelemetryClient = TelemetryClient,
                };

                foreach (var localeConfig in LocaleConfigurations)
                {
                    skillConfig.LocaleConfigurations.Add(localeConfig.Key, new LocaleConfiguration
                    {
                        LuisServices = localeConfig.Value.LuisServices.Where(l => skill.LuisServiceIds.Contains(l.Key) == true).ToDictionary(l => l.Key, l => l.Value)
                    });
                }

                if (skill.SupportedProviders != null)
                {
                    foreach (var provider in skill.SupportedProviders)
                    {
                        var matches = AuthenticationConnections.Where(x => x.Value == provider);

                        foreach (var match in matches)
                        {
                            skillConfig.AuthenticationConnections.Add(match.Key, match.Value);
                        }
                    }
                }

                foreach (var set in skill.Configuration)
                {
                    skillConfig.Properties.Add(set.Key, set.Value);
                }

                SkillDefinitions.Add(skill);
                SkillConfigurations.Add(skill.Id, skillConfig);
            }
        }
Ejemplo n.º 14
0
Archivo: Startup.cs Proyecto: sueely/AI
        public void ConfigureServices(IServiceCollection services)
        {
            // Load the connected services from .bot file.
            var botFilePath   = Configuration.GetSection("botFilePath")?.Value;
            var botFileSecret = Configuration.GetSection("botFileSecret")?.Value;
            var botConfig     = BotConfiguration.Load(botFilePath ?? @".\CustomAssistant.bot", botFileSecret);

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

            // Initializes your bot service clients and adds a singleton that your Bot can access through dependency injection.
            var skills            = Configuration.GetSection("skills").Get <List <SkillDefinition> >();
            var connectedServices = new BotServices(botConfig, skills);

            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);

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

            // Add the bot with options
            services.AddBot <VirtualAssistant>(options =>
            {
                // Load the connected services from .bot file.
                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}'.");
                }

                options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);

                // Telemetry Middleware (logs activity messages in Application Insights)
                var appInsightsService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.AppInsights) ?? throw new Exception("Please configure your AppInsights connection in your .bot file.");
                var instrumentationKey = (appInsightsService as AppInsightsService).InstrumentationKey;
                var appInsightsLogger  = new TelemetryLoggerMiddleware(instrumentationKey, logUserName: true, logOriginalMessage: true);
                options.Middleware.Add(appInsightsLogger);

                // Catches any errors that occur during a conversation turn and logs them to AppInsights.
                options.OnTurnError = async(context, exception) =>
                {
                    await context.SendActivityAsync("Sorry, it looks like something went wrong. Please try again.");
                    await context.SendActivityAsync(new Activity(type: ActivityTypes.Trace, text: $"Virtual Assistant Error: {exception.Message} | {exception.StackTrace}"));
                    connectedServices.TelemetryClient.TrackException(exception);
                };

                // 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);
                options.Middleware.Add(transcriptMiddleware);

                // Typing Middleware (automatically shows typing when the bot is responding/working)
                options.Middleware.Add(new ShowTypingMiddleware());
                options.Middleware.Add(new SetLocaleMiddleware(defaultLocale ?? "en"));
                options.Middleware.Add(new EventDebuggerMiddleware());
                options.Middleware.Add(new AutoSaveStateMiddleware(userState, conversationState));

                //// Translator is an optional component for scenarios when an Assistant needs to work beyond native language support
                //var translatorKey = Configuration.GetValue<string>("translatorKey");

                //if (!string.IsNullOrEmpty(translatorKey))
                //{
                //    options.Middleware.Add(new TranslationMiddleware(new string[] { "en", "fr", "it", "de", "es" }, translatorKey, false));
                //}
                //else
                //{
                //    throw new InvalidOperationException("Microsoft Text Translation API key is missing. Please add your translation key to the 'translatorKey' setting.");
                //}
            });
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BotServices"/> class.
        /// </summary>
        /// <param name="botConfiguration">The <see cref="BotConfiguration"/> instance for the bot.</param>
        /// <param name="skills">List of <see cref="SkillDefinition"/> for loading skill configurations.</param>
        /// <param name="languageModels">The locale specifc language model configs for each supported language.</param>
        /// <param name="skillEventsConfig">The configuration for skill events.</param>
        public BotServices(BotConfiguration botConfiguration, Dictionary <string, Dictionary <string, string> > languageModels, List <SkillDefinition> skills, List <SkillEvent> skillEventsConfig)
        {
            // Create service clients for each service in the .bot file.
            foreach (var service in botConfiguration.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.AppInsights:
                {
                    var appInsights = (AppInsightsService)service;
                    if (appInsights == null)
                    {
                        throw new InvalidOperationException("The Application Insights is not configured correctly in your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(appInsights.InstrumentationKey))
                    {
                        throw new InvalidOperationException("The Application Insights Instrumentation Key ('instrumentationKey') is required to run this sample.  Please update your '.bot' file.");
                    }

                    var telemetryConfig = new TelemetryConfiguration(appInsights.InstrumentationKey);
                    TelemetryClient = new TelemetryClient(telemetryConfig)
                    {
                        InstrumentationKey = appInsights.InstrumentationKey,
                    };

                    break;
                }

                case ServiceTypes.CosmosDB:
                {
                    var cosmos = service as CosmosDbService;

                    CosmosDbOptions = new CosmosDbStorageOptions
                    {
                        AuthKey          = cosmos.Key,
                        CollectionId     = cosmos.Collection,
                        DatabaseId       = cosmos.Database,
                        CosmosDBEndpoint = new Uri(cosmos.Endpoint),
                    };

                    break;
                }

                case ServiceTypes.Generic:
                {
                    if (service.Name == "Authentication")
                    {
                        var authentication = service as GenericService;
                        AuthenticationConnections = authentication.Configuration;
                    }

                    break;
                }
                }
            }

            // Create locale configuration object for each language config in appsettings.json
            foreach (var language in languageModels)
            {
                if (language.Value.TryGetValue("botFilePath", out var botFilePath) && File.Exists(botFilePath))
                {
                    var botFileSecret = language.Value["botFileSecret"];
                    var config        = BotConfiguration.Load(botFilePath, !string.IsNullOrEmpty(botFileSecret) ? botFileSecret : null);

                    var localeConfig = new LocaleConfiguration
                    {
                        Locale = language.Key
                    };

                    foreach (var service in config.Services)
                    {
                        switch (service.Type)
                        {
                        case ServiceTypes.Dispatch:
                        {
                            var dispatch = service as DispatchService;
                            if (dispatch == null)
                            {
                                throw new InvalidOperationException("The Dispatch service is not configured correctly in your '.bot' file.");
                            }

                            if (string.IsNullOrWhiteSpace(dispatch.AppId))
                            {
                                throw new InvalidOperationException("The Dispatch Luis Model Application Id ('appId') is required to run this sample.  Please update your '.bot' file.");
                            }

                            if (string.IsNullOrWhiteSpace(dispatch.SubscriptionKey))
                            {
                                throw new InvalidOperationException("The Subscription Key ('subscriptionKey') is required to run this sample.  Please update your '.bot' file.");
                            }

                            var dispatchApp = new LuisApplication(dispatch.AppId, dispatch.SubscriptionKey, dispatch.GetEndpoint());
                            localeConfig.DispatchRecognizer = new TelemetryLuisRecognizer(dispatchApp);
                            break;
                        }

                        case ServiceTypes.Luis:
                        {
                            var luis = service as LuisService;
                            if (luis == null)
                            {
                                throw new InvalidOperationException("The Luis service is not configured correctly in your '.bot' file.");
                            }

                            if (string.IsNullOrWhiteSpace(luis.AppId))
                            {
                                throw new InvalidOperationException("The Luis Model Application Id ('appId') is required to run this sample.  Please update your '.bot' file.");
                            }

                            if (string.IsNullOrWhiteSpace(luis.AuthoringKey))
                            {
                                throw new InvalidOperationException("The Luis Authoring Key ('authoringKey') is required to run this sample.  Please update your '.bot' file.");
                            }

                            if (string.IsNullOrWhiteSpace(luis.SubscriptionKey))
                            {
                                throw new InvalidOperationException("The Subscription Key ('subscriptionKey') is required to run this sample.  Please update your '.bot' file.");
                            }

                            if (string.IsNullOrWhiteSpace(luis.Region))
                            {
                                throw new InvalidOperationException("The Region ('region') is required to run this sample.  Please update your '.bot' file.");
                            }

                            var luisApp    = new LuisApplication(luis.AppId, luis.SubscriptionKey, luis.GetEndpoint());
                            var recognizer = new TelemetryLuisRecognizer(luisApp, logPersonalInformation: true);
                            localeConfig.LuisServices.Add(service.Id, recognizer);
                            break;
                        }

                        case ServiceTypes.QnA:
                        {
                            var qna         = service as QnAMakerService;
                            var qnaEndpoint = new QnAMakerEndpoint()
                            {
                                KnowledgeBaseId = qna.KbId,
                                EndpointKey     = qna.EndpointKey,
                                Host            = qna.Hostname,
                            };
                            var qnaMaker = new TelemetryQnAMaker(qnaEndpoint, logPersonalInformation: true);
                            localeConfig.QnAServices.Add(qna.Id, qnaMaker);
                            break;
                        }
                        }
                    }

                    LocaleConfigurations.Add(language.Key, localeConfig);
                }
            }

            // Create a skill configurations for each skill in appsettings.json
            foreach (var skill in skills)
            {
                var skillConfig = new SkillConfiguration()
                {
                    CosmosDbOptions = CosmosDbOptions
                };

                foreach (var localeConfig in LocaleConfigurations)
                {
                    skillConfig.LocaleConfigurations.Add(localeConfig.Key, new LocaleConfiguration
                    {
                        LuisServices = localeConfig.Value.LuisServices.Where(l => skill.LuisServiceIds.Contains(l.Key) == true).ToDictionary(l => l.Key, l => l.Value)
                    });
                }

                if (skill.SupportedProviders != null)
                {
                    foreach (var provider in skill.SupportedProviders)
                    {
                        var matches = AuthenticationConnections.Where(x => x.Value == provider);

                        foreach (var match in matches)
                        {
                            skillConfig.AuthenticationConnections.Add(match.Key, match.Value);
                        }
                    }
                }

                foreach (var set in skill.Configuration)
                {
                    skillConfig.Properties.Add(set.Key, set.Value);
                }

                SkillDefinitions.Add(skill);
                SkillConfigurations.Add(skill.Id, skillConfig);
                SkillEvents = skillEventsConfig != null?skillEventsConfig.ToDictionary(i => i.Event) : null;
            }
        }
Ejemplo n.º 16
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 ?? @".\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);
            });
        }
Ejemplo n.º 17
0
        public void ConfigureServices(IServiceCollection services)
        {
            // Enable distributed tracing.
            services.AddApplicationInsightsTelemetry(o =>
            {
                o.RequestCollectionOptions.EnableW3CDistributedTracing = true;
                o.RequestCollectionOptions.InjectResponseHeaders       = true;
                o.RequestCollectionOptions.TrackExceptions             = true;
            });
            services.AddSingleton <ITelemetryInitializer>(new OperationCorrelationTelemetryInitializer());

            _logger = _loggerFactory.CreateLogger <Startup>();
            _logger.LogInformation($"Configuring services for {nameof(EnterpriseBot)}.  IsProduction: {_isProduction}.");

            // 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."));

            // Initializes your bot service clients and adds a singleton that your Bot can access through dependency injection.
            var connectedServices = new BotServices(botConfig);

            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);

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

            // Add the bot with options
            services.AddBot <EnterpriseBot>(options =>
            {
                _logger.LogInformation($"Adding bot {nameof(EnterpriseBot)}");

                // Load the connected services from .bot file.
                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}'.");
                }

                options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);

                // Telemetry Middleware (logs activity messages in Application Insights)
                var appInsightsService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.AppInsights) ?? throw new Exception("Please configure your AppInsights connection in your .bot file.");
                var instrumentationKey = (appInsightsService as AppInsightsService).InstrumentationKey;
                var appInsightsLogger  = new TelemetryLoggerMiddleware(instrumentationKey, logUserName: true, logOriginalMessage: true);
                options.Middleware.Add(appInsightsLogger);

                // Catches any errors that occur during a conversation turn and logs them to AppInsights.
                options.OnTurnError = async(context, exception) =>
                {
                    await context.SendActivityAsync("Sorry, it looks like something went wrong.");
                    connectedServices.TelemetryClient.TrackException(exception);
                };

                // 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);
                options.Middleware.Add(transcriptMiddleware);

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

                options.Middleware.Add(new AutoSaveStateMiddleware(userState, conversationState));
                _logger.LogTrace($"Bot added successfully.");
            });
        }
Ejemplo n.º 18
0
        public void ConfigureServices(IServiceCollection services)
        {
            // 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."));

            // Get default locale from appsettings.json
            var defaultLocale = Configuration.GetSection("defaultLocale").Get <string>();

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

            // Initializes your bot service clients and adds a singleton that your Bot can access through dependency injection.
            var connectedServices = new BotServices(botConfig);

            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);

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

            // Add the bot with options
            services.AddBot <Kevya>(options =>
            {
                // Load the connected services from .bot file.
                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}'.");
                }

                options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);

                // Telemetry Middleware (logs activity messages in Application Insights)
                var sp = services.BuildServiceProvider();
                var telemetryClient = sp.GetService <IBotTelemetryClient>();

                var appInsightsLogger = new TelemetryLoggerMiddleware(telemetryClient, logUserName: true, logOriginalMessage: true);
                options.Middleware.Add(appInsightsLogger);

                // Catches any errors that occur during a conversation turn and logs them to AppInsights.
                options.OnTurnError = async(context, exception) =>
                {
                    telemetryClient.TrackException(exception);
                    await context.SendActivityAsync(MainStrings.ERROR);
                };

                // 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);
                options.Middleware.Add(transcriptMiddleware);

                // Typing Middleware (automatically shows typing when the bot is responding/working)
                //options.Middleware.Add(new ShowTypingMiddleware());

                // Locale Middleware (sets UI culture based on Activity.Locale)
                options.Middleware.Add(new SetLocaleMiddleware(defaultLocale ?? "en-us"));

                // Autosave State Middleware (saves bot state after each turn)
                options.Middleware.Add(new AutoSaveStateMiddleware(userState, conversationState));
            });
        }
Ejemplo n.º 19
0
Archivo: Startup.cs Proyecto: sueely/AI
        public void ConfigureServices(IServiceCollection services)
        {
            // Load the connected services from .bot file.
            var botFilePath   = Configuration.GetSection("botFilePath")?.Value;
            var botFileSecret = Configuration.GetSection("botFileSecret")?.Value;
            var botConfig     = BotConfiguration.Load(botFilePath ?? @".\CalendarSkill.bot", botFileSecret);

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

            // 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 connectedServices  = new SkillConfiguration(botConfig, 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);

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

            // Initialize calendar service client
            services.AddSingleton <IServiceManager, ServiceManager>();

            // Add the bot with options
            services.AddBot <CalendarSkill>(options =>
            {
                // Load the connected services from .bot file.
                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}'.");
                }

                options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);

                // Telemetry Middleware (logs activity messages in Application Insights)
                var appInsightsService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.AppInsights) ?? throw new Exception("Please configure your AppInsights connection in your .bot file.");
                var instrumentationKey = (appInsightsService as AppInsightsService).InstrumentationKey;
                var appInsightsLogger  = new TelemetryLoggerMiddleware(instrumentationKey, logUserName: true, logOriginalMessage: true);
                options.Middleware.Add(appInsightsLogger);

                // Catches any errors that occur during a conversation turn and logs them to AppInsights.
                options.OnTurnError = async(context, exception) =>
                {
                    await context.SendActivityAsync(context.Activity.CreateReply(CalendarSharedResponses.CalendarErrorMessage));
                    await context.SendActivityAsync(new Activity(type: ActivityTypes.Trace, text: $"Calendar Skill Error: {exception.Message} | {exception.StackTrace}"));
                    connectedServices.TelemetryClient.TrackException(exception);
                };

                // 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);
                options.Middleware.Add(transcriptMiddleware);

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

                options.Middleware.Add(new AutoSaveStateMiddleware(userState, conversationState));
            });
        }
Ejemplo n.º 20
0
 public OrderRepository(CosmosDbStorageOptions configurationOptions)
     : base(configurationOptions, DatabaseId, CollectionId)
 {
 }
 public CardConfigurationRepository(CosmosDbStorageOptions configurationOptions)
     : base(configurationOptions, CardConfigurationRepository.DatabaseId, CardConfigurationRepository.CollectionId)
 {
 }
Ejemplo n.º 22
0
        public void ConfigureServices(IServiceCollection services)
        {
            // Load the connected services from .bot file.
            var botFilePath   = Configuration.GetSection("botFilePath")?.Value;
            var botFileSecret = Configuration.GetSection("botFileSecret")?.Value;
            var botConfig     = BotConfiguration.Load(botFilePath ?? @".\ToDoSkill.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")?.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> > >();
            ISkillConfiguration connectedServices = new SkillConfiguration(botConfig, languageModels, supportedProviders, parameters, configuration);

            services.AddSingleton <ISkillConfiguration>(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);

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

            var serviceProvider = configuration.ContainsKey("TaskServiceProvider") ? configuration["TaskServiceProvider"].ToString() : string.Empty;

            if (serviceProvider.Equals("Outlook", StringComparison.InvariantCultureIgnoreCase))
            {
                services.AddTransient <ITaskService, OutlookService>();
            }
            else
            {
                services.AddTransient <ITaskService, OneNoteService>();
            }

            services.AddTransient <IMailService, MailService>();

            // Add the bot with options
            services.AddBot <ToDoSkill>(options =>
            {
                // Load the connected services from .bot file.
                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}'.");
                }

                options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);

                // Telemetry Middleware (logs activity messages in Application Insights)
                var appInsightsService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.AppInsights) ?? throw new Exception("Please configure your AppInsights connection in your .bot file.");
                var instrumentationKey = (appInsightsService as AppInsightsService).InstrumentationKey;
                var sp = services.BuildServiceProvider();
                var telemetryClient   = sp.GetService <IBotTelemetryClient>();
                var appInsightsLogger = new TelemetryLoggerMiddleware(telemetryClient, logUserName: true, logOriginalMessage: true);
                options.Middleware.Add(appInsightsLogger);

                // Catches any errors that occur during a conversation turn and logs them to AppInsights.
                options.OnTurnError = async(context, exception) =>
                {
                    CultureInfo.CurrentUICulture = new CultureInfo(context.Activity.Locale);
                    await context.SendActivityAsync(context.Activity.CreateReply(ToDoSharedResponses.ToDoErrorMessage));
                    await context.SendActivityAsync(new Activity(type: ActivityTypes.Trace, text: $"To Do Skill Error: {exception.Message} | {exception.StackTrace}"));
                    telemetryClient.TrackException(exception);
                };

                // 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);
                options.Middleware.Add(transcriptMiddleware);

                // Typing Middleware (automatically shows typing when the bot is responding/working)
                var typingMiddleware = new ShowTypingMiddleware();
                options.Middleware.Add(typingMiddleware);
                options.Middleware.Add(new SetLocaleMiddleware(defaultLocale ?? "en-us"));
                options.Middleware.Add(new AutoSaveStateMiddleware(userState, conversationState));
            });
        }
Ejemplo n.º 23
0
        public void ConfigureServices(IServiceCollection services)
        {
            var botSettings      = _configuration.GetSection("BotSettings").Get <BotSettings>();
            var cosmosdbSettings = _configuration.GetSection("CosmosDB").Get <CosmosDBSettings>();

            if (File.Exists(botSettings.FilePath) == false)
            {
                throw new FileNotFoundException($"The .bot configuration file was not found. botFilePath: {botSettings.FilePath}");
            }

            // Loads .bot configuration file
            BotConfiguration botConfig = null;

            try
            {
                botConfig =
                    BotConfiguration.Load(botSettings.FilePath, botSettings.FileSecret) ??
                    throw new InvalidOperationException($"The .bot configuration file '{botSettings.FilePath}' could not be loaded.");
            }
            catch
            {
                // Please ensure you have valid botFilePath and botFileSecret set for your environment.
                // You can find the botFilePath and botFileSecret in the Azure App Service application settings.
                // If you are running this bot locally, consider adding a appsettings.json file with botFilePath and botFileSecret.
                // See https://aka.ms/about-bot-file to learn more about .bot file its use and bot configuration.
                throw new InvalidOperationException("Error reading .bot file.");
            }

            services.AddSingleton <BotConfiguration>(botConfig);

            // Create the connected services from .bot file.
            // services.AddSingleton<BotServices>(new BotServices(botConfig));

            var isProduction = _hostingEnvironment.IsProduction();

            // Retrieve current endpoint.
            var environment = isProduction ? Startup.ProductionName : Startup.DevelopmentName;
            var service     = botConfig.Services.FirstOrDefault(s => s.Type == "endpoint" && s.Name == environment);

            if (service == null && isProduction)
            {
                // Attempt to load development environment
                service = botConfig.Services.FirstOrDefault(s => s.Type == "endpoint" && s.Name == Startup.DevelopmentName);
            }

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

            var cosmosDbStorageOptions = new CosmosDbStorageOptions
            {
                DatabaseId       = cosmosdbSettings.DatabaseId,
                CollectionId     = cosmosdbSettings.CollectionId,
                CosmosDBEndpoint = new Uri(cosmosdbSettings.EndpointUri),
                AuthKey          = cosmosdbSettings.AuthenticationKey
            };

            services.AddSingleton <CosmosDbStorageOptions>(cosmosDbStorageOptions);

            // Register state models
            var dataStore = new CosmosDbStorage(cosmosDbStorageOptions);

            var conversationState = new ConversationState(dataStore);

            services.AddSingleton(conversationState);

            var userState = new UserState(dataStore);

            services.AddSingleton(userState);

            // Register repositories
            services.AddSingleton <OrderRepository>();
            services.AddSingleton <CardConfigurationRepository>();

            // Register services
            services.AddSingleton <ICardService, CardService>();

            // Register bot
            services.AddBot <Bot>(options =>
            {
                options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);
                options.OnTurnError        = async(context, exception) =>
                {
                    _logger.LogError(exception, "Unhandled exception");

                    await context.SendActivityAsync("Черт, эти программисты опять налажали! Неведома ошибка");
                };
            });

            // Register accessors
            services.AddSingleton <BotAccessors>(new BotAccessors(userState, conversationState)
            {
                UserDataAccessor    = userState.CreateProperty <UserData>("WomenDayBot.UserData"),
                DialogStateAccessor = conversationState.CreateProperty <DialogState>("WomenDayBot.DialogState")
            });

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

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(options =>
            {
                options.RootPath = "ClientApp/build";
            });
        }