Esempio n. 1
0
        private static IStorage GetBlobDataStore(BotConfiguration botConfig)
        {
            const string StorageConfigurationId = "BotStateBlob";
            var          blobConfig             = botConfig.FindServiceByNameOrId(StorageConfigurationId);

            if (!(blobConfig is BlobStorageService blobStorageConfig))
            {
                throw new InvalidOperationException($"The .bot file does not contain an blob storage with name '{StorageConfigurationId}'.");
            }
            // Default container name.
            const string DefaultBotContainer = "bot-state-facerecognisebot";
            var          storageContainer    = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container;
            IStorage     dataStore           = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.ConnectionString, storageContainer);

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

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

            services.AddBot <PictureBot.Bots.PictureBot>(options =>
            {
                var appId     = Configuration.GetSection("MicrosoftAppId")?.Value;
                var appSecret = Configuration.GetSection("MicrosoftAppPassword")?.Value;

                options.CredentialProvider = new SimpleCredentialProvider(appId, appSecret);

                // Creates a logger for the application to use.
                ILogger logger = _loggerFactory.CreateLogger <PictureBot.Bots.PictureBot>();

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

                // The Memory Storage used here is for local bot debugging only. When the bot
                // is restarted, everything stored in memory will be gone.
                //IStorage dataStore = new MemoryStorage();

                var blobConnectionString = Configuration.GetSection("BlobStorageConnectionString")?.Value;
                var blobContainer        = Configuration.GetSection("BlobStorageContainer")?.Value;
                IStorage dataStore       = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobConnectionString, blobContainer);
                services.AddSingleton <IStorage>(dataStore);

                // For production bots use the Azure Blob or
                // Azure CosmosDB storage providers. For the Azure
                // based storage providers, add the Microsoft.Bot.Builder.Azure
                // Nuget package to your solution. That package is found at:
                // https://www.nuget.org/packages/Microsoft.Bot.Builder.Azure/
                // Uncomment the following lines to use Azure Blob Storage
                // //Storage configuration name or ID from the .bot file.
                // const string StorageConfigurationId = "<STORAGE-NAME-OR-ID-FROM-BOT-FILE>";
                // var blobConfig = botConfig.FindServiceByNameOrId(StorageConfigurationId);
                // if (!(blobConfig is BlobStorageService blobStorageConfig))
                // {
                //    throw new InvalidOperationException($"The .bot file does not contain an blob storage with name '{StorageConfigurationId}'.");
                // }
                // // Default container name.
                // const string DefaultBotContainer = "botstate";
                // var storageContainer = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container;
                // IStorage dataStore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.ConnectionString, storageContainer);

                var userState         = new UserState(dataStore);
                var conversationState = new ConversationState(dataStore);

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

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

                var middleware = options.Middleware;

                // Add Regex below
                middleware.Add(new RegExpRecognizerMiddleware()
                               .AddIntent("search", new Regex("search picture(?:s)*(.*)|search pic(?:s)*(.*)", RegexOptions.IgnoreCase))
                               .AddIntent("share", new Regex("share picture(?:s)*(.*)|share pic(?:s)*(.*)", RegexOptions.IgnoreCase))
                               .AddIntent("order", new Regex("order picture(?:s)*(.*)|order print(?:s)*(.*)|order pic(?:s)*(.*)", RegexOptions.IgnoreCase))
                               .AddIntent("help", new Regex("help(.*)", RegexOptions.IgnoreCase)));
            });



            // Create and register state accesssors.
            // Acessors created here are passed into the IBot-derived class on every turn.
            services.AddSingleton <PictureBotAccessors>(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 = services.BuildServiceProvider().GetService <ConversationState>();

                if (conversationState == null)
                {
                    throw new InvalidOperationException("ConversationState must be defined and added before adding conversation-scoped state accessors.");
                }

                // Create the custom state accessor.
                // State accessors enable other components to read and write individual properties of state.
                var accessors = new PictureBotAccessors(conversationState)
                {
                    PictureState        = conversationState.CreateProperty <PictureState>(PictureBotAccessors.PictureStateName),
                    DialogStateAccessor = conversationState.CreateProperty <DialogState>("DialogState"),
                };

                return(accessors);
            });

            // Create and register a LUIS recognizer.
            services.AddSingleton(sp =>
            {
                var luisAppId    = Configuration.GetSection("luisAppId")?.Value;
                var luisAppKey   = Configuration.GetSection("luisAppKey")?.Value;
                var luisEndPoint = Configuration.GetSection("luisEndPoint")?.Value;

                // Get LUIS information
                var luisApp = new LuisApplication(luisAppId, luisAppKey, luisEndPoint);

                // Specify LUIS options. These may vary for your bot.
                var luisPredictionOptions = new LuisPredictionOptions
                {
                    IncludeAllIntents = true,
                };

                // Create the recognizer
                var recognizer = new LuisRecognizer(luisApp, luisPredictionOptions, true, null);
                return(recognizer);
            });

            services.AddSingleton(sp =>
            {
                string cogsBaseUrl = Configuration.GetSection("cogsBaseUrl")?.Value;
                string cogsKey     = Configuration.GetSection("cogsKey")?.Value;

                var credentials            = new ApiKeyServiceClientCredentials(cogsKey);
                TextAnalyticsClient client = new TextAnalyticsClient(credentials)
                {
                    Endpoint = cogsBaseUrl
                };

                return(client);
            });
        }
