Ejemplo n.º 1
0
        public async Task should_load_incrementally_from_an_existing_storage()
        {
            var storage = new MemoryStorage();
            await Task.WhenAll(Enumerable.Range(0, 8).Select(x => storage.Put(new TestStorageObject(x))));

            var collection = new StorageCollection<TestStorageObject>(storage, "0", "6");
            Assert.True(collection.HasMoreItems);
            Assert.Equal(0, collection.Count);

            await collection.LoadMoreItemsAsync(2);

            Assert.Equal(2, collection.Count);
            Assert.Equal(collection.Select(e => e.Id), Enumerable.Range(0, 2).Select(i => i.ToString()));

            await collection.LoadMoreItemsAsync(2);

            Assert.Equal(4, collection.Count);
            Assert.Equal(collection.Select(e => e.Id), Enumerable.Range(0, 4).Select(i => i.ToString()));

            Assert.False(collection.IsLoading);
            Assert.True(collection.HasMoreItems);

            await collection.LoadMoreItemsAsync(10);
            Assert.Equal(6, collection.Count);
            Assert.False(collection.HasMoreItems);
            Assert.Equal(collection.Select(e => e.Id), Enumerable.Range(0, 6).Select(i => i.ToString()));
        }
        public static MemoryStorage UseMemoryStorage(this IGlobalConfiguration configuration,
            MemoryStorageOptions storageOptions)
        {
            var storage = new MemoryStorage(storageOptions);

            configuration.UseStorage(storage);

            return storage;
        }
Ejemplo n.º 3
0
        public async Task should_load_all_items()
        {
            var storage = new MemoryStorage();
            await Task.WhenAll(Enumerable.Range(0, 8).Select(x => storage.Put(new TestStorageObject(x))));

            var collection = new StorageCollection<TestStorageObject>(storage, "0", "6");
            Assert.True(collection.HasMoreItems);
            Assert.Equal(0, collection.Count);

            await collection.LoadAllAsync(2);

            Assert.Equal(6, collection.Count);
            Assert.False(collection.HasMoreItems);
            Assert.Equal(collection.Select(e => e.Id), Enumerable.Range(0, 6).Select(i => i.ToString()));
        }
Ejemplo n.º 4
0
        public static async Task storage_can_be_migrated_by_get_many_request()
        {
            var v1 = new MemoryStorage<Migration>();
            var v2 = new MemoryStorage<Migration>();
            var migrate = new StorageMigration<Migration>(v2, v1, null, true);

            var data = Enumerable.Range(0, 1000).Select(x => new Migration { Id = x, Time = DateTime.UtcNow });
            await Task.WhenAll(from x in data select v1.Put(x)).ConfigureAwait(false);

            var a = await migrate.All().ToListAsync().ConfigureAwait(false);
            var b = await v2.All().ToListAsync().ConfigureAwait(false);

            Assert.True(a.SequenceEqual(b));
            Assert.False((await v1.All().ToListAsync().ConfigureAwait(false)).Any());
        }
Ejemplo n.º 5
0
        public static void Main(string[] args)
        {
            //TODO
            //MainnetRules.BypassValidation = true;
            //MainnetRules.BypassExecuteScript = true;
            ScriptEngine.BypassVerifySignature = true;

            using (var storageContext = new MemoryStorageContext())
            using (var cacheContext = new CacheContext(storageContext))
            {
                var rules = new Testnet2Rules(cacheContext);

                using (var blockchainDaemon = new BlockchainDaemon(rules, cacheContext))
                using (var knownAddressStorage = new MemoryStorage<NetworkAddressKey, NetworkAddressWithTime>(storageContext))
                using (var localClient = new LocalClient(LocalClientType.ComparisonToolTestNet, blockchainDaemon, knownAddressStorage))
                {
                    // start the blockchain daemon
                    blockchainDaemon.Start();

                    // start p2p client
                    localClient.Start();

                    var projectFolder = Environment.CurrentDirectory;
                    while (projectFolder.Contains(@"\bin"))
                        projectFolder = Path.GetDirectoryName(projectFolder);

                    File.Delete(Path.Combine(projectFolder, "Bitcoinj-comparison.log"));

                    var javaProcessStartInfo = new ProcessStartInfo
                        {
                            FileName = @"C:\Program Files\Java\jdk1.7.0_25\bin\java.exe",
                            WorkingDirectory = projectFolder,
                            Arguments = @"-Djava.util.logging.config.file={0}\bitcoinj.log.properties -jar {0}\bitcoinj.jar".Format2(projectFolder),
                            UseShellExecute = false
                        };

                    var javaProcess = Process.Start(javaProcessStartInfo);

                    javaProcess.WaitForExit((int)TimeSpan.FromMinutes(5).TotalMilliseconds);
                    Console.ReadLine();
                }
            }
        }
Ejemplo n.º 6
0
        public static async Task storage_can_be_migrated_by_get_request()
        {
            var v1 = new MemoryStorage<Migration>();
            var v2 = new MemoryStorage<Migration>();
            var migrate = new StorageMigration<Migration>(v2, v1, null, true);

            await v1.Put(new Migration { Id = 1, Time = DateTime.UtcNow }).ConfigureAwait(false);

            Assert.Null(await v2.Get(StorageKey.Get(1)).ConfigureAwait(false));

            Assert.Equal(
                await v1.Get(StorageKey.Get(1)).ConfigureAwait(false),
                await migrate.Get(StorageKey.Get(1)).ConfigureAwait(false));

            Assert.Null(await v1.Get(StorageKey.Get(1)).ConfigureAwait(false));

            Assert.Equal(
                await v2.Get(StorageKey.Get(1)).ConfigureAwait(false),
                await migrate.Get(StorageKey.Get(1)).ConfigureAwait(false));
        }
