public DeleteEventDialog( SkillConfiguration services, IStatePropertyAccessor <CalendarSkillState> accessor, IServiceManager serviceManager) : base(nameof(DeleteEventDialog), services, accessor, serviceManager) { var deleteEvent = new WaterfallStep[] { GetAuthToken, AfterGetAuthToken, FromTokenToStartTime, ConfirmBeforeDelete, DeleteEventByStartTime, }; var updateStartTime = new WaterfallStep[] { UpdateStartTime, AfterUpdateStartTime, }; AddDialog(new WaterfallDialog(Actions.DeleteEvent, deleteEvent)); AddDialog(new WaterfallDialog(Actions.UpdateStartTime, updateStartTime)); // Set starting dialog for component InitialDialogId = Actions.DeleteEvent; }
public ToDoSkillDialog( string dialogId, SkillConfiguration services, IStatePropertyAccessor <ToDoSkillState> accessor, ITaskService serviceManager) : base(dialogId) { _services = services; _accessor = accessor; _serviceManager = serviceManager; if (!_services.AuthenticationConnections.Any()) { throw new Exception("You must configure an authentication connection in your bot file before using this component."); } foreach (var connection in services.AuthenticationConnections) { AddDialog(new OAuthPrompt( connection.Key, new OAuthPromptSettings { ConnectionName = connection.Value, Text = $"Please login with your {connection.Key} account.", Timeout = 30000, }, AuthPromptValidator)); } AddDialog(new EventPrompt(SkillModeAuth, "tokens/response", TokenResponseValidator)); AddDialog(new MultiProviderAuthDialog(services)); AddDialog(new TextPrompt(Action.Prompt)); }
public FindPointOfInterestDialog( SkillConfiguration services, IStatePropertyAccessor <PointOfInterestSkillState> accessor, IServiceManager serviceManager, IBotTelemetryClient telemetryClient) : base(nameof(FindPointOfInterestDialog), services, accessor, serviceManager, telemetryClient) { TelemetryClient = telemetryClient; var findPointOfInterest = new WaterfallStep[] { GetPointOfInterestLocations, ResponseToGetRoutePrompt, }; // Define the conversation flow using a waterfall model. AddDialog(new WaterfallDialog(Action.FindPointOfInterest, findPointOfInterest) { TelemetryClient = telemetryClient }); AddDialog(new RouteDialog(services, Accessor, ServiceManager, TelemetryClient)); // Set starting dialog for component InitialDialogId = Action.FindPointOfInterest; }
public SummaryDialog( SkillConfiguration services, IStatePropertyAccessor <CalendarSkillState> accessor, IServiceManager serviceManager) : base(nameof(SummaryDialog), services, accessor, serviceManager) { var showSummary = new WaterfallStep[] { IfClearContextStep, GetAuthToken, AfterGetAuthToken, ShowEventsSummary, PromptToRead, CallReadEventDialog, }; var readEvent = new WaterfallStep[] { ReadEvent, AfterReadOutEvent, }; // Define the conversation flow using a waterfall model. AddDialog(new WaterfallDialog(Actions.ShowEventsSummary, showSummary)); AddDialog(new WaterfallDialog(Actions.Read, readEvent)); // Set starting dialog for component InitialDialogId = Actions.ShowEventsSummary; }
public AddToDoItemDialog( SkillConfiguration services, IStatePropertyAccessor <ToDoSkillState> accessor, ITaskService serviceManager) : base(nameof(AddToDoItemDialog), services, accessor, serviceManager) { var addToDoTask = new WaterfallStep[] { GetAuthToken, AfterGetAuthToken, ClearContext, CollectToDoTaskContent, AddToDoTask, }; var collectToDoTaskContent = new WaterfallStep[] { AskToDoTaskContent, AfterAskToDoTaskContent, }; // Define the conversation flow using a waterfall model. AddDialog(new WaterfallDialog(Action.AddToDoTask, addToDoTask)); AddDialog(new WaterfallDialog(Action.CollectToDoTaskContent, collectToDoTaskContent)); // Set starting dialog for component InitialDialogId = Action.AddToDoTask; }
public MarkToDoItemDialog( SkillConfiguration services, IStatePropertyAccessor <ToDoSkillState> accessor, ITaskService serviceManager) : base(nameof(MarkToDoItemDialog), services, accessor, serviceManager) { var markToDoTask = new WaterfallStep[] { GetAuthToken, AfterGetAuthToken, ClearContext, InitAllTasks, CollectToDoTaskIndex, this.MarkToDoTaskCompleted, }; var collectToDoTaskIndex = new WaterfallStep[] { AskToDoTaskIndex, AfterAskToDoTaskIndex, }; // Define the conversation flow using a waterfall model. AddDialog(new WaterfallDialog(Action.MarkToDoTaskCompleted, markToDoTask)); AddDialog(new WaterfallDialog(Action.CollectToDoTaskIndex, collectToDoTaskIndex)); // Set starting dialog for component InitialDialogId = Action.MarkToDoTaskCompleted; }
public CalendarSkill(SkillConfiguration services, ConversationState conversationState, UserState userState, IServiceManager serviceManager = null, bool skillMode = false) { _skillMode = skillMode; _services = services ?? throw new ArgumentNullException(nameof(services)); _userState = userState ?? throw new ArgumentNullException(nameof(userState)); _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState)); _serviceManager = serviceManager ?? new ServiceManager(_services); _dialogs = new DialogSet(_conversationState.CreateProperty <DialogState>(nameof(DialogState))); _dialogs.Add(new MainDialog(_services, _conversationState, _userState, _serviceManager, _skillMode)); }
/// <summary> /// Initializes a new instance of the <see cref="CommuteIntent"/> class. /// </summary> /// <param name="skillClient">The skill client to use.</param> /// <param name="tflClient">The TfL API client to use.</param> /// <param name="contextAccessor">The AWS Lambda context accessor to use.</param> /// <param name="config">The skill configuration to use.</param> /// <param name="logger">The logger to use.</param> public CommuteIntent( ISkillClient skillClient, ITflClient tflClient, SkillConfiguration config, ILogger <CommuteIntent> logger) { Config = config; Logger = logger; SkillClient = skillClient; TflClient = tflClient; }
public RouteDialog( SkillConfiguration services, IStatePropertyAccessor <PointOfInterestSkillState> accessor, IServiceManager serviceManager, IBotTelemetryClient telemetryClient) : base(nameof(RouteDialog), services, accessor, serviceManager, telemetryClient) { TelemetryClient = telemetryClient; var checkForActiveRouteAndLocation = new WaterfallStep[] { CheckIfActiveRouteExists, CheckIfFoundLocationExists, CheckIfActiveLocationExists, }; var findRouteToActiveLocation = new WaterfallStep[] { GetRoutesToActiveLocation, ResponseToStartRoutePrompt, }; var findAlongRoute = new WaterfallStep[] { GetPointOfInterestLocations, ResponseToGetRoutePrompt, }; var findPointOfInterest = new WaterfallStep[] { GetPointOfInterestLocations, }; // Define the conversation flow using a waterfall model. AddDialog(new WaterfallDialog(Action.GetActiveRoute, checkForActiveRouteAndLocation) { TelemetryClient = telemetryClient }); AddDialog(new WaterfallDialog(Action.FindAlongRoute, findAlongRoute) { TelemetryClient = telemetryClient }); AddDialog(new WaterfallDialog(Action.FindRouteToActiveLocation, findRouteToActiveLocation) { TelemetryClient = telemetryClient }); AddDialog(new WaterfallDialog(Action.FindPointOfInterest, findPointOfInterest) { TelemetryClient = telemetryClient }); // Set starting dialog for component InitialDialogId = Action.GetActiveRoute; }
public PointOfInterestSkill(SkillConfiguration services, ConversationState conversationState, UserState userState, IBotTelemetryClient telemetryClient, IServiceManager serviceManager = null, bool skillMode = false) { _skillMode = skillMode; _services = services ?? throw new ArgumentNullException(nameof(services)); _userState = userState ?? throw new ArgumentNullException(nameof(userState)); _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState)); _serviceManager = serviceManager ?? new ServiceManager(); _telemetryClient = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient)); _dialogs = new DialogSet(_conversationState.CreateProperty <DialogState>(nameof(DialogState))); _dialogs.Add(new MainDialog(_services, _conversationState, _userState, _telemetryClient, _serviceManager, _skillMode)); }
public static void upload(string filepath) { var data = Helpers.LoadCSV(filepath); // Map columns var mapper = new CSVMapper { DataTable = data }; if (mapper.map("name", new[] { "NAME", "ID", "DISPLAYNAME", "SKILL" }) == -1) { throw new ArgumentException("Name column not found", "name"); } mapper.map("workgroups", new[] { "WORKGROUP", "WORKGROUPS", "GROUP", "GROUPS" }); mapper.map("users", new[] { "USER", "USERS", "AGENT", "AGENTS" }); var configurations = new SkillConfigurationList(ConfigurationManager.GetInstance(Application.ICSession)); foreach (DataRow row in data.Rows) { SkillConfiguration skill = null; var name = row.Field <string>(mapper["name"]); if (string.IsNullOrWhiteSpace(name)) { continue; } if (!SkillConfigurations.Any(item => item.ConfigurationId.DisplayName == name)) { skill = configurations.CreateObject(); skill.SetConfigurationId(name); skill.SetDisplayName(name); } else { skill = SkillConfigurations.First(item => item.ConfigurationId.DisplayName == name); skill.PrepareForEdit(); } if (mapper["workgroups"] > -1) { skill.WorkgroupAssignments.Value.Clear(); Helpers.ParseManySkillSettings(row.Field <string>(mapper["workgroups"])).ForEach(x => skill.WorkgroupAssignments.Value.Add(x)); } if (mapper["users"] > -1) { skill.UserAssignments.Value.Clear(); Helpers.ParseManySkillSettings(row.Field <string>(mapper["users"])).ForEach(x => skill.UserAssignments.Value.Add(x)); } skill.Commit(); } _SkillConfigurations = null; // So the list is fetched again }
public CalendarSkillDialog( string dialogId, SkillConfiguration services, IStatePropertyAccessor <CalendarSkillState> accessor, IServiceManager serviceManager) : base(dialogId) { Services = services; Accessor = accessor; ServiceManager = serviceManager; if (!Services.AuthenticationConnections.Any()) { throw new Exception("You must configure an authentication connection in your bot file before using this component."); } foreach (var connection in services.AuthenticationConnections) { AddDialog(new OAuthPrompt( connection.Key, new OAuthPromptSettings { ConnectionName = connection.Value, Text = $"Please login with your {connection.Key} account.", Timeout = 30000, }, AuthPromptValidator)); } AddDialog(new EventPrompt(SkillModeAuth, "tokens/response", TokenResponseValidator)); AddDialog(new MultiProviderAuthDialog(services)); AddDialog(new TextPrompt(Actions.Prompt)); AddDialog(new ConfirmPrompt(Actions.TakeFurtherAction, null, Culture.English) { Style = ListStyle.SuggestedAction }); AddDialog(new DateTimePrompt(Actions.DateTimePrompt, null, Culture.English)); AddDialog(new DateTimePrompt(Actions.DateTimePromptForUpdateDelete, DateTimePromptValidator, Culture.English)); AddDialog(new ChoicePrompt(Actions.Choice, ChoiceValidator, Culture.English) { Style = ListStyle.None, }); AddDialog(new ChoicePrompt(Actions.EventChoice, null, Culture.English) { Style = ListStyle.Inline, ChoiceOptions = new ChoiceFactoryOptions { InlineSeparator = string.Empty, InlineOr = string.Empty, InlineOrMore = string.Empty, IncludeNumbers = false } }); }
public MainDialog(SkillConfiguration services, ConversationState conversationState, UserState userState, IBotTelemetryClient telemetryClient, IServiceManager serviceManager, bool skillMode) : base(nameof(MainDialog), telemetryClient) { _skillMode = skillMode; _services = services; _conversationState = conversationState; _userState = userState; _serviceManager = serviceManager; // Initialize state accessor _stateAccessor = _conversationState.CreateProperty <weatherskillState>(nameof(weatherskillState)); _dialogStateAccessor = _conversationState.CreateProperty <DialogState>(nameof(DialogState)); RegisterDialogs(); }
public void ConfigureServices() { _skillConfiguration = new SkillConfiguration(_configuration); _containerBuilder.RegisterInstance(_skillConfiguration); _containerBuilder.Register(c => { var opt = new DbContextOptionsBuilder <SkillContext>(); opt.UseSqlServer(_skillConfiguration.ConnectionString); return(new SkillContext(opt.Options)); }) .AsSelf() .InstancePerLifetimeScope(); }
public PointOfInterestSkillDialog( string dialogId, SkillConfiguration services, IStatePropertyAccessor <PointOfInterestSkillState> accessor, IServiceManager serviceManager) : base(dialogId) { Services = services; Accessor = accessor; ServiceManager = serviceManager; AddDialog(new TextPrompt(Action.Prompt, CustomPromptValidatorAsync)); AddDialog(new ConfirmPrompt(Action.ConfirmPrompt) { Style = ListStyle.Auto, }); }
public CancelRouteDialog( SkillConfiguration services, IStatePropertyAccessor <PointOfInterestSkillState> accessor, IServiceManager serviceManager) : base(nameof(CancelRouteDialog), services, accessor, serviceManager) { var cancelRoute = new WaterfallStep[] { CancelActiveRoute, }; // Define the conversation flow using a waterfall model. AddDialog(new WaterfallDialog(Action.CancelActiveRoute, cancelRoute)); // Set starting dialog for component InitialDialogId = Action.CancelActiveRoute; }
public NextMeetingDialog( SkillConfiguration services, IStatePropertyAccessor <CalendarSkillState> accessor, IServiceManager serviceManager) : base(nameof(NextMeetingDialog), services, accessor, serviceManager) { var nextMeeting = new WaterfallStep[] { GetAuthToken, AfterGetAuthToken, ShowNextEvent, }; // Define the conversation flow using a waterfall model. AddDialog(new WaterfallDialog(Actions.ShowEventsSummary, nextMeeting)); // Set starting dialog for component InitialDialogId = Actions.ShowEventsSummary; }
public ToDoSkillDialog( string dialogId, SkillConfiguration services, IStatePropertyAccessor <ToDoSkillState> accessor, ITaskService serviceManager) : base(dialogId) { Services = services; Accessor = accessor; ServiceManager = serviceManager; if (!Services.AuthenticationConnections.Any()) { throw new Exception("You must configure an authentication connection in your bot file before using this component."); } AddDialog(new EventPrompt(SkillModeAuth, "tokens/response", TokenResponseValidator)); AddDialog(new MultiProviderAuthDialog(services)); AddDialog(new TextPrompt(Action.Prompt)); }
public MainDialog( SkillConfiguration services, ConversationState conversationState, UserState userState, IServiceManager serviceManager, bool skillMode) : base(nameof(MainDialog)) { _skillMode = skillMode; _services = services; _userState = userState; _conversationState = conversationState; _serviceManager = serviceManager; // Initialize state accessor _stateAccessor = _conversationState.CreateProperty <PointOfInterestSkillState>(nameof(PointOfInterestSkillState)); // Register dialogs RegisterDialogs(); }
public ToDoSkill(SkillConfiguration services, ConversationState conversationState, UserState userState, ITaskService serviceManager = null, bool skillMode = false) { _skillMode = skillMode; _services = services ?? throw new ArgumentNullException(nameof(services)); _userState = userState ?? throw new ArgumentNullException(nameof(userState)); _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState)); var isOutlookProvider = _services.Properties.ContainsKey("TaskServiceProvider") && _services.Properties["TaskServiceProvider"].ToString().Equals(ProviderTypes.Outlook.ToString(), StringComparison.InvariantCultureIgnoreCase); ITaskService taskService = new OneNoteService(); if (isOutlookProvider) { taskService = new OutlookService(); } _serviceManager = serviceManager ?? taskService; _dialogs = new DialogSet(_conversationState.CreateProperty <DialogState>(nameof(DialogState))); _dialogs.Add(new MainDialog(_services, _conversationState, _userState, _serviceManager, _skillMode)); }
/// <summary> /// Wire up each skill into the Virtual Assistant. /// </summary> /// <param name="skillName">Name of the skill.</param> /// <param name="skillType">Assembly reference to skill.</param> /// <param name="dispatchIntent">Dispatch Intent.</param> /// <param name="luisServiceIds">LUIS service IDs used by skill.</param> /// <param name="authConnections">Authentication connections.</param> /// <param name="localeConfiguration">Locale configuration.</param> /// <param name="supportedProviders">Supported Providers (optional).</param> private void InitialiseSkill(string skillName, Type skillType, string dispatchIntent, string[] luisServiceIds, string[] authConnections, Dictionary <string, LocaleConfiguration> localeConfiguration, string[] supportedProviders = null) { // Prepare skill configuration var skillConfiguration = new SkillConfiguration(); skillConfiguration.AuthenticationConnections.Add("DummyAuth", "DummyAuthConnection"); skillConfiguration.LocaleConfigurations = this.BotServices.LocaleConfigurations; this.BotServices.SkillConfigurations.Add(skillName, skillConfiguration); // Skill Registration var skillDefinition = new SkillDefinition { Assembly = skillType.AssemblyQualifiedName, Id = skillName, Name = skillName, DispatchIntent = dispatchIntent, LuisServiceIds = luisServiceIds, SupportedProviders = supportedProviders, }; this.BotServices.SkillDefinitions.Add(skillDefinition); }
public CalendarSkillDialog( string dialogId, SkillConfiguration services, IStatePropertyAccessor <CalendarSkillState> accessor, IServiceManager serviceManager) : base(dialogId) { _services = services; _accessor = accessor; _serviceManager = serviceManager; var oauthSettings = new OAuthPromptSettings() { ConnectionName = _services.AuthConnectionName, Text = $"Authentication", Title = "Signin", Timeout = 300000, // User has 5 minutes to login }; AddDialog(new EventPrompt(SkillModeAuth, "tokens/response", TokenResponseValidator)); AddDialog(new OAuthPrompt(LocalModeAuth, oauthSettings, AuthPromptValidator)); AddDialog(new TextPrompt(Actions.Prompt)); AddDialog(new ConfirmPrompt(Actions.TakeFurtherAction, null, Culture.English) { Style = ListStyle.SuggestedAction }); AddDialog(new DateTimePrompt(Actions.DateTimePrompt, null, Culture.English)); AddDialog(new DateTimePrompt(Actions.DateTimePromptForUpdateDelete, DateTimePromptValidator, Culture.English)); AddDialog(new ChoicePrompt(Actions.Choice, ChoiceValidator, Culture.English) { Style = ListStyle.None, }); AddDialog(new ChoicePrompt(Actions.EventChoice, null, Culture.English) { Style = ListStyle.Inline, ChoiceOptions = new ChoiceFactoryOptions { InlineSeparator = string.Empty, InlineOr = string.Empty, InlineOrMore = string.Empty, IncludeNumbers = false } }); }
public ToDoSkillDialog( string dialogId, SkillConfiguration services, IStatePropertyAccessor <ToDoSkillState> accessor, ITaskService serviceManager) : base(dialogId) { _services = services; _accessor = accessor; _serviceManager = serviceManager; var oauthSettings = new OAuthPromptSettings() { ConnectionName = _services.AuthConnectionName ?? throw new Exception("The authentication connection has not been initialized."), Text = $"Authentication", Title = "Signin", Timeout = 300000, // User has 5 minutes to login }; AddDialog(new EventPrompt(SkillModeAuth, "tokens/response", TokenResponseValidator)); AddDialog(new OAuthPrompt(LocalModeAuth, oauthSettings, AuthPromptValidator)); AddDialog(new TextPrompt(Action.Prompt)); }
public UpdateEventDialog( SkillConfiguration services, IStatePropertyAccessor <CalendarSkillState> accessor, IServiceManager serviceManager) : base(nameof(UpdateEventDialog), services, accessor, serviceManager) { var updateEvent = new WaterfallStep[] { GetAuthToken, AfterGetAuthToken, FromTokenToStartTime, FromEventsToNewDate, ConfirmBeforeUpdate, UpdateEventTime, }; var updateStartTime = new WaterfallStep[] { UpdateStartTime, AfterUpdateStartTime, }; var updateNewStartTime = new WaterfallStep[] { GetNewEventTime, AfterGetNewEventTime, }; // Define the conversation flow using a waterfall model. AddDialog(new WaterfallDialog(Actions.UpdateEventTime, updateEvent)); AddDialog(new WaterfallDialog(Actions.UpdateStartTime, updateStartTime)); AddDialog(new WaterfallDialog(Actions.UpdateNewStartTime, updateNewStartTime)); // Set starting dialog for component InitialDialogId = Actions.UpdateEventTime; }
public void ConfigureServices(IServiceCollection services) { // add background task queue services.AddSingleton<IBackgroundTaskQueue, BackgroundTaskQueue>(); services.AddHostedService<QueuedHostedService>(); // Load the connected services from .bot file. var botFilePath = Configuration.GetSection("botFilePath")?.Value; var botFileSecret = Configuration.GetSection("botFileSecret")?.Value; var botConfig = BotConfiguration.Load(botFilePath ?? @".\PointOfInterestSkill.bot", botFileSecret); services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot config file could not be loaded.")); // Use Application Insights services.AddBotApplicationInsights(botConfig); // Initializes your bot service clients and adds a singleton that your Bot can access through dependency injection. var parameters = Configuration.GetSection("parameters")?.Get<string[]>(); var configuration = Configuration.GetSection("configuration")?.GetChildren()?.ToDictionary(x => x.Key, y => y.Value as object); var languageModels = Configuration.GetSection("languageModels").Get<Dictionary<string, Dictionary<string, string>>>(); var connectedServices = new SkillConfiguration(botConfig, languageModels, null, parameters, configuration); services.AddSingleton<SkillConfigurationBase>(sp => connectedServices); var supportedLanguages = languageModels.Select(l => l.Key).ToArray(); var responses = new IResponseIdCollection[] { new CancelRouteResponses(), new FindPointOfInterestResponses(), new POIMainResponses(), new RouteResponses(), new POISharedResponses(), }; var responseManager = new ResponseManager(responses, supportedLanguages); // Register bot responses for all supported languages. services.AddSingleton(sp => responseManager); // Initialize Bot State var cosmosDbService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.CosmosDB) ?? throw new Exception("Please configure your CosmosDb service in your .bot file."); var cosmosDb = cosmosDbService as CosmosDbService; var cosmosOptions = new CosmosDbStorageOptions() { CosmosDBEndpoint = new Uri(cosmosDb.Endpoint), AuthKey = cosmosDb.Key, CollectionId = cosmosDb.Collection, DatabaseId = cosmosDb.Database, }; var dataStore = new CosmosDbStorage(cosmosOptions); var userState = new UserState(dataStore); var conversationState = new ConversationState(dataStore); var proactiveState = new ProactiveState(dataStore); services.AddSingleton(dataStore); services.AddSingleton(userState); services.AddSingleton(conversationState); services.AddSingleton(proactiveState); services.AddSingleton(new BotStateSet(userState, conversationState)); var environment = _isProduction ? "production" : "development"; var service = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.Endpoint && s.Name == environment); if (!(service is EndpointService endpointService)) { throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{environment}'."); } services.AddSingleton(endpointService); services.AddSingleton<IServiceManager, ServiceManager>(); // Add the bot with options services.AddBot<PointOfInterestSkill>(options => { options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword); // Telemetry Middleware (logs activity messages in Application Insights) var sp = services.BuildServiceProvider(); var telemetryClient = sp.GetService<IBotTelemetryClient>(); var appInsightsLogger = new TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: true); options.Middleware.Add(appInsightsLogger); // Catches any errors that occur during a conversation turn and logs them to AppInsights. options.OnTurnError = async (context, exception) => { CultureInfo.CurrentUICulture = new CultureInfo(context.Activity.Locale); await context.SendActivityAsync(responseManager.GetResponse(POISharedResponses.PointOfInterestErrorMessage)); await context.SendActivityAsync(new Activity(type: ActivityTypes.Trace, text: $"PointOfInterestSkill Error: {exception.Message} | {exception.StackTrace}")); telemetryClient.TrackExceptionEx(exception, context.Activity); }; // Transcript Middleware (saves conversation history in a standard format) var storageService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.BlobStorage) ?? throw new Exception("Please configure your Azure Storage service in your .bot file."); var blobStorage = storageService as BlobStorageService; var transcriptStore = new AzureBlobTranscriptStore(blobStorage.ConnectionString, blobStorage.Container); var transcriptMiddleware = new TranscriptLoggerMiddleware(transcriptStore); options.Middleware.Add(transcriptMiddleware); // Typing Middleware (automatically shows typing when the bot is responding/working) var typingMiddleware = new ShowTypingMiddleware(); options.Middleware.Add(typingMiddleware); options.Middleware.Add(new EventDebuggerMiddleware()); options.Middleware.Add(new AutoSaveStateMiddleware(userState, conversationState)); }); }
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_2); // add background task queue services.AddSingleton <IBackgroundTaskQueue, BackgroundTaskQueue>(); services.AddHostedService <QueuedHostedService>(); // Load the connected services from .bot file. var botFilePath = Configuration.GetSection("botFilePath")?.Value; var botFileSecret = Configuration.GetSection("botFileSecret")?.Value; var botConfig = BotConfiguration.Load(botFilePath ?? @".\automotiveskill.bot", botFileSecret); services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot config file could not be loaded.")); // Use Application Insights services.AddBotApplicationInsights(botConfig); // Initializes your bot service clients and adds a singleton that your Bot can access through dependency injection. var parameters = Configuration.GetSection("Parameters")?.Get <string[]>(); var configuration = Configuration.GetSection("Configuration")?.Get <Dictionary <string, object> >(); var supportedProviders = Configuration.GetSection("SupportedProviders")?.Get <string[]>(); var languageModels = Configuration.GetSection("languageModels").Get <Dictionary <string, Dictionary <string, string> > >(); var connectedServices = new SkillConfiguration(botConfig, languageModels, supportedProviders, parameters, configuration); services.AddSingleton <SkillConfigurationBase>(sp => connectedServices); var supportedLanguages = languageModels.Select(l => l.Key).ToArray(); var responseManager = new ResponseManager( supportedLanguages, new AutomotiveSkillMainResponses(), new AutomotiveSkillSharedResponses(), new VehicleSettingsResponses()); // Register bot responses for all supported languages. services.AddSingleton(sp => responseManager); // Initialize Bot State var cosmosDbService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.CosmosDB) ?? throw new Exception("Please configure your CosmosDb service in your .bot file."); var cosmosDb = cosmosDbService as CosmosDbService; var cosmosOptions = new CosmosDbStorageOptions() { CosmosDBEndpoint = new Uri(cosmosDb.Endpoint), AuthKey = cosmosDb.Key, CollectionId = cosmosDb.Collection, DatabaseId = cosmosDb.Database, }; var dataStore = new CosmosDbStorage(cosmosOptions); var userState = new UserState(dataStore); var conversationState = new ConversationState(dataStore); var proactiveState = new ProactiveState(dataStore); services.AddSingleton(dataStore); services.AddSingleton(userState); services.AddSingleton(conversationState); services.AddSingleton(proactiveState); services.AddSingleton(new BotStateSet(userState, conversationState)); var environment = _isProduction ? "production" : "development"; var service = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.Endpoint && s.Name == environment); if (!(service is EndpointService endpointService)) { throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{environment}'."); } services.AddSingleton(endpointService); // Initialize service client services.AddSingleton <IServiceManager, ServiceManager>(); // HttpContext required for path resolution services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); // Add the bot services.AddSingleton <IBot, AutomotiveSkill>(); // Add the http adapter to enable MVC style bot API services.AddTransient <IBotFrameworkHttpAdapter>((sp) => { var credentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword); // Telemetry Middleware (logs activity messages in Application Insights) var telemetryClient = sp.GetService <IBotTelemetryClient>(); var botFrameworkHttpAdapter = new BotFrameworkHttpAdapter(credentialProvider) { OnTurnError = async(context, exception) => { await context.SendActivityAsync(responseManager.GetResponse(AutomotiveSkillSharedResponses.ErrorMessage)); await context.SendActivityAsync(new Activity(type: ActivityTypes.Trace, text: $"Skill Error: {exception.Message} | {exception.StackTrace}")); telemetryClient.TrackExceptionEx(exception, context.Activity); } }; var appInsightsLogger = new TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: true); botFrameworkHttpAdapter.Use(appInsightsLogger); // Transcript Middleware (saves conversation history in a standard format) var storageService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.BlobStorage) ?? throw new Exception("Please configure your Azure Storage service in your .bot file."); var blobStorage = storageService as BlobStorageService; var transcriptStore = new AzureBlobTranscriptStore(blobStorage.ConnectionString, blobStorage.Container); var transcriptMiddleware = new TranscriptLoggerMiddleware(transcriptStore); botFrameworkHttpAdapter.Use(transcriptMiddleware); // Typing Middleware (automatically shows typing when the bot is responding/working) var typingMiddleware = new ShowTypingMiddleware(); botFrameworkHttpAdapter.Use(typingMiddleware); botFrameworkHttpAdapter.Use(new AutoSaveStateMiddleware(userState, conversationState)); return(botFrameworkHttpAdapter); }); }
public Skill(SkillConfiguration ic_configuration) { id = ic_configuration.ConfigurationId.Id; DisplayName = ic_configuration.ConfigurationId.DisplayName; configuration = ic_configuration; }
public CreateEventDialog( SkillConfiguration services, IStatePropertyAccessor <CalendarSkillState> accessor, IServiceManager serviceManager) : base(nameof(CreateEventDialog), services, accessor, serviceManager) { var createEvent = new WaterfallStep[] { GetAuthToken, AfterGetAuthToken, CollectAttendees, CollectTitle, CollectContent, CollectStartDate, CollectStartTime, CollectDuration, CollectLocation, ConfirmBeforeCreate, CreateEvent, }; var updateAddress = new WaterfallStep[] { UpdateAddress, AfterUpdateAddress, }; var confirmAttendee = new WaterfallStep[] { ConfirmAttendee, AfterConfirmAttendee, }; var updateName = new WaterfallStep[] { UpdateUserName, AfterUpdateUserName, }; var updateStartDate = new WaterfallStep[] { UpdateStartDateForCreate, AfterUpdateStartDateForCreate, }; var updateStartTime = new WaterfallStep[] { UpdateStartTimeForCreate, AfterUpdateStartTimeForCreate, }; var updateDuration = new WaterfallStep[] { UpdateDurationForCreate, AfterUpdateDurationForCreate, }; // Define the conversation flow using a waterfall model. AddDialog(new WaterfallDialog(Actions.CreateEvent, createEvent)); AddDialog(new WaterfallDialog(Actions.UpdateAddress, updateAddress)); AddDialog(new WaterfallDialog(Actions.ConfirmAttendee, confirmAttendee)); AddDialog(new WaterfallDialog(Actions.UpdateName, updateName)); AddDialog(new WaterfallDialog(Actions.UpdateStartDateForCreate, updateStartDate)); AddDialog(new WaterfallDialog(Actions.UpdateStartTimeForCreate, updateStartTime)); AddDialog(new WaterfallDialog(Actions.UpdateDurationForCreate, updateDuration)); // Set starting dialog for component InitialDialogId = Actions.CreateEvent; }
/// <summary> /// Initializes a new instance of the <see cref="BotServices"/> class. /// </summary> /// <param name="botConfiguration">The <see cref="BotConfiguration"/> instance for the bot.</param> public BotServices(BotConfiguration botConfiguration, List <SkillDefinition> skills) { foreach (var service in botConfiguration.Services) { switch (service.Type) { case ServiceTypes.AppInsights: { var appInsights = service as AppInsightsService; var telemetryConfig = new TelemetryConfiguration(appInsights.InstrumentationKey); TelemetryClient = new TelemetryClient(telemetryConfig); break; } case ServiceTypes.Dispatch: { var dispatch = service as DispatchService; var dispatchApp = new LuisApplication(dispatch.AppId, dispatch.SubscriptionKey, dispatch.GetEndpoint()); DispatchRecognizer = new TelemetryLuisRecognizer(dispatchApp); break; } case ServiceTypes.Luis: { var luis = service as LuisService; var luisApp = new LuisApplication(luis.AppId, luis.SubscriptionKey, luis.GetEndpoint()); LuisServices.Add(service.Id, new TelemetryLuisRecognizer(luisApp)); break; } case ServiceTypes.QnA: { var qna = service as QnAMakerService; var qnaEndpoint = new QnAMakerEndpoint() { KnowledgeBaseId = qna.KbId, EndpointKey = qna.EndpointKey, Host = qna.Hostname, }; var qnaMaker = new TelemetryQnAMaker(qnaEndpoint); QnAServices.Add(qna.Id, qnaMaker); break; } case ServiceTypes.Generic: { if (service.Name == "Authentication") { var authentication = service as GenericService; AuthenticationConnections = authentication.Configuration; } break; } case ServiceTypes.CosmosDB: { var cosmos = service as CosmosDbService; CosmosDbOptions = new CosmosDbStorageOptions { AuthKey = cosmos.Key, CollectionId = cosmos.Collection, DatabaseId = cosmos.Database, CosmosDBEndpoint = new Uri(cosmos.Endpoint), }; break; } } } foreach (var skill in skills) { var skillConfig = new SkillConfiguration() { CosmosDbOptions = CosmosDbOptions, TelemetryClient = TelemetryClient, LuisServices = LuisServices.Where(l => skill.LuisServiceIds.Contains(l.Key) == true).ToDictionary(l => l.Key, l => l.Value as IRecognizer), }; if (skill.SupportedProviders != null) { foreach (var provider in skill.SupportedProviders) { var matches = AuthenticationConnections.Where(x => x.Value == provider); foreach (var match in matches) { skillConfig.AuthenticationConnections.Add(match.Key, match.Value); } } } foreach (var set in skill.Configuration) { skillConfig.Properties.Add(set.Key, set.Value); } SkillDefinitions.Add(skill); SkillConfigurations.Add(skill.Id, skillConfig); } }
public void ConfigureServices(IServiceCollection services) { // Load the connected services from .bot file. var botFilePath = Configuration.GetSection("botFilePath")?.Value; var botFileSecret = Configuration.GetSection("botFileSecret")?.Value; var botConfig = BotConfiguration.Load(botFilePath ?? @".\ToDoSkill.bot", botFileSecret); services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot config file could not be loaded.")); // Use Application Insights services.AddBotApplicationInsights(botConfig); // Initializes your bot service clients and adds a singleton that your Bot can access through dependency injection. var parameters = Configuration.GetSection("parameters")?.Get <string[]>(); var configuration = Configuration.GetSection("configuration")?.GetChildren()?.ToDictionary(x => x.Key, y => y.Value as object); var supportedProviders = Configuration.GetSection("supportedProviders")?.Get <string[]>(); var languageModels = Configuration.GetSection("languageModels").Get <Dictionary <string, Dictionary <string, string> > >(); ISkillConfiguration connectedServices = new SkillConfiguration(botConfig, languageModels, supportedProviders, parameters, configuration); services.AddSingleton <ISkillConfiguration>(sp => connectedServices); var defaultLocale = Configuration.GetSection("defaultLocale").Get <string>(); // Initialize Bot State var cosmosDbService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.CosmosDB) ?? throw new Exception("Please configure your CosmosDb service in your .bot file."); var cosmosDb = cosmosDbService as CosmosDbService; var cosmosOptions = new CosmosDbStorageOptions() { CosmosDBEndpoint = new Uri(cosmosDb.Endpoint), AuthKey = cosmosDb.Key, CollectionId = cosmosDb.Collection, DatabaseId = cosmosDb.Database, }; var dataStore = new CosmosDbStorage(cosmosOptions); var userState = new UserState(dataStore); var conversationState = new ConversationState(dataStore); services.AddSingleton(dataStore); services.AddSingleton(userState); services.AddSingleton(conversationState); services.AddSingleton(new BotStateSet(userState, conversationState)); var serviceProvider = configuration.ContainsKey("TaskServiceProvider") ? configuration["TaskServiceProvider"].ToString() : string.Empty; if (serviceProvider.Equals("Outlook", StringComparison.InvariantCultureIgnoreCase)) { services.AddTransient <ITaskService, OutlookService>(); } else { services.AddTransient <ITaskService, OneNoteService>(); } services.AddTransient <IMailService, MailService>(); // Add the bot with options services.AddBot <ToDoSkill>(options => { // Load the connected services from .bot file. var environment = _isProduction ? "production" : "development"; var service = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.Endpoint && s.Name == environment); if (!(service is EndpointService endpointService)) { throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{environment}'."); } options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword); // Telemetry Middleware (logs activity messages in Application Insights) var appInsightsService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.AppInsights) ?? throw new Exception("Please configure your AppInsights connection in your .bot file."); var instrumentationKey = (appInsightsService as AppInsightsService).InstrumentationKey; var sp = services.BuildServiceProvider(); var telemetryClient = sp.GetService <IBotTelemetryClient>(); var appInsightsLogger = new TelemetryLoggerMiddleware(telemetryClient, logUserName: true, logOriginalMessage: true); options.Middleware.Add(appInsightsLogger); // Catches any errors that occur during a conversation turn and logs them to AppInsights. options.OnTurnError = async(context, exception) => { CultureInfo.CurrentUICulture = new CultureInfo(context.Activity.Locale); await context.SendActivityAsync(context.Activity.CreateReply(ToDoSharedResponses.ToDoErrorMessage)); await context.SendActivityAsync(new Activity(type: ActivityTypes.Trace, text: $"To Do Skill Error: {exception.Message} | {exception.StackTrace}")); telemetryClient.TrackException(exception); }; // Transcript Middleware (saves conversation history in a standard format) var storageService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.BlobStorage) ?? throw new Exception("Please configure your Azure Storage service in your .bot file."); var blobStorage = storageService as BlobStorageService; var transcriptStore = new AzureBlobTranscriptStore(blobStorage.ConnectionString, blobStorage.Container); var transcriptMiddleware = new TranscriptLoggerMiddleware(transcriptStore); options.Middleware.Add(transcriptMiddleware); // Typing Middleware (automatically shows typing when the bot is responding/working) var typingMiddleware = new ShowTypingMiddleware(); options.Middleware.Add(typingMiddleware); options.Middleware.Add(new SetLocaleMiddleware(defaultLocale ?? "en-us")); options.Middleware.Add(new AutoSaveStateMiddleware(userState, conversationState)); }); }
/// <summary> /// Initializes a new instance of the <see cref="StatusIntent"/> class. /// </summary> /// <param name="tflClient">The TfL API client to use.</param> /// <param name="config">The skill configuration to use.</param> public StatusIntent(ITflClient tflClient, SkillConfiguration config) { Config = config; TflClient = tflClient; }