Esempio n. 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddNewtonsoftJson();

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

            // Create the bot as a transient. In this case the ASP Controller is expecting an IBot.
            //services.AddTransient<IBot, Bots.PictureBot>();
            services.AddBot <PictureBot.Bots.PictureBot>(options =>
            {
                var appId     = Configuration.GetSection("MicrosoftAppId")?.Value;
                var appSecret = Configuration.GetSection("MicrosoftAppPassword")?.Value;

                options.CredentialProvider = new SimpleCredentialProvider(appId, appSecret);

                // Creates a logger for the application to use.
                ILogger logger = _loggerFactory.CreateLogger <PictureBot.Bots.PictureBot>();

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

                // The Memory Storage used here is for local bot debugging only. When the bot
                // is restarted, everything stored in memory will be gone.
                //IStorage dataStore = new MemoryStorage();
                var blobConnectionString = Configuration.GetSection("BlobStorageConnectionString")?.Value;
                var blobContainer        = Configuration.GetSection("BlobStorageContainer")?.Value;
                IStorage dataStore       = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobConnectionString, blobContainer);
                // For production bots use the Azure Blob or
                // Azure CosmosDB storage providers. For the Azure
                // based storage providers, add the Microsoft.Bot.Builder.Azure
                // Nuget package to your solution. That package is found at:
                // https://www.nuget.org/packages/Microsoft.Bot.Builder.Azure/
                // Uncomment the following lines to use Azure Blob Storage
                // //Storage configuration name or ID from the .bot file.
                // const string StorageConfigurationId = "<STORAGE-NAME-OR-ID-FROM-BOT-FILE>";
                // var blobConfig = botConfig.FindServiceByNameOrId(StorageConfigurationId);
                // if (!(blobConfig is BlobStorageService blobStorageConfig))
                // {
                //    throw new InvalidOperationException($"The .bot file does not contain an blob storage with name '{StorageConfigurationId}'.");
                // }
                // // Default container name.
                // const string DefaultBotContainer = "botstate";
                // var storageContainer = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container;
                // IStorage dataStore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.ConnectionString, storageContainer);

                // Create Conversation State object.
                // The Conversation State object is where we persist anything at the conversation-scope.
                //var conversationState = new ConversationState(dataStore);

                //options.State.Add(conversationState);
                var userState         = new UserState(dataStore);
                var conversationState = new ConversationState(dataStore);

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

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

                var middleware = options.Middleware;
                // Add middleware below with "middleware.Add(...."
                // Add Regex below
                middleware.Add(new RegExpRecognizerMiddleware()
                               .AddIntent("search", new Regex("search picture(?:s)*(.*)|search pic(?:s)*(.*)", RegexOptions.IgnoreCase))
                               .AddIntent("share", new Regex("share picture(?:s)*(.*)|share pic(?:s)*(.*)", RegexOptions.IgnoreCase))
                               .AddIntent("order", new Regex("order picture(?:s)*(.*)|order print(?:s)*(.*)|order pic(?:s)*(.*)", RegexOptions.IgnoreCase))
                               .AddIntent("help", new Regex("help(.*)", RegexOptions.IgnoreCase)));
            });

            services.AddSingleton <PictureBotAccessors>(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 conversationState = services.BuildServiceProvider().GetService <ConversationState>();

                if (conversationState == null)
                {
                    throw new InvalidOperationException("ConversationState must be defined and added before adding conversation-scoped state accessors.");
                }

                // Create the custom state accessor.
                // State accessors enable other components to read and write individual properties of state.
                var accessors = new PictureBotAccessors(conversationState)
                {
                    PictureState        = conversationState.CreateProperty <PictureState>(PictureBotAccessors.PictureStateName),
                    DialogStateAccessor = conversationState.CreateProperty <DialogState>("DialogState"),
                };

                return(accessors);
            });
            services.AddSingleton(sp =>
            {
                var luisApplication = new LuisApplication(
                    Configuration.GetSection("luisAppId")?.Value,
                    Configuration.GetSection("luisAppKey")?.Value,
                    Configuration.GetSection("luisEndPoint")?.Value);
                // Set the recognizer options depending on which endpoint version you want to use.
                // More details can be found in https://docs.microsoft.com/en-gb/azure/cognitive-services/luis/luis-migration-api-v3
                var recognizerOptions = new LuisRecognizerOptionsV3(luisApplication)
                {
                    PredictionOptions = new Microsoft.Bot.Builder.AI.LuisV3.LuisPredictionOptions
                    {
                        IncludeAllIntents = true,
                    }
                };
                return(new LuisRecognizer(recognizerOptions));
            });
        }