Ejemplo n.º 7
0
        public static async Task storage_can_be_migrated_in_a_batch()
        {
            var v1 = new MemoryStorage<Migration>();
            var v2 = new MemoryStorage<Migration>();
            var v3 = new MemoryStorage<Migration>();
            var migrate = new StorageMigration<Migration>(v2, v1);
            var migrateAndDelete = new StorageMigration<Migration>(v3, v1, null, true);

            var data = Enumerable.Range(0, 100).Select(x => new Migration { Id = x, Time = DateTime.UtcNow });
            await Task.WhenAll(from x in data select v1.Put(x)).ConfigureAwait(false);

            Assert.True(data.Select(x => x.Id).SequenceEqual((await v1.All().ToListAsync().ConfigureAwait(false)).Select(x => x.Id)));

            await migrate.MigrateAsync(123).ConfigureAwait(false);

            Assert.True(data.Select(x => x.Id).SequenceEqual((await v1.All().ToListAsync().ConfigureAwait(false)).Select(x => x.Id)));
            Assert.True(data.Select(x => x.Id).SequenceEqual((await v2.All().ToListAsync().ConfigureAwait(false)).Select(x => x.Id)));

            await migrateAndDelete.MigrateAsync(456).ConfigureAwait(false);
            Assert.Equal(0, (await v1.All().ToListAsync()).Count());
            Assert.True(data.Select(x => x.Id).SequenceEqual((await v3.All().ToListAsync().ConfigureAwait(false)).Select(x => x.Id)));
        }
Ejemplo n.º 8
0
 public void Inititalize()
 {
     _storage  = new MemoryStorage <PersonStorableItem <Guid>, Guid>();
     _testCrud = new StorageTestCrud <MemoryStorage <PersonStorableItem <Guid>, Guid>, PersonStorableItem <Guid>, Guid>(_storage);
 }
Ejemplo n.º 9
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(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 CalendarSkillAccessors
                {
                    ConversationDialogState = conversationState.CreateProperty <DialogState>("CalendarSkillDialogState"),
                    CalendarSkillState      = conversationState.CreateProperty <CalendarSkillState>("CalendarSkillState"),
                };

                return(accessors);
            });

            services.AddSingleton <IServiceManager, ServiceManager>();

            services.AddSingleton <CalendarSkillServices>(sp =>
            {
                var luisModels = this.Configuration.GetSection("services").Get <LanguageModel[]>();

                var luis = luisModels[0];
                var calendarSkillService = new CalendarSkillServices();
                {
                    var luisApp        = new LuisApplication(luis.Id, luis.SubscriptionKey, "https://westus.api.cognitive.microsoft.com");
                    var luisRecognizer = new LuisRecognizer(luisApp);
                    calendarSkillService.LuisRecognizer = luisRecognizer;
                    var authConnectionName = this.Configuration.GetSection("authConnectionName")?.Value;
                    calendarSkillService.AuthConnectionName = authConnectionName;
                }

                return(calendarSkillService);
            });

            services.AddBot <CalendarSkill>(options =>
            {
                options.CredentialProvider = new ConfigurationCredentialProvider(Configuration);

                // Catches any errors that occur during a conversation turn and logs them to AppInsights.
                options.OnTurnError = async(context, exception) =>
                {
                    await context.SendActivityAsync($"CalendarSkill: {exception.Message}");
                    await context.SendActivityAsync(exception.StackTrace);
                };

                var transcriptStore = new AzureBlobTranscriptStore(this.Configuration.GetSection("AzureBlobConnectionString")?.Value, this.Configuration.GetSection("transcriptContainer")?.Value);
                options.Middleware.Add(new TranscriptLoggerMiddleware(transcriptStore));

                IStorage dataStore = new MemoryStorage();
                options.State.Add(new ConversationState(dataStore));
                options.Middleware.Add(new AutoSaveStateMiddleware(options.State.ToArray()));
            });
        }
Ejemplo 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>
        /// <seealso cref="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1"/>
        public void ConfigureServices(IServiceCollection services)
        {
            // Add botConfiguration singleton
            // See https://aka.ms/about-bot-file to learn more about .bot file its use and bot configuration.
            var secretKey   = Configuration.GetSection("botFileSecret")?.Value;
            var botFilePath = Configuration.GetSection("botFilePath")?.Value;
            var botConfig   = BotConfiguration.Load(botFilePath ?? @".\cafe-bot.bot", secretKey);

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

            // Add BotServices singleton
            services.AddSingleton(sp => new BotServices(botConfig));

            // 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/
            // Un-comment 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 = "<DEFAULT-CONTAINER>";
            // var storageContainer = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container;
            // IStorage dataStore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.ConnectionString, storageContainer);
            services.AddSingleton(dataStore);
            var userState         = new UserState(dataStore);
            var conversationState = new ConversationState(dataStore);

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

            // The BotStateSet enables read() and write() in parallel on multiple BotState instances.
            services.AddSingleton(new BotStateSet(userState, conversationState));

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

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

                // Automatically save state at the end of a turn.
                options.Middleware
                .Add(new AutoSaveStateMiddleware(userState, conversationState));
            });
        }
Ejemplo n.º 11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Retrieve configuration from sections
            Settings.MicrosoftAppId       = Configuration.GetSection("MicrosoftAppId")?.Value;
            Settings.MicrosoftAppPassword = Configuration.GetSection("MicrosoftAppPassword")?.Value;
            Settings.TranslatorTextAPIKey = Configuration.GetSection("TranslatorTextAPIKey")?.Value;
            Settings.BotVersion           = Configuration.GetSection("BotVersion")?.Value;
            Settings.LuisAppId01          = Configuration.GetSection("LuisAppId01")?.Value;
            Settings.LuisName01           = Configuration.GetSection("LuisName01")?.Value;
            Settings.LuisAuthoringKey01   = Configuration.GetSection("LuisAuthoringKey01")?.Value;
            Settings.LuisEndpoint01       = Configuration.GetSection("LuisEndpoint01")?.Value;

            IStorage storage = new MemoryStorage();

            services.AddBot <Bot>(options =>
            {
                options.State.Add(new UserState(storage));
                options.State.Add(new ConversationState(storage));

                options.CredentialProvider = new SimpleCredentialProvider(Settings.MicrosoftAppId, Settings.MicrosoftAppPassword);

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

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

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

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

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

                return(accessors);
            });
        }