Esempio n. 4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            services.AddHttpClient();
            var myConfig = Configuration.Get <WebsterConfig>();

            services.AddSingleton <WebsterConfig>(sp => myConfig);
            services.AddSingleton <ILogger>(_logFactory.CreateLogger <Webster>());
            services.AddApplicationInsightsTelemetry(myConfig.AppInsightsKey);
            services.AddSingleton <IBotTelemetryClient, BotTelemetryClient>();


            IStorage            datastore;
            ICredentialProvider creds;

            if (Environment.IsDevelopment())
            {
                datastore = new MemoryStorage();
                creds     = new SimpleCredentialProvider("", "");
            }
            else
            {
                const string DefaultBotContainer = "botstore";
                datastore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(myConfig.StateStore, DefaultBotContainer);
                creds     = new SimpleCredentialProvider(myConfig.MicrosoftAppId, myConfig.MicrosoftAppPassword);
            }
            services.AddSingleton <ICredentialProvider>(sp => creds);
            services.AddSingleton <IStorage>(ds => datastore);

            services.AddSingleton <ConversationState>();
            services.AddSingleton <UserState>();
            services.AddSingleton <IRecognizer, Recognizer>();
            // services.AddSingleton<IWebsterQnAMaker, WebsterQnAMaker>();
            services.AddSingleton <IStatePropertyAccessor <DialogState> >((sp) =>
            {
                var cs = sp.GetService <ConversationState>();
                return(cs.CreateProperty <DialogState>(nameof(DialogState)));
            });
            services.AddSingleton <IStatePropertyAccessor <WeatherState> >((sp) =>
            {
                var us = sp.GetService <UserState>();
                return(us.CreateProperty <WeatherState>(nameof(WeatherState)));
            });
            /* Add the dialog(s) as singleton(s) */
            services.AddSingleton <GetWeather>();

            /* Build up the DialogSet object */
            services.AddSingleton <DialogSet>((sp) =>
            {
                var ds = new DialogSet(sp.GetService <IStatePropertyAccessor <DialogState> >());
                ds.Add(sp.GetService <GetWeather>());
                return(ds);
            });

            /* MiddlewareSet is an ordered list of execution objects */
            var set = new MiddlewareSet();

            set.Use(new AutoSaveStateMiddleware(new BotState[] { services.BuildServiceProvider().GetService <UserState>(), services.BuildServiceProvider().GetService <ConversationState>() }))
            .Use(new MembersAddedMiddleware())
            .Use(new LuisRecognizerMiddleware(services.BuildServiceProvider().GetService <IRecognizer>(), myConfig.LuisConfidence))
            .Use(new InterruptMiddleware(services.BuildServiceProvider().GetService <IStatePropertyAccessor <DialogState> >()))
            .Use(new ContinueDialogMiddleware(services.BuildServiceProvider().GetService <DialogSet>()))
            .Use(new DialogDispatcher(services.BuildServiceProvider().GetService <DialogSet>()));

            // .Use(new QnAMakerMiddleware(services.BuildServiceProvider().GetService<IWebsterQnAMaker>(), float.Parse(myConfig.QnAConfidence)));
            services.AddSingleton <IMiddleware>(sp => set);

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

            // Create the bot as a transient.
            services.AddTransient <IBot, Webster>();
        }
Esempio n. 5
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection"/> specifies the contract for a collection of service descriptors.</param>
        /// <seealso cref="IStatePropertyAccessor{T}"/>
        /// <seealso cref="https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection"/>
        /// <seealso cref="https://docs.microsoft.com/en-us/azure/bot-service/bot-service-manage-channels?view=azure-bot-service-4.0"/>
        public void ConfigureServices(IServiceCollection services)
        {
            // Loads .bot configuration file and adds a singleton that your Bot can access through dependency injection.
            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}");
            }
            var botConfig = BotConfiguration.Load(botFilePath ?? @".\BotConfiguration.bot", secretKey);

            // Creates a logger for the application to use.
            // services.AddSingleton<ILogger>(_logger);

            services.AddApplicationInsightsTelemetry();

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

            // don't serialise self-referencing loops
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };


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

                // Retrieve current endpoint.
                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 ?? Configuration[ConfigHelper.BotServiceEndpointAppId],
                    endpointService.AppPassword ?? Configuration[ConfigHelper.BotServiceEndpointAppPassword]);

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

            IStorage storage = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(
                Configuration[ConfigHelper.StorageConnectionString],
                Configuration[ConfigHelper.StorageStateContainer]);

            ConversationState conversationState = new ConversationState(storage);
            UserState         userState         = new UserState(storage);
            DialogState       dialogState       = new DialogState();

            services.AddSingleton(sp =>
            {
                // Create the custom state accessor.
                return(new RingoBotAccessors(conversationState, userState)
                {
                    ConversationDataAccessor = conversationState.CreateProperty <ConversationData>(RingoBotAccessors.ConversationDataName),
                    UserProfileAccessor = userState.CreateProperty <UserProfile>(RingoBotAccessors.UserProfileName),
                    DialogState = conversationState.CreateProperty <DialogState>(RingoBotAccessors.DialogStateName),
                });
            });

            services.AddSingleton <ISpotifyService, SpotifyService>();
            services.AddSingleton <IRingoService, RingoService>();
            services.AddSingleton <IAlbumsApi, AlbumsApi>();
            services.AddSingleton <IArtistsApi, ArtistsApi>();
            services.AddSingleton <IPlaylistsApi, PlaylistsApi>();
            services.AddSingleton <IPlayerApi, PlayerApi>();
            services.AddSingleton <HttpClient, HttpClient>();
            services.AddSingleton <IUserAccountsService, UserAccountsService>();
            services.AddSingleton <IAccountsService, AccountsService>();
            services.AddSingleton <IAuthService, AuthService>();
            services.AddSingleton <IRingoBotCommands, RingoBotCommands>();
            services.AddSingleton <IUserData, UserData>();
            services.AddSingleton <IStationData, StationData>();
            services.AddSingleton <IListenerData, ListenerData>();
            services.AddSingleton <IStateData, StateData>();
        }