Ejemplo n.º 12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            //Instantiate the bot configuration for use in the bot
            //Traffic coming through to your app is protected by the app ID and app secret
            //credentials applied to your Bot Registration on Azure.
            //If you are running locally, these can be blank.
            var secretKey   = Configuration.GetSection("botFileSecret")?.Value;
            var botFilePath = Configuration.GetSection("botFilePath")?.Value;

            var botConfig = BotConfiguration.Load(botFilePath ?? @".\BotConfiguration.bot", secretKey);

            if (botConfig == null)
            {
                throw new InvalidOperationException($"The .bot config file could not be loaded from [{botFilePath}]");
            }

            //Step 1) We can pass bot-related dependencies to the bot and dialogs via DI. Start with the bot configuration
            //Add the bot configuration as something we can retrieve through DI

            //TODO - Add the BotConfiguration to the services container

            //Step 2) Configure the QnA services
            //      - (Optional) Throw an exception if the service is null or if any required fields are empty

            //TODO - Retrieve the first service from the configuration of type ServiceTypes.QnA

            //TODO - Create a new instance of QnAMaker and add it to the services container as a singleton

            //The extension to add a bot to our services container
            //can be found in Microsoft.Bot.Builder.Integration.AspNet.Core
            //Whichever type is passed will be the bot that is created
            services.AddBot <QnAMakerBot>(options =>
            {
                //The bot configuration can map different endpoints for different environments
                var serviceName = Environment.EnvironmentName.ToLowerInvariant();
                var service     = botConfig.FindServiceByNameOrId(serviceName) as EndpointService;
                if (service == null)
                {
                    throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{serviceName}'.");
                }

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


                //Memory storage is only used for this example.
                //In a production application, you should always rely on
                //a more persistant storage mechanism, such as CosmosDB
                IStorage dataStore = new MemoryStorage();

                //Whichever datastore we're working with, we will need to use it
                //to actually store the conversation state.
                var conversationState = new ConversationState(dataStore);
                options.State.Add(conversationState);

                //Step 3) Add a callback for "OnTurnError" that logs any bot or middleware errors to the console
                //     - (Optional) Send a message to the user indicating there was a problem

                ILogger logger = _loggerFactory.CreateLogger <QnAMakerBot>();

                //TODO - Set options.OnTurnError to an async Task that accepts a ITurnContext and Exception
            });
        }
        public async Task <IActionResult> Post([FromBody] LUISDiscoveryRequest model)
        {
            // non-forced-to-disposal
            LUISDiscoveryResponse result = new LUISDiscoveryResponse
            {
                IsSucceded = true,
                ResultId   = (int)LUISDiscoveryResponseEnum.Success
            };

            // forced-to-disposal

            try
            {
                if (string.IsNullOrEmpty(model.Text))
                {
                    throw new BusinessException((int)LUISDiscoveryResponseEnum.FailedEmptyText);
                }

                // building service list
                Settings.LuisServices = new Dictionary <string, LuisRecognizer>();
                foreach (LuisAppRegistration app in Settings.LuisAppRegistrations)
                {
                    var luis = new LuisApplication(app.LuisAppId, app.LuisAuthoringKey, app.LuisEndpoint);

                    LuisPredictionOptions luisPredictionOptions = null;
                    LuisRecognizer        recognizer            = null;

                    bool needsPredictionOptions = false;
                    if ((!string.IsNullOrEmpty(model.BingSpellCheckSubscriptionKey)) || (model.EnableLuisTelemetry))
                    {
                        needsPredictionOptions = true;
                    }

                    if (needsPredictionOptions)
                    {
                        luisPredictionOptions = new LuisPredictionOptions();

                        if (model.EnableLuisTelemetry)
                        {
                            luisPredictionOptions.TelemetryClient        = telemetry;
                            luisPredictionOptions.Log                    = true;
                            luisPredictionOptions.LogPersonalInformation = true;
                        }

                        if (!string.IsNullOrEmpty(model.BingSpellCheckSubscriptionKey))
                        {
                            luisPredictionOptions.BingSpellCheckSubscriptionKey = model.BingSpellCheckSubscriptionKey;
                            luisPredictionOptions.SpellCheck        = true;
                            luisPredictionOptions.IncludeAllIntents = true;
                        }

                        recognizer = new LuisRecognizer(luis, luisPredictionOptions);
                    }
                    else
                    {
                        recognizer = new LuisRecognizer(luis);
                    }

                    Settings.LuisServices.Add(app.LuisName, recognizer);
                }

                foreach (LuisAppRegistration app in Settings.LuisAppRegistrations)
                {
                    var storage           = new MemoryStorage();
                    var conversationState = new ConversationState(storage);

                    var adapter = new TestAdapter().Use(new AutoSaveStateMiddleware(conversationState));

                    IMessageActivity msg = Activity.CreateMessageActivity();
                    msg.Id           = Guid.NewGuid().ToString();
                    msg.From         = new ChannelAccount("sip: [email protected]", "bot");
                    msg.Recipient    = new ChannelAccount("sip: [email protected]", "agent");
                    msg.Text         = model.Text;
                    msg.Locale       = "en-us";
                    msg.ServiceUrl   = "url";
                    msg.ChannelId    = Guid.NewGuid().ToString();
                    msg.Conversation = new ConversationAccount();
                    msg.Type         = ActivityTypes.Message;
                    msg.Timestamp    = DateTime.UtcNow;

                    var context = new TurnContext(adapter, (Activity)msg);

                    var recognizerResult = await Settings.LuisServices[app.LuisName].RecognizeAsync(context, new CancellationToken());
                    var topIntent        = recognizerResult?.GetTopScoringIntent();
                    if (topIntent != null && topIntent.HasValue && topIntent.Value.score >= .90 && topIntent.Value.intent != "None")
                    {
                        result.LuisAppDetails.Add(new LuisAppDetail()
                        {
                            Name = app.LuisName, Intent = topIntent.Value.intent, Score = topIntent.Value.score
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                result.IsSucceded = false;

                if (ex is BusinessException)
                {
                    result.ResultId = ((BusinessException)ex).ResultId;
                }
                else
                {
                    result.ResultId = (int)LUISDiscoveryResponseEnum.Failed;

                    this.logger.LogError($">> Exception: {ex.Message}, StackTrace: {ex.StackTrace}");

                    if (ex.InnerException != null)
                    {
                        this.logger.LogError($">> Inner Exception Message: {ex.InnerException.Message}, Inner Exception StackTrace: {ex.InnerException.StackTrace}");
                    }
                }
            }
            finally
            {
                // clean forced-to-disposal

                GC.Collect();
            }

            string message = EnumDescription.GetEnumDescription((LUISDiscoveryResponseEnum)result.ResultId);

            this.logger.LogInformation($">> Message information: {message}");

            return((result.IsSucceded) ? (ActionResult) new OkObjectResult(new { result = result }) : (ActionResult) new BadRequestObjectResult(new { message = message }));
        }
Ejemplo n.º 14
0
 public Identifier VisitMemoryStorage(MemoryStorage mem)
 {
     return(frame.Memory);
 }
Ejemplo n.º 15
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>
        /// <seealso cref="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1"/>
        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 ?? @".\BotConfiguration.bot", secretKey);

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

            services.AddSingleton(sp => connectedServices);

            services.AddSingleton(sp => botConfig);

            services.AddBot <QnABot>(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, endpointService.AppPassword);

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

                // 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 = "<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 = "<DEFAULT-CONTAINER>";
                // 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);
            });
        }