Esempio n. 6
0
        public void ConfigureServices(IServiceCollection services)
        {
            IStorage dataStore;

            var environment = Configuration.GetSection("environment")?.Value == "production" ? "production" : "development";

            _isProduction = environment == "production";

            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.
            var botConfig = BotConfiguration.Load(@".\PasswordBot.bot", secretKey);

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


            // The Memory Storage used here is for local bot debugging only. When the bot
            // is restarted, everything stored in memory will be gone.
            if (!_isProduction)
            {
                dataStore = new MemoryStorage();
            }
            else
            {
                // //Storage configuration name or ID from the .bot file.
                const string StorageConfigurationId = "blob";
                var          blobConfig             = botConfig.FindServiceByNameOrId(StorageConfigurationId);

                if (!(blobConfig is BlobStorageService blobStorageConfig))
                {
                    throw new InvalidOperationException($"The .bot file does not contain an blob storage with name '{StorageConfigurationId}'.");
                }

                //Default container name.
                const string DefaultBotContainer = "passwordnotificationbot";
                var          storageContainer    = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container;
                dataStore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.ConnectionString, storageContainer);
            }

            // Create PasswordNotificationState object.
            // The Password Notification State object is where we persist anything at the notification-scope.
            // Note: It's independent of any user or conversation.
            PasswordNotificationState notificationsState = new PasswordNotificationState(dataStore);

            // Make it available to our bot
            services.AddSingleton(sp => notificationsState);

            ConversationState conversationState       = new ConversationState(dataStore);
            UserState         userState               = new UserState(dataStore);
            DialogState       conversationDialogState = new DialogState();

            services.AddBot <PasswordBot>(options =>
            {
                // Retrieve current endpoint.
                var service = botConfig.Services.FirstOrDefault(s => s.Type == "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);
                options.ChannelProvider    = new ConfigurationChannelProvider(Configuration);

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

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

            services.AddSingleton <StateBotAccessors>(sp =>
            {
                return(new StateBotAccessors(conversationDialogState, conversationState, userState)
                {
                    // The dialogs will need a state store accessor. Creating it here once (on-demand) allows the dependency injection
                    // to hand it to our IBot class that is create per-request.
                    ConversationDataAccessor = conversationState.CreateProperty <ConversationData>(StateBotAccessors.ConversationDataName),
                    UserProfileAccessor = userState.CreateProperty <UserProfile>(StateBotAccessors.UserProfileName),
                    ConversationDialogStateAccessor = conversationState.CreateProperty <DialogState>(StateBotAccessors.ConversationDialogName),
                });
            });

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

                return((EndpointService)service);
            });
        }
Esempio n. 7
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection"/> specifies the contract for a collection of service descriptors.</param>
        /// <seealso cref="IStatePropertyAccessor{T}"/>
        /// <seealso cref="https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection"/>
        /// <seealso cref="https://docs.microsoft.com/en-us/azure/bot-service/bot-service-manage-channels?view=azure-bot-service-4.0"/>
        public void ConfigureServices(IServiceCollection services)
        {
            var secretKey   = Configuration.GetSection("botFileSecret")?.Value;
            var botFilePath = Configuration.GetSection("botFilePath")?.Value;

            // Loads .bot configuration file and adds a singleton that your Bot can access through dependency injection.
            var botConfig = BotConfiguration.Load(botFilePath, secretKey);

            services.AddSingleton(sp => botConfig);

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

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

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

            //IStorage dataStore = new MemoryStorage();
            // For production bots use the Azure Blob or
            // Azure CosmosDB storage providers. For the Azure
            // based storage providers, add the Microsoft.Bot.Builder.Azure
            // Nuget package to your solution. That package is found at:
            // https://www.nuget.org/packages/Microsoft.Bot.Builder.Azure/
            // Un-comment the following lines to use Azure Blob Storage
            // Storage configuration name or ID from the .bot file.
            const string StorageConfigurationId = "blobstorage";
            var          blobConfig             = botConfig.FindServiceByNameOrId(StorageConfigurationId);

            if (!(blobConfig is BlobStorageService blobStorageConfig))
            {
                throw new InvalidOperationException($"The .bot file does not contain an blob storage with name '{StorageConfigurationId}'.");
            }
            // Default container name.
            const string DefaultBotContainer = "botstate";
            var          storageContainer    = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container;
            IStorage     dataStore           = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.ConnectionString, storageContainer);

            var conversationState = new ConversationState(dataStore);

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

            services.AddSingleton(userState);

            var iservice = botConfig.Services.FirstOrDefault(s => s.Type == "endpoint" && s.Name == "investservice-" + environment);

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

            var investService = new InvestDataService(investServiceEndpoint.Endpoint, investServiceEndpoint.AppId, investServiceEndpoint.AppPassword);

            services.AddSingleton(investService);
            var botAccount  = new MicrosoftAppCredentials(endpointService.AppId, endpointService.AppPassword);
            var pushService = new PortfolioPushService(investService, botAccount, dataStore);

            services.AddSingleton(pushService);

            services.AddBot <InvestbotBot> (options =>
            {
                options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);
                options.ChannelProvider    = new ConfigurationChannelProvider(Configuration);
                ILogger logger             = loggerFactory.CreateLogger <InvestbotBot>();

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

            var connectionString =
                "Server=tcp:iwnp0c751k.database.windows.net,1433;Initial Catalog=invest_hangfire;Persist Security Info=False;User ID=Investbot;Password=InvBotPDollarwyrdSharp_;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";

            try
            {
                services.AddHangfire(conf => conf.UseSqlServerStorage(connectionString));
                //pushService.SetupJob();
            }
            catch (Exception ex)
            {
                Diagnostic.Log += ex.Message;
            }
        }
Esempio n. 8
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(Environment.CurrentDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()

                         .Build();

            var myConfig = config.Get <WebsterConfig>();

            builder.Services.AddSingleton <WebsterConfig>(sp => myConfig);
            // builder.Services.AddSingleton<ILogger>();
            builder.Services.AddApplicationInsightsTelemetry(myConfig.AppInsightsKey);
            builder.Services.AddSingleton <IBotTelemetryClient, BotTelemetryClient>();
            IStorage            datastore;
            ICredentialProvider creds;



            if (Convert.ToBoolean(Environment.GetEnvironmentVariable("IsDevelopment")))
            {
                datastore = new MemoryStorage();
                creds     = new SimpleCredentialProvider("", "");
            }
            else
            {
                const string DefaultBotContainer = "botstore";
                datastore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(myConfig.StateStore, DefaultBotContainer);
                creds     = new SimpleCredentialProvider(myConfig.MicrosoftAppId, myConfig.MicrosoftAppPassword);
            }
            builder.Services.AddSingleton <ICredentialProvider>(sp => creds);
            builder.Services.AddSingleton <IStorage>(ds => datastore);

            builder.Services.AddSingleton <ConversationState>();
            builder.Services.AddSingleton <UserState>();
            builder.Services.AddSingleton <IRecognizer, Recognizer>();
            // services.AddSingleton<IWebsterQnAMaker, WebsterQnAMaker>();
            builder.Services.AddSingleton <IStatePropertyAccessor <DialogState> >((sp) =>
            {
                var cs = sp.GetService <ConversationState>();
                return(cs.CreateProperty <DialogState>(nameof(DialogState)));
            });
            builder.Services.AddSingleton <IStatePropertyAccessor <WeatherState> >((sp) =>
            {
                var us = sp.GetService <UserState>();
                return(us.CreateProperty <WeatherState>(nameof(WeatherState)));
            });
            /* Add the dialog(s) as singleton(s) */
            builder.Services.AddSingleton <GetWeather>();

            /* Build up the DialogSet object */
            builder.Services.AddSingleton <DialogSet>((sp) =>
            {
                var ds = new DialogSet(sp.GetService <IStatePropertyAccessor <DialogState> >());
                ds.Add(sp.GetService <GetWeather>());
                return(ds);
            });



            var set = new MiddlewareSet();

            set.Use(new AutoSaveStateMiddleware(new BotState[] { builder.Services.BuildServiceProvider().GetService <UserState>()
                                                                 , builder.Services.BuildServiceProvider().GetService <ConversationState>() }))
            .Use(new MembersAddedMiddleware())
            .Use(new LuisRecognizerMiddleware(builder.Services.BuildServiceProvider().GetService <IRecognizer>(), myConfig.LuisConfidence))
            .Use(new InterruptMiddleware(builder.Services.BuildServiceProvider().GetService <IStatePropertyAccessor <DialogState> >()))
            .Use(new ContinueDialogMiddleware(builder.Services.BuildServiceProvider().GetService <DialogSet>()))
            .Use(new DialogDispatcher(builder.Services.BuildServiceProvider().GetService <DialogSet>()));



            // .Use(new QnAMakerMiddleware(services.BuildServiceProvider().GetService<IWebsterQnAMaker>(), float.Parse(myConfig.QnAConfidence)));
            builder.Services.AddSingleton <IMiddleware>(sp => set);

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

            // Create the bot as a transient.
            builder.Services.AddTransient <IBot, Webster>();
        }