Ejemplo n.º 16
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)
        {
            services.AddBot <EchoWithCounterBot>(options =>
            {
                // Creates a logger for the application to use.
                ILogger logger = _loggerFactory.CreateLogger <EchoWithCounterBot>();

                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 ?? @".\BotConfiguration.bot", 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.
    ";
                    logger.LogError(msg);
                    throw new InvalidOperationException(msg);
                }

                services.AddSingleton(sp => 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();
                    logger.LogWarning("Attempting to load development endpoint in production 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);

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

            // Create and register state accessors.
            // Accessors created here are passed into the IBot-derived class on every turn.
            services.AddSingleton <EchoBotAccessors>(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.");
                }

                // Create the custom state accessor.
                // State accessors enable other components to read and write individual properties of state.
                var accessors = new EchoBotAccessors(conversationState)
                {
                    CounterState = conversationState.CreateProperty <CounterState>(EchoBotAccessors.CounterStateName),
                };

                return(accessors);
            });
        }
Ejemplo n.º 17
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            // Get assets directory.
            var assetsDirectory = GetAssetsDirectory();

            // Build configuration with assets.
            var config = BuildConfiguration(assetsDirectory);

            var settings = new BotSettings();

            config.Bind(settings);

            var services = builder.Services;

            services.AddSingleton <IConfiguration>(config);

            services.AddLogging();

            // Create the credential provider to be used with the Bot Framework Adapter.
            services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>();
            services.AddSingleton <BotAdapter>(sp => (BotFrameworkHttpAdapter)sp.GetService <IBotFrameworkHttpAdapter>());

            // Register AuthConfiguration to enable custom claim validation.
            services.AddSingleton <AuthenticationConfiguration>();

            // Adaptive component registration
            ComponentRegistration.Add(new DialogsComponentRegistration());
            ComponentRegistration.Add(new DeclarativeComponentRegistration());
            ComponentRegistration.Add(new AdaptiveComponentRegistration());
            ComponentRegistration.Add(new LanguageGenerationComponentRegistration());
            ComponentRegistration.Add(new QnAMakerComponentRegistration());
            ComponentRegistration.Add(new LuisComponentRegistration());

            // This is for custom action component registration.
            //ComponentRegistration.Add(new CustomActionComponentRegistration());

            // Register the skills client and skills request handler.
            services.AddSingleton <SkillConversationIdFactoryBase, Bot.Builder.Skills.SkillConversationIdFactory>();
            services.AddHttpClient <BotFrameworkClient, SkillHttpClient>();
            services.AddSingleton <ChannelServiceHandler, SkillHandler>();

            // Register telemetry client, initializers and middleware
            services.AddApplicationInsightsTelemetry(settings?.ApplicationInsights?.InstrumentationKey ?? string.Empty);

            services.AddSingleton <ITelemetryInitializer, OperationCorrelationTelemetryInitializer>();
            services.AddSingleton <ITelemetryInitializer, TelemetryBotIdInitializer>();
            services.AddSingleton <IBotTelemetryClient, BotTelemetryClient>();
            services.AddSingleton <TelemetryLoggerMiddleware>(sp =>
            {
                var telemetryClient = sp.GetService <IBotTelemetryClient>();
                return(new TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: settings?.Telemetry?.LogPersonalInformation ?? false));
            });
            services.AddSingleton <TelemetryInitializerMiddleware>(sp =>
            {
                var httpContextAccessor       = sp.GetService <IHttpContextAccessor>();
                var telemetryLoggerMiddleware = sp.GetService <TelemetryLoggerMiddleware>();
                return(new TelemetryInitializerMiddleware(httpContextAccessor, telemetryLoggerMiddleware, settings?.Telemetry?.LogActivities ?? false));
            });

            // Storage
            IStorage storage;

            if (ConfigSectionValid(settings?.CosmosDb?.AuthKey))
            {
                storage = new CosmosDbPartitionedStorage(settings?.CosmosDb);
            }
            else
            {
                storage = new MemoryStorage();
            }

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

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

            // Resource explorer to track declarative assets
            var resourceExplorer = new ResourceExplorer().AddFolder(assetsDirectory.FullName);

            services.AddSingleton(resourceExplorer);

            // Adapter
            services.AddSingleton <IBotFrameworkHttpAdapter, BotFrameworkHttpAdapter>(s =>
            {
                // Retrieve required dependencies
                IStorage storage    = s.GetService <IStorage>();
                UserState userState = s.GetService <UserState>();
                ConversationState conversationState = s.GetService <ConversationState>();
                TelemetryInitializerMiddleware telemetryInitializerMiddleware = s.GetService <TelemetryInitializerMiddleware>();

                var adapter = new BotFrameworkHttpAdapter(new ConfigurationCredentialProvider(config));

                adapter
                .UseStorage(storage)
                .UseBotState(userState, conversationState)
                .Use(new RegisterClassMiddleware <IConfiguration>(config))
                .Use(telemetryInitializerMiddleware);

                // Configure Middlewares
                ConfigureTranscriptLoggerMiddleware(adapter, settings);
                ConfigureInspectionMiddleWare(adapter, settings, s);
                ConfigureShowTypingMiddleWare(adapter, settings);
                ConfigureSetSpeakMiddleWare(adapter, settings);

                adapter.OnTurnError = async(turnContext, exception) =>
                {
                    await turnContext.SendActivityAsync(exception.Message).ConfigureAwait(false);
                    await conversationState.ClearStateAsync(turnContext).ConfigureAwait(false);
                    await conversationState.SaveChangesAsync(turnContext).ConfigureAwait(false);
                };

                return(adapter);
            });

            var defaultLocale = config.GetValue <string>(DefaultLanguageSetting) ?? EnglishLocale;

            var removeRecipientMention = settings?.Feature?.RemoveRecipientMention ?? false;

            // Bot
            services.AddSingleton <IBot>(s =>
                                         new ComposerBot(
                                             s.GetService <ConversationState>(),
                                             s.GetService <UserState>(),
                                             s.GetService <ResourceExplorer>(),
                                             s.GetService <BotFrameworkClient>(),
                                             s.GetService <SkillConversationIdFactoryBase>(),
                                             s.GetService <IBotTelemetryClient>(),
                                             GetRootDialog(assetsDirectory.FullName),
                                             defaultLocale,
                                             removeRecipientMention));
        }