Esempio n. 9
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection"/> specifies the contract for a collection of service descriptors.</param>
        /// <seealso cref="IStatePropertyAccessor{T}"/>
        /// <seealso cref="https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection"/>
        /// <seealso cref="https://docs.microsoft.com/en-us/azure/bot-service/bot-service-manage-channels?view=azure-bot-service-4.0"/>
        public void ConfigureServices(IServiceCollection services)
        {
            var secretKey   = Configuration.GetSection("botFileSecret")?.Value;
            var botFilePath = Configuration.GetSection("botFilePath")?.Value;

            // Refer botbuider-tools - MSBot - https://github.com/Microsoft/botbuilder-tools/tree/master/packages/MSBot/docs
            // Loads .bot configuration file and adds a singleton that your Bot can access through dependency injection.
            var botConfig = BotConfiguration.Load(botFilePath ?? @".\MsBotv4.bot", secretKey);

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

            // Initialize Bot Connected Services clients.
            var connectedServices = new BotServices(botConfig);

            services.AddSingleton(sp => connectedServices);

            services.AddSingleton(sp => botConfig);

            //BotBuilderCommunity OpenSource - https://github.com/BotBuilderCommunity/botbuilder-community-dotnet
            services.AddBot <Chatbot>(options =>
            {
                // Retrieve current endpoint.
                var environment = _isProduction ? "production" : "development";
                var service     = botConfig.Services.FirstOrDefault(s => s.Type == "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);

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

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

                // The Memory Storage used here is for local bot debugging only. When the bot
                // is restarted, everything stored in memory will be gone.
                //IStorage dataStore = new MemoryStorage();

                // For production bots use the Azure Blob or
                // Azure CosmosDB storage providers. For the Azure
                // based storage providers, add the Microsoft.Bot.Builder.Azure
                // Nuget package to your solution. That package is found at:
                // https://www.nuget.org/packages/Microsoft.Bot.Builder.Azure/
                // Uncomment the following lines to use Azure Blob Storage
                //Storage configuration name or ID from the .bot file.
                const string StorageConfigurationId = "BlobDataStore";
                var blobConfig = botConfig.FindServiceByNameOrId(StorageConfigurationId);
                if (!(blobConfig is BlobStorageService blobStorageConfig))
                {
                    throw new InvalidOperationException($"The .bot file does not contain an blob storage with name '{StorageConfigurationId}'.");
                }
                // Default container name.
                const string DefaultBotContainer = "default";
                var storageContainer             = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container;
                IStorage dataStore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.ConnectionString, storageContainer);


                // Create Conversation State object.
                // The Conversation State object is where we persist anything at the conversation-scope.
                var conversationState = new ConversationState(dataStore);
                var userState         = new UserState(dataStore);
                options.State.Add(conversationState);
                options.State.Add(userState);

                if (Configuration.GetValue <bool>("isTranslationMiddlewareEnabled"))
                {
                    var translatorKey = Configuration.GetValue <string>("msTranslatorKey");
                    options.Middleware.Add(
                        new TranslationMiddleware(new MicrosoftTranslator(translatorKey),
                                                  ChatbotStateAccessor.Create(conversationState, userState)));
                }

                //https://github.com/BotBuilderCommunity/botbuilder-community-dotnet/tree/master/libraries/Bot.Builder.Community.Middleware.SpellCheck
                if (Configuration.GetValue <bool>("isSpellCheckEnabled"))
                {
                    options.Middleware.Add(new SpellCheckMiddleware(Configuration));
                }
            });

            // Create and register state accessors.
            // Accessors created here are passed into the IBot-derived class on every turn.
            services.AddSingleton <ChatbotStateAccessor>(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 userState = options.State.OfType <UserState>().FirstOrDefault();
                if (userState == null)
                {
                    throw new InvalidOperationException("UserState must be defined and added before adding user-scoped state accessors.");
                }
                // Create the custom state accessor.
                // State accessors enable other components to read and write individual properties of state.
                var accessors = ChatbotStateAccessor.Create(conversationState, userState);

                return(accessors);
            });
        }