Ejemplo n.º 18
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)
        {
            services.AddBot <GraphAuthenticationBot>(options =>
            {
                // From https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-authentication?view=azure-bot-service-4.0&tabs=aadv2%2Ccsharp#create-and-register-an-azure-ad-application
                var appId                  = Configuration.GetSection("MicrosoftAppId").Value;
                var appPassword            = Configuration.GetSection("MicrosoftAppPassword").Value;
                options.CredentialProvider = new SimpleCredentialProvider(appId, appPassword);

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

                // 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 = "<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 = "<DEFAULT-CONTAINER>";
                // 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);
                options.State.Add(userState);
            });

            services.AddSingleton <GraphAuthenticationBotAccessors>(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 conversation-scoped state accessors.");
                }

                // Create Custom State Property Accessors
                // State Property Accessors enable components to read and write individual
                // properties, without having to pass the entire State object.
                var accessors = new GraphAuthenticationBotAccessors(conversationState, userState)
                {
                    CommandState            = userState.CreateProperty <string>(GraphAuthenticationBotAccessors.CommandStateName),
                    ConversationDialogState = conversationState.CreateProperty <DialogState>(GraphAuthenticationBotAccessors.DialogStateName),
                };

                return(accessors);
            });
        }
        public async void AskForATopicSampleTest()
        {
            var storage = new MemoryStorage();

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

            var adapter = new TestAdapter()
                          .Use(new AutoSaveStateMiddleware(conversationState));

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

            luisServices.Add(Settings.LuisName01, recognizer);

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

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

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

            qnaServices.Add(Settings.QnAName01, qnaMaker);

            var accessors = new BotAccessors(new LoggerFactory(), conversationState, userState, luisServices, qnaServices)
            {
                ConversationDialogState   = conversationState.CreateProperty <DialogState>("DialogState"),
                AskForExamplePreference   = conversationState.CreateProperty <bool>("AskForExamplePreference"),
                DetectedFaceIdPreference  = conversationState.CreateProperty <string>("DetectedFaceIdPreference"),
                ImageUriPreference        = conversationState.CreateProperty <string>("ImageUriPreference"),
                HashPreference            = conversationState.CreateProperty <string>("HashPreference"),
                IsNewPreference           = conversationState.CreateProperty <bool>("IsNewPreference"),
                FullnamePreference        = userState.CreateProperty <string>("FullnamePreference"),
                NamePreference            = userState.CreateProperty <string>("NamePreference"),
                LastnamePreference        = userState.CreateProperty <string>("LastnamePreference"),
                IsAuthenticatedPreference = userState.CreateProperty <bool>("IsAuthenticatedPreference")
            };

            List <MediaUrl> mediaList = new List <MediaUrl>();

            mediaList.Add(new MediaUrl("https://www.youtube.com/watch?v=CmTSY9oO3dw"));

            VideoCard videoCard = new VideoCard
            {
                Title     = "Interview Sample",
                Text      = "Each interview takes on a life of its own, but there are certain standard questions that arise. By reviewing them in advance, you can arrive confident and ready to articulate your skills and qualifications. Take a look at the sample questions here, and then bolster them with those specific to your goals and the organization. Both your answers to the interviewer's questions and those you post to them can provide a mechanism by which to communicate your qualifications.",
                Autostart = false,
                Media     = mediaList
            };

            Activity activity = new Activity
            {
                Type        = ActivityTypes.Message,
                Attachments = new List <Attachment> {
                    videoCard.ToAttachment()
                }
            };

            await new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                var state   = await accessors.ConversationDialogState.GetAsync(turnContext, () => new DialogState());
                var dialogs = new DialogSet(accessors.ConversationDialogState);
                dialogs.Add(new LuisQnADialog(accessors));

                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);

                var results = await dc.ContinueDialogAsync(cancellationToken);
                if (results.Status == DialogTurnStatus.Empty)
                {
                    await dc.BeginDialogAsync(LuisQnADialog.dialogId, null, cancellationToken);
                }
                else if (results.Status == DialogTurnStatus.Complete)
                {
                    //no additional send activities.
                }
            })
            .Send("")
            .AssertReply("What topic would you like to know more about?")
            .Send("i would like to see a sample about the considerations for a human resources interview")
            .AssertReply((ac) =>
            {
                if (ac.AsMessageActivity().Attachments != null)
                {
                    var contentType = ac.AsMessageActivity().Attachments[0].ContentType;
                    Assert.Equal("application/vnd.microsoft.card.video", contentType);
                }
                else
                {
                    Assert.NotNull(ac.AsMessageActivity().Attachments);
                }
            })
            .StartTestAsync();
        }
Ejemplo n.º 20
0
 /// <exception cref="System.Exception"></exception>
 public override void SetUp()
 {
     _memoryStorage = new MemoryStorage();
 }
Ejemplo n.º 21
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddBot <DialogueBotWithAccessor>(options =>
            {
                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 ?? @".\BotConfiguration.bot", secretKey);
                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, endpointService.AppPassword);

                options.Middleware.Add(new SimplifiedEchoBotMiddleware1());
                options.Middleware.Add(new SimplifiedEchoBotMiddleware2());
                options.Middleware.Add(new SimplifiedEchoBotMiddleware3());

                // Memory Storage is for local bot debugging only. When the bot
                // is restarted, everything stored in memory will be gone.  This is where you'd want to use Cosmos or Blob Storage to have persistance beyond application's life.
                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/

                //Look at CosmosDB storage setup here:
                //https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-v4-storage?view=azure-bot-service-4.0&tabs=csharp#using-cosmos-db

                // 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 = "<DEFAULT-CONTAINER>";
                // var storageContainer = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container;
                // IStorage dataStore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.ConnectionString, storageContainer);


                // Create and add conversation state.
                // The Conversation State object is where we persist anything at the conversation-scope.

                //Each state management object automates the reading and writing of associated state information to storage.
                //The storage layer connects to the backing storage for state, such as in-memory(for testing), or Azure Cosmos DB Storage(for production).

                var conversationState = new ConversationState(dataStore);
                options.State.Add(conversationState);
            });

            // Create and register state accessors.
            // Accessors created here are passed into the IBot-derived class on every turn.
            services.AddSingleton(sp =>
            {
                // We need to grab the conversationState we added on the options in the previous step.
                var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
                if (options == null)
                {
                    throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the State Accessors");
                }

                var conversationState = options.State.OfType <ConversationState>().FirstOrDefault();
                if (conversationState == null)
                {
                    throw new InvalidOperationException("ConversationState must be defined and added before adding conversation-scoped state accessors.");
                }

                // 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.
                // Create the custom state accessor.
                // State accessors enable other components to read and write individual properties of state.
                var accessors = new DialogueBotConversationStateAccessor(conversationState)
                {
                    ConversationDialogState = conversationState.CreateProperty <DialogState>("DialogState"),
                };
                return(accessors);
            });
        }
Ejemplo n.º 22
0
 public Storage VisitMemoryStorage(MemoryStorage global)
 {
     return(global);
 }
Ejemplo n.º 23
0
 public override void Initial()
 {
     Storage = new MemoryStorage();
 }
Ejemplo n.º 24
0
 public Identifier VisitMemoryStorage(MemoryStorage mem)
 {
     if (id ! == frameOld.Memory)
     {
         return(frameNew.Memory);
     }
Ejemplo n.º 25
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));

            // Create PimBotServiceProvider
            var featureService  = new FeatureService(new FeatureRepository());
            var keywordService  = new KeywordService(new KeywordRepository());
            var categoryService = new CategoryService(new CategoryRepository());
            var itemService     = new ItemService(new ItemRepository(), featureService, keywordService, categoryService, new PictureRepository());
            var serviceProvider = new PimBotServiceProvider(itemService, keywordService, featureService, categoryService);

            services.AddSingleton <IPimbotServiceProvider>(serviceProvider);

            services.AddScoped <IKeywordService, KeywordService>();

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

            // For testing and develop
            IStorage dataStore = new MemoryStorage();

            // For publishing
//            IStorage dataStore = new CosmosDbStorage(new CosmosDbStorageOptions()
//            {
//                AuthKey = Constants.CosmosDBKey,
//                CollectionId = Constants.CosmosDBCollectionName,
//                CosmosDBEndpoint = new Uri(Constants.CosmosServiceEndpoint),
//                DatabaseId = Constants.CosmosDBDatabaseName,
//            });

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

            services.AddSingleton(conversationState);

            services.AddScoped <IKeywordService, KeywordService>();

            var userState = new UserState(dataStore);

            services.AddSingleton(userState);

            var blobStorage = new AzureBlobTranscriptStore(
                Constants.AzureBlogStorageConnectionString,
                Constants.BlobTranscriptStorageContainerName);

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

                ILogger logger = _loggerFactory.CreateLogger <PimBot.PimBot>();

                // For logging every single conversations
//                options.Middleware.Add(new TranscriptLoggerMiddleware(blobStorage));
                options.Middleware.Add(new ShowTypingMiddleware());
                var middleware = options.Middleware;

                // Catches any errors that occur during a conversation turn and logs them to currently
                // configured ILogger.
                options.OnTurnError = async(context, exception) =>
                {
                    logger.LogError($"Exception caught : {exception}");
                    if (exception is System.Net.Http.HttpRequestException || exception is System.Net.Sockets.SocketException)
                    {
                        await context.SendActivityAsync(Messages.ServerIssue);
                    }
                    else
                    {
                        await context.SendActivityAsync(Messages.SomethingWrong);
                    }
                };
            });
        }
Ejemplo n.º 26
0
 public bool VisitMemoryStorage(MemoryStorage global)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 27
0
        private async Task InitializeSkill(DialogContext dc)
        {
            try
            {
                IStorage storage;

                if (_skillConfiguration.CosmosDbOptions != null)
                {
                    var cosmosDbOptions = _skillConfiguration.CosmosDbOptions;
                    cosmosDbOptions.CollectionId = _skillDefinition.Name;
                    storage = new CosmosDbStorage(cosmosDbOptions);
                }
                else
                {
                    storage = new MemoryStorage();
                }

                // Initialize skill state
                var userState         = new UserState(storage);
                var conversationState = new ConversationState(storage);

                // Create skill instance
                try
                {
                    var skillType = Type.GetType(_skillDefinition.Assembly);
                    _activatedSkill = (IBot)Activator.CreateInstance(skillType, _skillConfiguration, conversationState, userState, _telemetryClient, null, true);
                }
                catch (Exception e)
                {
                    var message = $"Skill ({_skillDefinition.Name}) could not be created.";
                    throw new InvalidOperationException(message, e);
                }

                _inProcAdapter = new InProcAdapter
                {
                    // set up skill turn error handling
                    OnTurnError = async(context, exception) =>
                    {
                        await context.SendActivityAsync(context.Activity.CreateReply(CommonResponses.ErrorMessage_SkillError));

                        await dc.Context.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : $"Skill Error: {exception.Message} | {exception.StackTrace}"));

                        // Log exception in AppInsights
                        _telemetryClient.TrackExceptionEx(exception, context.Activity);
                    },
                };

                _inProcAdapter.Use(new EventDebuggerMiddleware());
                _inProcAdapter.Use(new SetLocaleMiddleware(dc.Context.Activity.Locale ?? "en-us"));
                _inProcAdapter.Use(new AutoSaveStateMiddleware(userState, conversationState));
                _skillInitialized = true;
            }
            catch
            {
                // something went wrong initializing the skill, so end dialog cleanly and throw so the error is logged
                _skillInitialized = false;
                await dc.EndDialogAsync();

                throw;
            }
        }