Esempio n. 10
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">Specifies the contract for a <see cref="IServiceCollection"/> of service descriptors.</param>
        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.Where(s => s.Type == "endpoint" && s.Name == "development").FirstOrDefault();
            }

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

            // Memory Storage is for local bot debugging only. When the bot
            // is restarted, everything stored in memory will be gone.
            IStorage dataStore = null;

            if (!_isProduction)
            {
                dataStore = new MemoryStorage();
            }
            else
            {
                // For production bots use the Azure Blob or
                // Azure CosmosDB storage providers. For the Azure
                // based storage providers, add the Microsoft.Bot.Builder.Azure
                // Nuget package to your solution. That package is found at:
                // https://www.nuget.org/packages/Microsoft.Bot.Builder.Azure/
                // Un-comment the following lines to use Azure Blob Storage
                // Storage configuration name or ID from the .bot file.
                const string StorageConfigurationId = "toremx5h";
                var          blobConfig             = botConfig.FindServiceByNameOrId(StorageConfigurationId);
                if (!(blobConfig is BlobStorageService blobStorageConfig))
                {
                    throw new InvalidOperationException($"The .bot file does not contain an blob storage with name '{StorageConfigurationId}'.");
                }

                // Default container name.
                const string DefaultBotContainer = "botstate";
                var          storageContainer    = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container;
                dataStore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.ConnectionString, storageContainer);
            }

            // Create and add conversation state.
            var conversationState = new ConversationState(dataStore);

            services.AddSingleton(conversationState);

            var userState = new UserState(dataStore);

            services.AddSingleton(userState);

            services.AddBot <UStoreBot>(options =>
            {
                options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);
                options.ChannelProvider    = new ConfigurationChannelProvider(Configuration);

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

            //if (_isProduction)
            //{
            services.AddDbContext <UStoreDBContext>(options =>
                                                    options.UseSqlServer(Configuration.GetConnectionString("UStoreDBProd")));
            //}
            //else
            //{
            //    services.AddDbContext<UStoreDBContext>(options =>
            //        options.UseSqlServer(Configuration.GetConnectionString("UStoreDBDev")));
            //}
        }