Ejemplo n.º 28
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>
        /// <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)
        {
            services.AddBot <MultiTurnPromptsBot>(options =>
            {
                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 ?? @".\multi-turn-prompt.bot", secretKey);
                services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot configuration file could not be loaded. ({botConfig})"));

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

                // 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 = "<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 = "<DEFAULT-CONTAINER>";
                // 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);

                // Create and add user state.
                var userState = new UserState(dataStore);
                options.State.Add(userState);
            });

            // Create and register state accessors.
            // Accessors created here are passed into the IBot-derived class on every turn.
            services.AddSingleton <MultiTurnPromptsBotAccessors>(sp =>
            {
                // We need to grab the conversationState we added on the options in the previous step
                var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
                if (options == null)
                {
                    throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the State Accessors");
                }

                var 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 = new MultiTurnPromptsBotAccessors(conversationState, userState)
                {
                    ConversationDialogState = conversationState.CreateProperty <DialogState>("DialogState"),
                    UserProfile             = userState.CreateProperty <UserProfile>("UserProfile"),
                };

                return(accessors);
            });
        }
Ejemplo n.º 29
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>();
        }
Ejemplo n.º 30
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options => options.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddSingleton <IConfiguration>(this.Configuration);

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

            services.AddSingleton <InspectionMiddleware>();

            // Load settings
            var settings = new BotSettings();

            Configuration.Bind(settings);

            IStorage storage = null;

            // Configure storage for deployment
            if (!string.IsNullOrEmpty(settings.CosmosDb.AuthKey))
            {
                storage = new CosmosDbStorage(settings.CosmosDb);
            }
            else
            {
                Console.WriteLine("The settings of CosmosDbStorage is incomplete, please check following settings: settings.CosmosDb");
                storage = new MemoryStorage();
            }

            services.AddSingleton(storage);
            var userState         = new UserState(storage);
            var conversationState = new ConversationState(storage);
            var inspectionState   = new InspectionState(storage);

            // Configure telemetry
            services.AddApplicationInsightsTelemetry();
            var telemetryClient = new BotTelemetryClient(new TelemetryClient());

            services.AddSingleton <IBotTelemetryClient>(telemetryClient);
            services.AddBotApplicationInsights(telemetryClient);

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

            TypeFactory.Configuration = this.Configuration;

            // manage all bot resources
            var resourceExplorer = new ResourceExplorer().AddFolder(botFile);

            var credentials = new MicrosoftAppCredentials(this.Configuration["MicrosoftAppId"], this.Configuration["MicrosoftAppPassword"]);

            services.AddSingleton <IBotFrameworkHttpAdapter, BotFrameworkHttpAdapter>((s) =>
            {
                var adapter = new BotFrameworkHttpAdapter(new ConfigurationCredentialProvider(this.Configuration));
                adapter
                .UseStorage(storage)
                .UseState(userState, conversationState)
                .UseAdaptiveDialogs()
                .UseResourceExplorer(resourceExplorer)
                .UseLanguageGeneration(resourceExplorer, "common.lg")
                .Use(new RegisterClassMiddleware <IConfiguration>(Configuration))
                .Use(new InspectionMiddleware(inspectionState, userState, conversationState, credentials));

                if (!string.IsNullOrEmpty(settings.BlobStorage.ConnectionString) && !string.IsNullOrEmpty(settings.BlobStorage.Container))
                {
                    adapter.Use(new TranscriptLoggerMiddleware(new AzureBlobTranscriptStore(settings.BlobStorage.ConnectionString, settings.BlobStorage.Container)));
                }
                else
                {
                    Console.WriteLine("The settings of TranscriptLoggerMiddleware is incomplete, please check following settings: settings.BlobStorage.ConnectionString, settings.BlobStorage.Container");
                }

                adapter.OnTurnError = async(turnContext, exception) =>
                {
                    await turnContext.SendActivityAsync(exception.Message).ConfigureAwait(false);
                    telemetryClient.TrackException(new Exception("Exceptions: " + exception.Message));
                    await conversationState.ClearStateAsync(turnContext).ConfigureAwait(false);
                    await conversationState.SaveChangesAsync(turnContext).ConfigureAwait(false);
                };
                return(adapter);
            });

            services.AddSingleton <IBot, ComposerBot>((sp) => new ComposerBot("Main.dialog", conversationState, userState, resourceExplorer, DebugSupport.SourceMap, telemetryClient));
        }
Ejemplo n.º 31
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// <param name="services">Specifies the contract for a <see cref="IServiceCollection"/> of service descriptors.</param>
        /// </summary>
        public void ConfigureServices(IServiceCollection services)
        {
            // Memory Storage 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/
            // Un-comment 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 = "<DEFAULT-CONTAINER>";
            // var storageContainer = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container;
            // IStorage 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);

            var privateConversationState = new PrivateConversationState(dataStore);

            services.AddSingleton(privateConversationState);

            services.AddSingleton <StateAccessors>(sp => new StateAccessors(userState, conversationState, privateConversationState)
            {
                DialogStateAccessor = conversationState.CreateProperty <DialogState>(nameof(DialogState)),
                LoggedUserAccessor  = privateConversationState.CreateProperty <LoggedUserState>(nameof(LoggedUserState)),
                LuisStateAccessor   = userState.CreateProperty <LuisState>(nameof(LuisState)),
                CRMStateAccessor    = userState.CreateProperty <CRMState>(nameof(CRMState))
            });

            services.AddOptions();

            // Load settings from appsettings.json
            services.Configure <BotConfig>(Configuration.GetSection("BotConfig"));
            services.Configure <LuisConfig>(Configuration.GetSection("LuisConfig"));
            services.Configure <ServicesConfig>(Configuration.GetSection("ServicesConfig"));

            services.AddSingleton <BotServices>(sp => ActivatorUtilities.CreateInstance <BotServices>(sp));

            services.AddBot <ProxiCallBot>(options =>
            {
                options.CredentialProvider = new SimpleCredentialProvider(Configuration.GetSection("BotConfig")["MicrosoftAppId"], Configuration.GetSection("BotConfig")["MicrosoftAppPassword"]);

                // Catches any errors that occur during a conversation turn and logs them to currently
                // configured ILogger.
                ILogger logger = _loggerFactory.CreateLogger <ProxiCallBot>();

                options.OnTurnError = async(context, exception) =>
                {
                    var errorMessage = ExceptionHandler(exception);
                    logger.LogError($"Exception caught : {exception}");

                    var activity    = MessageFactory.Text(errorMessage, errorMessage, InputHints.AcceptingInput);
                    activity.Locale = CulturedBot.Culture?.Name;
                    await context.SendActivityAsync(activity);
                };

                //Adding Teams middleware
                options.Middleware.Add(
                    new TeamsMiddleware(
                        new ConfigurationCredentialProvider(this.Configuration)
                        )
                    );
            });

            services.AddHttpClient <AccountService>();
            services.AddHttpClient <CompanyService>();
            services.AddHttpClient <LeadService>();
            services.AddHttpClient <OpportunityService>();
            services.AddHttpClient <ProductService>();

            services.AddLocalization(options => options.ResourcesPath = "Resources");
        }
Ejemplo n.º 32
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;

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

            try
            {
                botConfig = BotConfiguration.Load(botFilePath ?? @".\BotConfiguration.bot", 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 config file could not be loaded. ({botConfig})"));

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

            // Memory Storage 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/
            // Un-comment 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 and add conversation state.
            var conversationState = new ConversationState(dataStore);

            services.AddSingleton(conversationState);

            var userState = new UserState(dataStore);

            services.AddSingleton(userState);

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

                // Catches any errors that occur during a conversation turn and logs them to currently
                // configured ILogger.
                ILogger logger      = _loggerFactory.CreateLogger <BasicBot>();
                options.OnTurnError = async(context, exception) =>
                {
                    logger.LogError($"Exception caught : {exception}");
                    await context.SendActivityAsync("Sorry, it looks like something went wrong.");
                };
            });
        }
Ejemplo n.º 33
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)
        {
            services.AddMvc();

            // create luis recognizer
            var luisApplication = new LuisApplication(
                Configuration["LuisAppId"],
                Configuration["LuisAPIKey"],
                Configuration["LuisAPIHostName"]);

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

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

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

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

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

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

            // Create the telemetry middleware to initialize telemetry gathering
            //services.AddSingleton<TelemetryInitializerMiddleware>();

            // Create the telemetry middleware (used by the telemetry initializer) to track conversation events
            services.AddSingleton <TelemetryLoggerMiddleware>();
            // Create the storage we'll be using for User and Conversation state. (Memory is great for testing purposes.)
            services.AddSingleton <IStorage, MemoryStorage>();
            //services.AddSingleton<IStorage, AzureBlobStorage>();

            // Create the User state. (Used in this bot's Dialog implementation.)
            services.AddSingleton <UserState>();

            // Create the Conversation state. (Used by the Dialog system itself.)
            services.AddSingleton <ConversationState>();

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

            // Memory Storage is for local bot debugging only. When the bot
            // is restarted, everything stored in memory will be gone.
            IStorage dataStore = new MemoryStorage();
            //IStorage dataStore = new AzureBlobStorage(Configuration["BlobStorageConnection"], Configuration["BlobContainerName"]);

            var conversationState = new ConversationState(dataStore);

            services.AddSingleton(conversationState);

            var userState = new UserState(dataStore);

            services.AddSingleton(userState);

            //var personalityChatOptions = new PersonalityChatMiddlewareOptions(
            //  respondOnlyIfChat: true,
            //  scoreThreshold: 0.5F,
            //  botPersona: PersonalityChatPersona.Humorous);
            //services.AddSingleton(new PersonalityChatMiddleware(personalityChatOptions));


            services.AddTransient <IBot, EchoBot>();

            // Create and register state accessors.
            // Accessors created here are passed into the IBot-derived class on every turn.
            services.AddSingleton(sp =>
            {
                // We need to grab the conversationState we added on the options in the previous step
                var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
                if (options == null)
                {
                    throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the State Accessors");
                }

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

                return(accessors);
            });

            // Add QnA Maker here
        }
Ejemplo n.º 34
0
 public bool VisitMemoryStorage(MemoryStorage global, bool defining)
 {
     return(false);
 }
Ejemplo n.º 35
0
 public Identifier VisitMemoryStorage(MemoryStorage global)
 {
     return(procCalling.Frame.Memory);
 }
Ejemplo n.º 36
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)
        {
            services.AddBot <PictureBot>(options =>
            {
                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 ?? @".\BotConfiguration.bot", secretKey);
                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, endpointService.AppPassword);

                // Creates a logger for the application to use.
                ILogger logger = _loggerFactory.CreateLogger <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();

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

            // 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 = options.State.OfType <ConversationState>().FirstOrDefault();
                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 =>
            {
                // Get LUIS information
                var luisApp = new LuisApplication("be8b4fcb-c354-4361-98d5-a4d399e68274",
                                                  "e603d56cb046479bb7e6bc02df4b8e42",
                                                  "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/be8b4fcb-c354-4361-98d5-a4d399e68274?subscription-key=e603d56cb046479bb7e6bc02df4b8e42&timezoneOffset=-360&q=");

                // 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);
            });
        }
Ejemplo n.º 37
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 ?? @".\JayResortBot.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 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 dataStore         = new MemoryStorage();
            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 <JayResortBot>(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.");
                    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));
            });
        }