Esempio n. 1
0
        public FakeSkill(SkillConfigurationBase services, EndpointService endpointService, ConversationState conversationState, UserState userState, ProactiveState proactiveState, IBotTelemetryClient telemetryClient, IBackgroundTaskQueue backgroundTaskQueue, bool skillMode = false, ResponseManager responseManager = null, ServiceManager serviceManager = null)
        {
            _skillMode           = skillMode;
            _services            = services ?? throw new ArgumentNullException(nameof(services));
            _userState           = userState ?? throw new ArgumentNullException(nameof(userState));
            _conversationState   = conversationState ?? throw new ArgumentNullException(nameof(conversationState));
            _proactiveState      = proactiveState;
            _endpointService     = endpointService;
            _backgroundTaskQueue = backgroundTaskQueue;
            _telemetryClient     = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));
            _serviceManager      = serviceManager ?? new ServiceManager();

            if (responseManager == null)
            {
                var locales = new string[] { "en-us", "de-de", "es-es", "fr-fr", "it-it", "zh-cn" };
                responseManager = new ResponseManager(
                    locales,
                    new SampleAuthResponses(),
                    new MainResponses(),
                    new SharedResponses(),
                    new SampleResponses());
            }

            _responseManager = responseManager;
            _dialogs         = new DialogSet(_conversationState.CreateProperty <DialogState>(nameof(DialogState)));
            _dialogs.Add(new MainDialog(_services, _responseManager, _conversationState, _userState, _telemetryClient, _serviceManager, _skillMode));
        }
Esempio n. 2
0
        public DefaultAdapter(
            BotSettings settings,
            ICredentialProvider credentialProvider,
            IChannelProvider channelProvider,
            LocaleTemplateManager templateFile,
            ConversationState conversationState,
            TelemetryInitializerMiddleware telemetryMiddleware,
            IBotTelemetryClient telemetryClient,
            ProactiveState proactiveState)
            : base(credentialProvider, channelProvider)
        {
            OnTurnError = async(turnContext, exception) =>
            {
                await turnContext.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : $"Exception Message: {exception.Message}, Stack: {exception.StackTrace}"));

                await turnContext.SendActivityAsync(templateFile.GenerateActivityForLocale("ErrorMessage", settings.DefaultLocale));

                telemetryClient.TrackException(exception);
            };

            Use(telemetryMiddleware);

            // Uncomment the following line for local development without Azure Storage
            // Use(new TranscriptLoggerMiddleware(new MemoryTranscriptStore()));
            Use(new TranscriptLoggerMiddleware(new AzureBlobTranscriptStore(settings.BlobStorage.ConnectionString, settings.BlobStorage.Container)));
            Use(new ShowTypingMiddleware());
            Use(new SetLocaleMiddleware(settings.DefaultLocale ?? "en-us"));
            Use(new EventDebuggerMiddleware());
            Use(new SetSpeakMiddleware());

            // SAMPLE: Proactive notifications
            Use(new ProactiveStateMiddleware(proactiveState));
        }
Esempio n. 3
0
        public MainDialog(
            BotSettings settings,
            BotServices services,
            ResponseManager responseManager,
            ConversationState conversationState,
            ProactiveState proactiveState,
            CreateEventDialog createEventDialog,
            ChangeEventStatusDialog changeEventStatusDialog,
            TimeRemainingDialog timeRemainingDialog,
            SummaryDialog summaryDialog,
            UpdateEventDialog updateEventDialog,
            ConnectToMeetingDialog connectToMeetingDialog,
            UpcomingEventDialog upcomingEventDialog,
            IBotTelemetryClient telemetryClient)
            : base(nameof(MainDialog), telemetryClient)
        {
            _settings          = settings;
            _services          = services;
            _responseManager   = responseManager;
            _conversationState = conversationState;
            TelemetryClient    = telemetryClient;

            // Initialize state accessor
            _stateAccessor = _conversationState.CreateProperty <CalendarSkillState>(nameof(CalendarSkillState));

            // Register dialogs
            AddDialog(createEventDialog ?? throw new ArgumentNullException(nameof(createEventDialog)));
            AddDialog(changeEventStatusDialog ?? throw new ArgumentNullException(nameof(changeEventStatusDialog)));
            AddDialog(timeRemainingDialog ?? throw new ArgumentNullException(nameof(timeRemainingDialog)));
            AddDialog(summaryDialog ?? throw new ArgumentNullException(nameof(summaryDialog)));
            AddDialog(updateEventDialog ?? throw new ArgumentNullException(nameof(updateEventDialog)));
            AddDialog(connectToMeetingDialog ?? throw new ArgumentNullException(nameof(connectToMeetingDialog)));
            AddDialog(upcomingEventDialog ?? throw new ArgumentNullException(nameof(upcomingEventDialog)));
        }
Esempio n. 4
0
        public UpcomingEventDialog(
            BotSettings settings,
            BotServices services,
            ConversationState conversationState,
            LocaleTemplateEngineManager localeTemplateEngineManager,
            ProactiveState proactiveState,
            IServiceManager serviceManager,
            IBotTelemetryClient telemetryClient,
            IBackgroundTaskQueue backgroundTaskQueue,
            MicrosoftAppCredentials appCredentials)
            : base(nameof(UpcomingEventDialog), settings, services, conversationState, localeTemplateEngineManager, serviceManager, telemetryClient, appCredentials)
        {
            _backgroundTaskQueue    = backgroundTaskQueue;
            _proactiveState         = proactiveState;
            _proactiveStateAccessor = _proactiveState.CreateProperty <ProactiveModel>(nameof(ProactiveModel));

            var upcomingMeeting = new WaterfallStep[]
            {
                GetAuthToken,
                AfterGetAuthToken,
                QueueUpcomingEventWorker
            };

            // Define the conversation flow using a waterfall model.
            AddDialog(new WaterfallDialog(Actions.ShowUpcomingMeeting, upcomingMeeting));

            // Set starting dialog for component
            InitialDialogId = Actions.ShowUpcomingMeeting;
        }
Esempio n. 5
0
        public MainDialog(
            SkillConfigurationBase services,
            EndpointService endpointService,
            ResponseManager responseManager,
            ConversationState conversationState,
            UserState userState,
            ProactiveState proactiveState,
            IBotTelemetryClient telemetryClient,
            IBackgroundTaskQueue backgroundTaskQueue,
            IServiceManager serviceManager,
            bool skillMode)
            : base(nameof(MainDialog), telemetryClient)
        {
            _skillMode           = skillMode;
            _services            = services;
            _endpointService     = endpointService;
            _responseManager     = responseManager;
            _userState           = userState;
            _conversationState   = conversationState;
            _proactiveState      = proactiveState;
            TelemetryClient      = telemetryClient;
            _backgroundTaskQueue = backgroundTaskQueue;
            _serviceManager      = serviceManager;

            // Initialize state accessor
            _stateAccessor          = _conversationState.CreateProperty <CalendarSkillState>(nameof(CalendarSkillState));
            _proactiveStateAccessor = _proactiveState.CreateProperty <ProactiveModel>(nameof(ProactiveModel));

            // Register dialogs
            RegisterDialogs();
        }
Esempio n. 6
0
        public RestaurantBooking(
            SkillConfigurationBase services,
            EndpointService endpointService,
            ConversationState conversationState,
            UserState userState,
            ProactiveState proactiveState,
            IBotTelemetryClient telemetryClient,
            IBackgroundTaskQueue backgroundTaskQueue,
            bool skillMode = false,
            ResponseManager responseManager  = null,
            IServiceManager serviceManager   = null,
            IHttpContextAccessor httpContext = null)
        {
            _skillMode         = skillMode;
            _services          = services ?? throw new ArgumentNullException(nameof(services));
            _userState         = userState ?? throw new ArgumentNullException(nameof(userState));
            _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState));
            _telemetryClient   = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));
            _serviceManager    = serviceManager ?? new ServiceManager();
            _httpContext       = httpContext;

            if (responseManager == null)
            {
                responseManager = new ResponseManager(
                    _services.LocaleConfigurations.Keys.ToArray(),
                    new RestaurantBookingSharedResponses(),
                    new RestaurantBookingMainResponses());
            }

            _responseManager = responseManager;
            _dialogs         = new DialogSet(_conversationState.CreateProperty <DialogState>(nameof(DialogState)));
            _dialogs.Add(new MainDialog(_services, _responseManager, _conversationState, _userState, _telemetryClient, _serviceManager, _httpContext, _skillMode));
        }
Esempio n. 7
0
        public DefaultAdapter(
            BotSettings settings,
            ICredentialProvider credentialProvider,
            IBotTelemetryClient telemetryClient,
            ProactiveState proactiveState)
            : base(credentialProvider)
        {
            OnTurnError = async(turnContext, exception) =>
            {
                await turnContext.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : $"{exception.Message}"));

                await turnContext.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : $"{exception.StackTrace}"));

                await turnContext.SendActivityAsync(MainStrings.ERROR);

                telemetryClient.TrackException(exception);
            };

            // Uncomment and fill in the following line to use ContentModerator
            // Use(new ContentModeratorMiddleware(settings.ContentModerator.Key, "<yourCMRegion>"));
            Use(new TranscriptLoggerMiddleware(new AzureBlobTranscriptStore(settings.BlobStorage.ConnectionString, settings.BlobStorage.Container)));
            Use(new TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: true));
            Use(new ShowTypingMiddleware());
            Use(new SetLocaleMiddleware(settings.DefaultLocale ?? "en-us"));
            Use(new EventDebuggerMiddleware());
            Use(new ProactiveStateMiddleware(proactiveState));
        }
        public MainDialog(
            IServiceProvider serviceProvider,
            IBotTelemetryClient telemetryClient,
            MicrosoftAppCredentials appCredentials,
            ProactiveState proactiveState)
            : base(nameof(MainDialog), telemetryClient)
        {
            _services       = serviceProvider.GetService <BotServices>();
            _settings       = serviceProvider.GetService <BotSettings>();
            _templateEngine = serviceProvider.GetService <LocaleTemplateEngineManager>();
            TelemetryClient = telemetryClient;

            // Create user state properties
            var userState = serviceProvider.GetService <UserState>();

            _userProfileState = userState.CreateProperty <UserProfileState>(nameof(UserProfileState));
            _skillContext     = userState.CreateProperty <SkillContext>(nameof(SkillContext));

            // Create conversation state properties
            var conversationState = serviceProvider.GetService <ConversationState>();

            _previousResponseAccessor = conversationState.CreateProperty <List <Activity> >(StateProperties.PreviousBotResponse);

            // SAMPLE: Create proactive state properties
            _appCredentials         = appCredentials;
            _proactiveStateAccessor = proactiveState.CreateProperty <ProactiveModel>(nameof(ProactiveModel));

            // Register dialogs
            _onboardingDialog  = serviceProvider.GetService <OnboardingDialog>();
            _switchSkillDialog = serviceProvider.GetService <SwitchSkillDialog>();
            AddDialog(_onboardingDialog);
            AddDialog(_switchSkillDialog);

            // Register a QnAMakerDialog for each registered knowledgebase and ensure localised responses are provided.
            var localizedServices = _services.GetCognitiveModels();

            foreach (var knowledgebase in localizedServices.QnAConfiguration)
            {
                var qnaDialog = new QnAMakerDialog(
                    knowledgeBaseId: knowledgebase.Value.KnowledgeBaseId,
                    endpointKey: knowledgebase.Value.EndpointKey,
                    hostName: knowledgebase.Value.Host,
                    noAnswer: _templateEngine.GenerateActivityForLocale("UnsupportedMessage"),
                    activeLearningCardTitle: _templateEngine.GenerateActivityForLocale("QnaMakerAdaptiveLearningCardTitle").Text,
                    cardNoMatchText: _templateEngine.GenerateActivityForLocale("QnaMakerNoMatchText").Text)
                {
                    Id = knowledgebase.Key
                };
                AddDialog(qnaDialog);
            }

            // Register skill dialogs
            var skillDialogs = serviceProvider.GetServices <SkillDialog>();

            foreach (var dialog in skillDialogs)
            {
                AddDialog(dialog);
            }
        }
 public DefaultActivityHandler(IServiceProvider serviceProvider, T dialog)
 {
     _dialog = dialog;
     _dialog.TelemetryClient = serviceProvider.GetService <IBotTelemetryClient>();
     _conversationState      = serviceProvider.GetService <ConversationState>();
     _userState              = serviceProvider.GetService <UserState>();
     _proactiveState         = serviceProvider.GetService <ProactiveState>();
     _dialogStateAccessor    = _conversationState.CreateProperty <DialogState>(nameof(DialogState));
     _proactiveStateAccessor = _proactiveState.CreateProperty <ProactiveModel>(nameof(ProactiveModel));
     _appCredentials         = serviceProvider.GetService <MicrosoftAppCredentials>();
     _templateManager        = serviceProvider.GetService <LocaleTemplateManager>();
 }
Esempio n. 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="VirtualAssistant"/> class.
        /// </summary>
        /// <param name="botServices">Bot services.</param>
        /// <param name="conversationState">Bot conversation state.</param>
        /// <param name="userState">Bot user state.</param>
        /// <param name="proactiveState">Proactive state.</param>
        /// <param name="endpointService">Bot endpoint service.</param>
        /// <param name="telemetryClient">Bot telemetry client.</param>
        /// <param name="backgroundTaskQueue">Background task queue.</param>
        public VirtualAssistant(BotServices botServices, ConversationState conversationState, UserState userState, ProactiveState proactiveState, EndpointService endpointService, IBotTelemetryClient telemetryClient, IBackgroundTaskQueue backgroundTaskQueue)
        {
            _conversationState   = conversationState ?? throw new ArgumentNullException(nameof(conversationState));
            _userState           = userState ?? throw new ArgumentNullException(nameof(userState));
            _proactiveState      = proactiveState ?? throw new ArgumentNullException(nameof(proactiveState));
            _services            = botServices ?? throw new ArgumentNullException(nameof(botServices));
            _endpointService     = endpointService ?? throw new ArgumentNullException(nameof(endpointService));
            _telemetryClient     = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));
            _backgroundTaskQueue = backgroundTaskQueue;

            _dialogs = new DialogSet(_conversationState.CreateProperty <DialogState>(nameof(VirtualAssistant)));
            _dialogs.Add(new MainDialog(_services, _conversationState, _userState, _proactiveState, _endpointService, _telemetryClient, _backgroundTaskQueue));
        }
Esempio n. 11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="VirtualAssistant"/> class.
        /// </summary>
        /// <param name="botServices">Bot services.</param>
        /// <param name="conversationState">Bot conversation state.</param>
        /// <param name="userState">Bot user state.</param>
        /// <param name="proactiveState">Proactive state.</param>
        /// <param name="endpointService">Bot endpoint service.</param>
        /// <param name="telemetryClient">Bot telemetry client.</param>
        /// <param name="backgroundTaskQueue">Background task queue.</param>
        /// <param name="responseManager">Response manager.</param>
        /// <param name="imageAssetLocation">Image asset location.</param>
        /// <param name="httpContext">Http context.</param>
        public VirtualAssistant(BotServices botServices, ConversationState conversationState, UserState userState, ProactiveState proactiveState, EndpointService endpointService, IBotTelemetryClient telemetryClient, IBackgroundTaskQueue backgroundTaskQueue, ResponseManager responseManager, string imageAssetLocation, IHttpContextAccessor httpContext = null)
        {
            _conversationState   = conversationState ?? throw new ArgumentNullException(nameof(conversationState));
            _userState           = userState ?? throw new ArgumentNullException(nameof(userState));
            _proactiveState      = proactiveState ?? throw new ArgumentNullException(nameof(proactiveState));
            _services            = botServices ?? throw new ArgumentNullException(nameof(botServices));
            _endpointService     = endpointService ?? throw new ArgumentNullException(nameof(endpointService));
            _telemetryClient     = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));
            _backgroundTaskQueue = backgroundTaskQueue;
            _responseManager     = responseManager;
            _imageAssetLocation  = imageAssetLocation;
            _httpContext         = httpContext ?? throw new ArgumentNullException(nameof(httpContext));

            _dialogs = new DialogSet(_conversationState.CreateProperty <DialogState>(nameof(VirtualAssistant)));
            _dialogs.Add(new MainDialog(_services, _conversationState, _userState, _proactiveState, _endpointService, _telemetryClient, _backgroundTaskQueue, _responseManager, _imageAssetLocation, _httpContext));
        }
Esempio n. 12
0
 public CreateSubscriptionTeamsImplementation(
     IServiceProvider serviceProvider)
 {
     _conversationState            = serviceProvider.GetService <ConversationState>();
     _settings                     = serviceProvider.GetService <BotSettings>();
     _services                     = serviceProvider.GetService <BotServices>();
     _stateAccessor                = _conversationState.CreateProperty <SkillState>(nameof(SkillState));
     _serviceManager               = serviceProvider.GetService <IServiceManager>();
     _connectorClient              = serviceProvider.GetService <IConnectorClient>();
     _teamsTicketUpdateActivity    = serviceProvider.GetService <ITeamsActivity <AdaptiveCard> >();
     _proactiveState               = serviceProvider.GetService <ProactiveState>();
     _proactiveStateAccessor       = _proactiveState.CreateProperty <ProactiveModel>(nameof(ProactiveModel));
     _activityReferenceMapAccessor = _conversationState.CreateProperty <ActivityReferenceMap>(nameof(ActivityReferenceMap));
     _proactiveStateActivityReferenceMapAccessor     = _proactiveState.CreateProperty <ActivityReferenceMap>(nameof(ActivityReferenceMap));
     _proactiveStateConversationReferenceMapAccessor = _proactiveState.CreateProperty <ConversationReferenceMap>(nameof(ConversationReferenceMap));
     _subscriptionManager = serviceProvider.GetService <SubscriptionManager>();
 }
 public DefaultActivityHandler(IServiceProvider serviceProvider, T dialog)
 {
     _dialog = dialog;
     _dialog.TelemetryClient = serviceProvider.GetService <IBotTelemetryClient>();
     _conversationState      = serviceProvider.GetService <ConversationState>();
     _userState                    = serviceProvider.GetService <UserState>();
     _proactiveState               = serviceProvider.GetService <ProactiveState>();
     _dialogStateAccessor          = _conversationState.CreateProperty <DialogState>(nameof(DialogState));
     _proactiveStateAccessor       = _proactiveState.CreateProperty <ProactiveModel>(nameof(ProactiveModel));
     _activityReferenceMapAccessor = _proactiveState.CreateProperty <ActivityReferenceMap>(nameof(ActivityReferenceMap));
     _proactiveStateConversationReferenceMapAccessor = _proactiveState.CreateProperty <ConversationReferenceMap>(nameof(ConversationReferenceMap));
     _botSettings               = serviceProvider.GetService <BotSettings>();
     _templateManager           = serviceProvider.GetService <LocaleTemplateManager>();
     _serviceProvider           = serviceProvider;
     _teamsTicketUpdateActivity = serviceProvider.GetService <ITeamsActivity <AdaptiveCard> >();
     _subscriptionManager       = serviceProvider.GetService <SubscriptionManager>();
 }
Esempio n. 14
0
        public SkillDialog(SkillDefinition skillDefinition, SkillConfigurationBase skillConfiguration, ProactiveState proactiveState, EndpointService endpointService, IBotTelemetryClient telemetryClient, IBackgroundTaskQueue backgroundTaskQueue, bool useCachedTokens = true)
            : base(skillDefinition.Id)
        {
            _skillDefinition     = skillDefinition;
            _skillConfiguration  = skillConfiguration;
            _proactiveState      = proactiveState;
            _endpointService     = endpointService;
            _telemetryClient     = telemetryClient;
            _backgroundTaskQueue = backgroundTaskQueue;
            _useCachedTokens     = useCachedTokens;

            var supportedLanguages = skillConfiguration.LocaleConfigurations.Keys.ToArray();

            _responseManager = new ResponseManager(supportedLanguages, new SkillResponses());

            AddDialog(new MultiProviderAuthDialog(skillConfiguration));
        }
Esempio n. 15
0
        public CalendarSkill(
            SkillConfigurationBase services,
            EndpointService endpointService,
            ConversationState conversationState,
            UserState userState,
            ProactiveState proactiveState,
            IBotTelemetryClient telemetryClient,
            IBackgroundTaskQueue backgroundTaskQueue,
            bool skillMode = false,
            ResponseManager responseManager = null,
            IServiceManager serviceManager  = null)
        {
            _skillMode           = skillMode;
            _services            = services ?? throw new ArgumentNullException(nameof(services));
            _endpointService     = endpointService ?? throw new ArgumentNullException(nameof(endpointService));
            _userState           = userState ?? throw new ArgumentNullException(nameof(userState));
            _conversationState   = conversationState ?? throw new ArgumentNullException(nameof(conversationState));
            _proactiveState      = proactiveState ?? throw new ArgumentNullException(nameof(proactiveState));
            _serviceManager      = serviceManager ?? new ServiceManager(_services);
            _telemetryClient     = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));
            _backgroundTaskQueue = backgroundTaskQueue ?? throw new ArgumentNullException(nameof(backgroundTaskQueue));

            if (responseManager == null)
            {
                var supportedLanguages = services.LocaleConfigurations.Keys.ToArray();
                responseManager = new ResponseManager(
                    new IResponseIdCollection[]
                {
                    new FindContactResponses(),
                    new ChangeEventStatusResponses(),
                    new CreateEventResponses(),
                    new JoinEventResponses(),
                    new CalendarMainResponses(),
                    new CalendarSharedResponses(),
                    new SummaryResponses(),
                    new TimeRemainingResponses(),
                    new UpdateEventResponses(),
                    new UpcomingEventResponses()
                }, supportedLanguages);
            }

            _responseManager = responseManager;
            _dialogs         = new DialogSet(_conversationState.CreateProperty <DialogState>(nameof(DialogState)));
            _dialogs.Add(new MainDialog(_services, _endpointService, _responseManager, _conversationState, _userState, _proactiveState, _telemetryClient, _backgroundTaskQueue, _serviceManager, _skillMode));
        }
Esempio n. 16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AutomotiveSkill"/> class.
        /// </summary>
        /// <param name="services">Skill Configuration information.</param>
        /// <param name="endpointService">Endpoint service for the bot.</param>
        /// <param name="conversationState">Conversation State.</param>
        /// <param name="userState">User State.</param>
        /// <param name="proactiveState">Proative state.</param>
        /// <param name="telemetryClient">Telemetry Client.</param>
        /// <param name="backgroundTaskQueue">Background task queue.</param>
        /// <param name="serviceManager">Service Manager.</param>
        /// <param name="skillMode">Indicates whether the skill is running in skill or local mode.</param>
        /// <param name="responseManager">The responses for the bot.</param>
        /// <param name="httpContext">HttpContext accessor used to create relative URIs for images when in local mode.</param>
        public AutomotiveSkill(
            SkillConfigurationBase services,
            EndpointService endpointService,
            ConversationState conversationState,
            UserState userState,
            ProactiveState proactiveState,
            IBotTelemetryClient telemetryClient,
            IBackgroundTaskQueue backgroundTaskQueue,
            bool skillMode = false,
            ResponseManager responseManager  = null,
            IServiceManager serviceManager   = null,
            IHttpContextAccessor httpContext = null)
        {
            _skillMode       = skillMode;
            _services        = services ?? throw new ArgumentNullException(nameof(services));
            _endpointService = endpointService ?? throw new ArgumentNullException(nameof(endpointService));
            _userState       = userState ?? throw new ArgumentNullException(nameof(userState));

            // If we are running in local-mode we need the HttpContext to create image file paths
            if (!skillMode)
            {
                _httpContext = httpContext ?? throw new ArgumentNullException(nameof(httpContext));
            }

            _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState));
            _serviceManager    = serviceManager ?? new ServiceManager();
            _telemetryClient   = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));

            if (responseManager == null)
            {
                var supportedLanguages = services.LocaleConfigurations.Keys.ToArray();
                responseManager = new ResponseManager(
                    new IResponseIdCollection[]
                {
                    new AutomotiveSkillMainResponses(),
                    new AutomotiveSkillSharedResponses(),
                    new VehicleSettingsResponses(),
                }, supportedLanguages);
            }

            _responseManager = responseManager;
            _dialogs         = new DialogSet(_conversationState.CreateProperty <DialogState>(nameof(DialogState)));
            _dialogs.Add(new MainDialog(_services, _responseManager, _conversationState, _userState, _serviceManager, _httpContext, _telemetryClient, _skillMode));
        }
Esempio n. 17
0
        public MainDialog(BotServices services, ConversationState conversationState, UserState userState, ProactiveState proactiveState, EndpointService endpointService, IBotTelemetryClient telemetryClient, IBackgroundTaskQueue backgroundTaskQueue)
            : base(nameof(MainDialog), telemetryClient)
        {
            _services              = services ?? throw new ArgumentNullException(nameof(services));
            _conversationState     = conversationState;
            _userState             = userState;
            _proactiveState        = proactiveState;
            _endpointService       = endpointService;
            TelemetryClient        = telemetryClient;
            _backgroundTaskQueue   = backgroundTaskQueue;
            _onboardingState       = _userState.CreateProperty <OnboardingState>(nameof(OnboardingState));
            _parametersAccessor    = _userState.CreateProperty <Dictionary <string, object> >("userInfo");
            _virtualAssistantState = _conversationState.CreateProperty <VirtualAssistantState>(nameof(VirtualAssistantState));

            AddDialog(new OnboardingDialog(_services, _onboardingState, telemetryClient));
            AddDialog(new EscalateDialog(_services, telemetryClient));

            RegisterSkills(_services.SkillDefinitions);
        }
Esempio n. 18
0
        public async Task DefaultOptions()
        {
            var microsoftAppId = string.Empty;

            var storage = new MemoryStorage();
            var state   = new ProactiveState(storage);
            var proactiveStateAccessor = state.CreateProperty <ProactiveModel>(nameof(ProactiveModel));

            var conversation = TestAdapter.CreateConversation("Name");

            conversation.User.Role = "user";

            var adapter = new TestAdapter(conversation)
                          .Use(new ProactiveStateMiddleware(state));

            var response          = "Response";
            var proactiveResponse = "ProactiveResponse";
            var proactiveEvent    = new Activity(type: ActivityTypes.Event, value: "user1", text: proactiveResponse);

            await new TestFlow(adapter, async(context, cancellationToken) =>
            {
                if (context.Activity.Type == ActivityTypes.Event)
                {
                    var proactiveModel = await proactiveStateAccessor.GetAsync(context, () => new ProactiveModel());

                    var hashedUserId = MD5Util.ComputeHash(context.Activity.Value.ToString());

                    var conversationReference = proactiveModel[hashedUserId].Conversation;

                    await context.Adapter.ContinueConversationAsync(microsoftAppId, conversationReference, ContinueConversationCallback(context, context.Activity.Text), cancellationToken);
                }
                else
                {
                    await context.SendActivityAsync(context.Activity.CreateReply(response));
                }
            })
            .Send("foo")
            .AssertReply(response)
            .Send(proactiveEvent)
            .AssertReply(proactiveResponse)
            .StartTestAsync();
        }
        public MainDialog(
            IServiceProvider serviceProvider,
            IBotTelemetryClient telemetryClient,
            MicrosoftAppCredentials appCredentials,
            ProactiveState proactiveState)
            : base(nameof(MainDialog), telemetryClient)
        {
            _services                 = serviceProvider.GetService <BotServices>();
            _settings                 = serviceProvider.GetService <BotSettings>();
            _templateEngine           = serviceProvider.GetService <LocaleTemplateEngineManager>();
            _previousResponseAccessor = serviceProvider.GetService <IStatePropertyAccessor <List <Activity> > >();
            TelemetryClient           = telemetryClient;
            _appCredentials           = appCredentials;
            _proactiveStateAccessor   = proactiveState.CreateProperty <ProactiveModel>(nameof(ProactiveModel));

            // Create user state properties
            var userState = serviceProvider.GetService <UserState>();

            _userProfileState = userState.CreateProperty <UserProfileState>(nameof(UserProfileState));
            _skillContext     = userState.CreateProperty <SkillContext>(nameof(SkillContext));

            // Create conversation state properties
            var conversationState = serviceProvider.GetService <ConversationState>();

            _previousResponseAccessor = conversationState.CreateProperty <List <Activity> >(StateProperties.PreviousBotResponse);

            // Register dialogs
            _onboardingDialog = serviceProvider.GetService <OnboardingDialog>();
            AddDialog(_onboardingDialog);

            _qnaDialog = serviceProvider.GetService <QnADialog>();
            AddDialog(_qnaDialog);

            // Register skill dialogs
            var skillDialogs = serviceProvider.GetServices <SkillDialog>();

            foreach (var dialog in skillDialogs)
            {
                AddDialog(dialog);
            }
        }
Esempio n. 20
0
        public override void Initialize()
        {
            var builder = new ContainerBuilder();

            ConversationState            = new ConversationState(new MemoryStorage());
            UserState                    = new UserState(new MemoryStorage());
            ProactiveState               = new ProactiveState(new MemoryStorage());
            AutomotiveSkillStateAccessor = ConversationState.CreateProperty <AutomotiveSkillState>(nameof(AutomotiveSkillState));
            Services            = new MockSkillConfiguration();
            BackgroundTaskQueue = new BackgroundTaskQueue();
            EndpointService     = new EndpointService();

            ResponseManager = new ResponseManager(
                responseTemplates: new IResponseIdCollection[]
            {
                new AutomotiveSkillMainResponses(),
                new AutomotiveSkillSharedResponses(),
                new VehicleSettingsResponses()
            },
                locales: new string[] { "en-us", "de-de", "es-es", "fr-fr", "it-it", "zh-cn" });
            ImageAssetLocation = "https://localhost";
            this.Services.Properties.Add("ImageAssetLocation", ImageAssetLocation);

            builder.RegisterInstance(new BotStateSet(this.UserState, this.ConversationState));

            builder.RegisterInstance(new BotStateSet(UserState, ConversationState));

            Container = builder.Build();

            TelemetryClient = new NullBotTelemetryClient();

            // Mock HttpContext for image path resolution
            MockHttpContext = new DefaultHttpContext();
            MockHttpContext.Request.Scheme = "http";
            MockHttpContext.Request.Host   = new HostString("localhost", 3980);

            MockHttpContextAcessor = new HttpContextAccessor
            {
                HttpContext = MockHttpContext
            };
        }
Esempio n. 21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NewsSkill"/> class.
        /// </summary>
        /// <param name="services">Skill Configuration information.</param>
        /// <param name="endpointService">Endpoint service for the bot.</param>
        /// <param name="conversationState">Conversation State.</param>
        /// <param name="userState">User State.</param>
        /// <param name="proactiveState">Proative state.</param>
        /// <param name="telemetryClient">Telemetry Client.</param>
        /// <param name="backgroundTaskQueue">Background task queue.</param>
        /// <param name="serviceManager">Service Manager.</param>
        /// <param name="skillMode">Indicates whether the skill is running in skill or local mode.</param>
        public NewsSkill(
            SkillConfigurationBase services,
            EndpointService endpointService,
            ConversationState conversationState,
            UserState userState,
            ProactiveState proactiveState,
            IBotTelemetryClient telemetryClient,
            IBackgroundTaskQueue backgroundTaskQueue,
            bool skillMode = false)
        {
            _skillMode       = skillMode;
            _services        = services ?? throw new ArgumentNullException(nameof(services));
            _endpointService = endpointService ?? throw new ArgumentNullException(nameof(endpointService));
            _userState       = userState ?? throw new ArgumentNullException(nameof(userState));

            _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState));
            _telemetryClient   = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));

            _dialogs = new DialogSet(_conversationState.CreateProperty <DialogState>(nameof(DialogState)));
            _dialogs.Add(new MainDialog(_services, _conversationState, _userState, _telemetryClient, _skillMode));
        }
        public UpcomingEventDialog(
            IServiceProvider serviceProvider)
            : base(nameof(UpcomingEventDialog), serviceProvider)
        {
            _backgroundTaskQueue    = serviceProvider.GetService <BackgroundTaskQueue>();
            _proactiveState         = serviceProvider.GetService <ProactiveState>();
            _proactiveStateAccessor = _proactiveState.CreateProperty <ProactiveModel>(nameof(ProactiveModel));

            var upcomingMeeting = new WaterfallStep[]
            {
                GetAuthTokenAsync,
                AfterGetAuthTokenAsync,
                QueueUpcomingEventWorkerAsync
            };

            // Define the conversation flow using a waterfall model.
            AddDialog(new WaterfallDialog(Actions.ShowUpcomingMeeting, upcomingMeeting));

            // Set starting dialog for component
            InitialDialogId = Actions.ShowUpcomingMeeting;
        }
Esempio n. 23
0
        public EmailSkill(
            SkillConfigurationBase services,
            EndpointService endpointService,
            ConversationState conversationState,
            UserState userState,
            ProactiveState proactiveState,
            IBotTelemetryClient telemetryClient,
            IBackgroundTaskQueue backgroundTaskQueue,
            bool skillMode = false,
            ResponseManager responseManager = null,
            IServiceManager serviceManager  = null)
        {
            _skillMode         = skillMode;
            _services          = services ?? throw new ArgumentNullException(nameof(services));
            _userState         = userState ?? throw new ArgumentNullException(nameof(userState));
            _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState));
            _telemetryClient   = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));
            _serviceManager    = serviceManager ?? new ServiceManager(services);

            if (responseManager == null)
            {
                var supportedLanguages = services.LocaleConfigurations.Keys.ToArray();
                responseManager = new ResponseManager(
                    new IResponseIdCollection[]
                {
                    new FindContactResponses(),
                    new DeleteEmailResponses(),
                    new ForwardEmailResponses(),
                    new EmailMainResponses(),
                    new ReplyEmailResponses(),
                    new SendEmailResponses(),
                    new EmailSharedResponses(),
                    new ShowEmailResponses(),
                }, supportedLanguages);
            }

            _responseManager = responseManager;
            _dialogs         = new DialogSet(_conversationState.CreateProperty <DialogState>(nameof(DialogState)));
            _dialogs.Add(new MainDialog(_services, _responseManager, _conversationState, _userState, _telemetryClient, _serviceManager, _skillMode));
        }
Esempio n. 24
0
        public DefaultAdapter(
            BotSettings settings,
            ICredentialProvider credentialProvider,
            IChannelProvider channelProvider,
            AuthenticationConfiguration authConfig,
            LocaleTemplateManager templateEngine,
            ConversationState conversationState,
            TelemetryInitializerMiddleware telemetryMiddleware,
            IBotTelemetryClient telemetryClient,
            ILogger <BotFrameworkHttpAdapter> logger,
            ProactiveState proactiveState,
            SkillsConfiguration skillsConfig = null,
            SkillHttpClient skillClient      = null)
            : base(credentialProvider, authConfig, channelProvider, logger: logger)
        {
            _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState));
            _logger            = logger ?? throw new ArgumentNullException(nameof(logger));
            _templateEngine    = templateEngine ?? throw new ArgumentNullException(nameof(templateEngine));
            _telemetryClient   = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));
            _skillClient       = skillClient;
            _skillsConfig      = skillsConfig;
            _settings          = settings;

            OnTurnError = HandleTurnErrorAsync;

            Use(telemetryMiddleware);

            // Uncomment the following line for local development without Azure Storage
            // Use(new TranscriptLoggerMiddleware(new MemoryTranscriptStore()));
            Use(new TranscriptLoggerMiddleware(new BlobsTranscriptStore(settings.BlobStorage.ConnectionString, settings.BlobStorage.Container)));
            Use(new ShowTypingMiddleware());
            Use(new SetLocaleMiddleware(settings.DefaultLocale ?? "en-us"));
            Use(new EventDebuggerMiddleware());
            Use(new SetSpeakMiddleware("en-US-JennyNeural", true));
            Use(new ProactiveStateMiddleware(proactiveState));
        }
Esempio n. 25
0
File: Startup.cs Progetto: munip/AI
        public void ConfigureServices(IServiceCollection services)
        {
            // add background task queue
            services.AddSingleton <IBackgroundTaskQueue, BackgroundTaskQueue>();
            services.AddHostedService <QueuedHostedService>();

            // Load the connected services from .bot file.
            var botFilePath   = Configuration.GetSection("botFilePath")?.Value;
            var botFileSecret = Configuration.GetSection("botFileSecret")?.Value;
            var botConfig     = BotConfiguration.Load(botFilePath ?? throw new Exception("Please configure your bot file path in appsettings.json."), botFileSecret);

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

            // Initializes your bot service clients and adds a singleton that your Bot can access through dependency injection.
            var languageModels            = Configuration.GetSection("languageModels").Get <Dictionary <string, Dictionary <string, string> > >();
            var skills                    = Configuration.GetSection("skills").Get <List <SkillDefinition> >();
            List <SkillEvent> skillEvents = null;
            var skillEventsConfig         = Configuration.GetSection(SkillEventsConfigName);

            if (skillEventsConfig != null)
            {
                skillEvents = skillEventsConfig.Get <List <SkillEvent> >();
            }

            var connectedServices = new BotServices(botConfig, languageModels, skills, skillEvents);

            services.AddSingleton(sp => connectedServices);

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

            // Initialize Bot State
            var cosmosDbService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.CosmosDB) ?? throw new Exception("Please configure your CosmosDb service in your .bot file.");
            var cosmosDb        = cosmosDbService as CosmosDbService;
            var cosmosOptions   = new CosmosDbStorageOptions()
            {
                CosmosDBEndpoint = new Uri(cosmosDb.Endpoint),
                AuthKey          = cosmosDb.Key,
                CollectionId     = cosmosDb.Collection,
                DatabaseId       = cosmosDb.Database,
            };
            var dataStore         = new CosmosDbStorage(cosmosOptions);
            var userState         = new UserState(dataStore);
            var conversationState = new ConversationState(dataStore);
            var proactiveState    = new ProactiveState(dataStore);

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

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

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

            services.AddSingleton(endpointService);

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

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

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

                // Transcript Middleware (saves conversation history in a standard format)
                var storageService       = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.BlobStorage) ?? throw new Exception("Please configure your Azure Storage service in your .bot file.");
                var blobStorage          = storageService as BlobStorageService;
                var transcriptStore      = new AzureBlobTranscriptStore(blobStorage.ConnectionString, blobStorage.Container);
                var transcriptMiddleware = new TranscriptLoggerMiddleware(transcriptStore);
                options.Middleware.Add(transcriptMiddleware);

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

                //// Translator is an optional component for scenarios when an Assistant needs to work beyond native language support
                // var translatorKey = Configuration.GetValue<string>("translatorKey");
                // if (!string.IsNullOrEmpty(translatorKey))
                // {
                //     options.Middleware.Add(new TranslationMiddleware(new string[] { "en", "fr", "it", "de", "es" }, translatorKey, false));
                // }
                // else
                // {
                //     throw new InvalidOperationException("Microsoft Text Translation API key is missing. Please add your translation key to the 'translatorKey' setting.");
                // }
            });
        }
Esempio n. 26
0
        public void ConfigureServices(IServiceCollection services)
        {
            // add background task queue
            services.AddSingleton<IBackgroundTaskQueue, BackgroundTaskQueue>();
            services.AddHostedService<QueuedHostedService>();

            // Load the connected services from .bot file.
            var botFilePath = Configuration.GetSection("botFilePath")?.Value;
            var botFileSecret = Configuration.GetSection("botFileSecret")?.Value;
            var botConfig = BotConfiguration.Load(botFilePath ?? @".\PointOfInterestSkill.bot", botFileSecret);
            services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot config file could not be loaded."));

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

            // Initializes your bot service clients and adds a singleton that your Bot can access through dependency injection.
            var parameters = Configuration.GetSection("parameters")?.Get<string[]>();
            var configuration = Configuration.GetSection("configuration")?.GetChildren()?.ToDictionary(x => x.Key, y => y.Value as object);
            var languageModels = Configuration.GetSection("languageModels").Get<Dictionary<string, Dictionary<string, string>>>();
            var connectedServices = new SkillConfiguration(botConfig, languageModels, null, parameters, configuration);
            services.AddSingleton<SkillConfigurationBase>(sp => connectedServices);

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

            var responseManager = new ResponseManager(responses, supportedLanguages);

            // Register bot responses for all supported languages.
            services.AddSingleton(sp => responseManager);

            // Initialize Bot State
            var cosmosDbService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.CosmosDB) ?? throw new Exception("Please configure your CosmosDb service in your .bot file.");
            var cosmosDb = cosmosDbService as CosmosDbService;
            var cosmosOptions = new CosmosDbStorageOptions()
            {
                CosmosDBEndpoint = new Uri(cosmosDb.Endpoint),
                AuthKey = cosmosDb.Key,
                CollectionId = cosmosDb.Collection,
                DatabaseId = cosmosDb.Database,
            };
            var dataStore = new CosmosDbStorage(cosmosOptions);
            var userState = new UserState(dataStore);
            var conversationState = new ConversationState(dataStore);
            var proactiveState = new ProactiveState(dataStore);

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

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

            services.AddSingleton(endpointService);

            services.AddSingleton<IServiceManager, ServiceManager>();

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

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

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

                // Transcript Middleware (saves conversation history in a standard format)
                var storageService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.BlobStorage) ?? throw new Exception("Please configure your Azure Storage service in your .bot file.");
                var blobStorage = storageService as BlobStorageService;
                var transcriptStore = new AzureBlobTranscriptStore(blobStorage.ConnectionString, blobStorage.Container);
                var transcriptMiddleware = new TranscriptLoggerMiddleware(transcriptStore);
                options.Middleware.Add(transcriptMiddleware);

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

                options.Middleware.Add(new EventDebuggerMiddleware());
                options.Middleware.Add(new AutoSaveStateMiddleware(userState, conversationState));
            });
        }
Esempio n. 27
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_2);

            // add background task queue
            services.AddSingleton <IBackgroundTaskQueue, BackgroundTaskQueue>();
            services.AddHostedService <QueuedHostedService>();

            // Load the connected services from .bot file.
            var botFilePath   = Configuration.GetSection("botFilePath")?.Value;
            var botFileSecret = Configuration.GetSection("botFileSecret")?.Value;
            var botConfig     = BotConfiguration.Load(botFilePath ?? @".\automotiveskill.bot", botFileSecret);

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

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

            // Initializes your bot service clients and adds a singleton that your Bot can access through dependency injection.
            var parameters         = Configuration.GetSection("Parameters")?.Get <string[]>();
            var configuration      = Configuration.GetSection("Configuration")?.Get <Dictionary <string, object> >();
            var supportedProviders = Configuration.GetSection("SupportedProviders")?.Get <string[]>();
            var languageModels     = Configuration.GetSection("languageModels").Get <Dictionary <string, Dictionary <string, string> > >();
            var connectedServices  = new SkillConfiguration(botConfig, languageModels, supportedProviders, parameters, configuration);

            services.AddSingleton <SkillConfigurationBase>(sp => connectedServices);

            var supportedLanguages = languageModels.Select(l => l.Key).ToArray();
            var responseManager    = new ResponseManager(
                supportedLanguages,
                new AutomotiveSkillMainResponses(),
                new AutomotiveSkillSharedResponses(),
                new VehicleSettingsResponses());

            // Register bot responses for all supported languages.
            services.AddSingleton(sp => responseManager);

            // Initialize Bot State
            var cosmosDbService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.CosmosDB) ?? throw new Exception("Please configure your CosmosDb service in your .bot file.");
            var cosmosDb        = cosmosDbService as CosmosDbService;
            var cosmosOptions   = new CosmosDbStorageOptions()
            {
                CosmosDBEndpoint = new Uri(cosmosDb.Endpoint),
                AuthKey          = cosmosDb.Key,
                CollectionId     = cosmosDb.Collection,
                DatabaseId       = cosmosDb.Database,
            };
            var dataStore         = new CosmosDbStorage(cosmosOptions);
            var userState         = new UserState(dataStore);
            var conversationState = new ConversationState(dataStore);
            var proactiveState    = new ProactiveState(dataStore);

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

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

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

            services.AddSingleton(endpointService);

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

            // HttpContext required for path resolution
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            // Add the bot
            services.AddSingleton <IBot, AutomotiveSkill>();

            // Add the http adapter to enable MVC style bot API
            services.AddTransient <IBotFrameworkHttpAdapter>((sp) =>
            {
                var credentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);

                // Telemetry Middleware (logs activity messages in Application Insights)
                var telemetryClient         = sp.GetService <IBotTelemetryClient>();
                var botFrameworkHttpAdapter = new BotFrameworkHttpAdapter(credentialProvider)
                {
                    OnTurnError = async(context, exception) =>
                    {
                        await context.SendActivityAsync(responseManager.GetResponse(AutomotiveSkillSharedResponses.ErrorMessage));
                        await context.SendActivityAsync(new Activity(type: ActivityTypes.Trace, text: $"Skill Error: {exception.Message} | {exception.StackTrace}"));
                        telemetryClient.TrackExceptionEx(exception, context.Activity);
                    }
                };
                var appInsightsLogger = new TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: true);
                botFrameworkHttpAdapter.Use(appInsightsLogger);

                // Transcript Middleware (saves conversation history in a standard format)
                var storageService       = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.BlobStorage) ?? throw new Exception("Please configure your Azure Storage service in your .bot file.");
                var blobStorage          = storageService as BlobStorageService;
                var transcriptStore      = new AzureBlobTranscriptStore(blobStorage.ConnectionString, blobStorage.Container);
                var transcriptMiddleware = new TranscriptLoggerMiddleware(transcriptStore);
                botFrameworkHttpAdapter.Use(transcriptMiddleware);

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

                botFrameworkHttpAdapter.Use(new AutoSaveStateMiddleware(userState, conversationState));

                return(botFrameworkHttpAdapter);
            });
        }
Esempio n. 28
0
        public new void Initialize()
        {
            var builder = new ContainerBuilder();

            ConversationState   = new ConversationState(new MemoryStorage());
            DialogState         = ConversationState.CreateProperty <DialogState>(nameof(DialogState));
            UserState           = new UserState(new MemoryStorage());
            ProactiveState      = new ProactiveState(new MemoryStorage());
            TelemetryClient     = new NullBotTelemetryClient();
            BackgroundTaskQueue = new BackgroundTaskQueue();
            EndpointService     = new EndpointService();
            SkillConfigurations = new Dictionary <string, SkillConfigurationBase>();

            // Add the LUIS model fakes used by the Skill
            Services = new MockSkillConfiguration();
            Services.LocaleConfigurations.Add("en", new LocaleConfiguration()
            {
                Locale       = "en-us",
                LuisServices = new Dictionary <string, ITelemetryLuisRecognizer>
                {
                    { "general", GeneralTestUtil.CreateRecognizer() },
                    { "FakeSkill", FakeSkillTestUtil.CreateRecognizer() }
                }
            });

            Services.LocaleConfigurations.Add("es", new LocaleConfiguration()
            {
                Locale       = "es-mx",
                LuisServices = new Dictionary <string, ITelemetryLuisRecognizer>
                {
                    { "general", GeneralTestUtil.CreateRecognizer() },
                    { "FakeSkill", FakeSkillTestUtil.CreateRecognizer() }
                }
            });

            // Dummy Authentication connection for Auth testing
            Services.AuthenticationConnections = new Dictionary <string, string>
            {
                { "DummyAuth", "DummyAuthConnection" }
            };

            builder.RegisterInstance(new BotStateSet(UserState, ConversationState));
            Container = builder.Build();

            Dialogs = new DialogSet(DialogState);

            var locales = new string[] { "en-us", "de-de", "es-es", "fr-fr", "it-it", "zh-cn" };

            ResponseManager = new ResponseManager(
                locales,
                new SampleAuthResponses(),
                new MainResponses(),
                new SharedResponses(),
                new SampleResponses());

            // Manually mange the conversation metadata when we need finer grained control
            ConversationReference = new ConversationReference
            {
                ChannelId  = "test",
                ServiceUrl = "https://test.com",
            };

            ConversationReference.User         = new ChannelAccount("user1", "User1");
            ConversationReference.Bot          = new ChannelAccount("bot", "Bot");
            ConversationReference.Conversation = new ConversationAccount(false, "convo1", "Conversation1");
        }
Esempio n. 29
0
 public ProactiveStateMiddleware(ProactiveState proactiveState)
 {
     _proactiveState         = proactiveState;
     _proactiveStateAccessor = _proactiveState.CreateProperty <ProactiveModel>(nameof(ProactiveModel));
 }
Esempio n. 30
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_2);

            // add background task queue
            services.AddSingleton <IBackgroundTaskQueue, BackgroundTaskQueue>();
            services.AddHostedService <QueuedHostedService>();

            // Load the connected services from .bot file.
            var botFilePath   = Configuration.GetSection("botFilePath")?.Value;
            var botFileSecret = Configuration.GetSection("botFileSecret")?.Value;
            var botConfig     = BotConfiguration.Load(botFilePath ?? throw new Exception("Please configure your bot file path in appsettings.json."), botFileSecret);

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

            // Initializes your bot service clients and adds a singleton that your Bot can access through dependency injection.
            var languageModels            = Configuration.GetSection("languageModels").Get <Dictionary <string, Dictionary <string, string> > >();
            var skills                    = Configuration.GetSection("skills").Get <List <SkillDefinition> >();
            List <SkillEvent> skillEvents = null;
            var skillEventsConfig         = Configuration.GetSection(SkillEventsConfigName);

            if (skillEventsConfig != null)
            {
                skillEvents = skillEventsConfig.Get <List <SkillEvent> >();
            }

            var connectedServices = new BotServices(botConfig, languageModels, skills, skillEvents);

            services.AddSingleton(sp => connectedServices);

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

            // Initialize Bot State
            var cosmosDbService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.CosmosDB) ?? throw new Exception("Please configure your CosmosDb service in your .bot file.");
            var cosmosDb        = cosmosDbService as CosmosDbService;
            var cosmosOptions   = new CosmosDbStorageOptions()
            {
                CosmosDBEndpoint = new Uri(cosmosDb.Endpoint),
                AuthKey          = cosmosDb.Key,
                CollectionId     = cosmosDb.Collection,
                DatabaseId       = cosmosDb.Database,
            };
            var dataStore         = new CosmosDbStorage(cosmosOptions);
            var userState         = new UserState(dataStore);
            var conversationState = new ConversationState(dataStore);
            var proactiveState    = new ProactiveState(dataStore);

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

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

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

            services.AddSingleton(endpointService);

            services.AddSingleton <IBot, VirtualAssistant>();

            // Add the http adapter to enable MVC style bot API
            services.AddSingleton <IBotFrameworkHttpAdapter>((sp) =>
            {
                var credentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);

                var telemetryClient         = sp.GetService <IBotTelemetryClient>();
                var botFrameworkHttpAdapter = new BotFrameworkHttpAdapter(credentialProvider)
                {
                    OnTurnError = async(context, exception) =>
                    {
                        CultureInfo.CurrentUICulture = new CultureInfo(context.Activity.Locale);
                        var responseBuilder          = new MainResponses();
                        await responseBuilder.ReplyWith(context, MainResponses.ResponseIds.Error);
                        await context.SendActivityAsync(new Activity(type: ActivityTypes.Trace, text: $"Virtual Assistant Error: {exception.Message} | {exception.StackTrace}"));
                        telemetryClient.TrackExceptionEx(exception, context.Activity);
                    }
                };

                // Telemetry Middleware (logs activity messages in Application Insights)
                var appInsightsLogger = new TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: true);
                botFrameworkHttpAdapter.Use(appInsightsLogger);

                // Transcript Middleware (saves conversation history in a standard format)
                var storageService       = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.BlobStorage) ?? throw new Exception("Please configure your Azure Storage service in your .bot file.");
                var blobStorage          = storageService as BlobStorageService;
                var transcriptStore      = new AzureBlobTranscriptStore(blobStorage.ConnectionString, blobStorage.Container);
                var transcriptMiddleware = new TranscriptLoggerMiddleware(transcriptStore);
                botFrameworkHttpAdapter.Use(transcriptMiddleware);

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

                return(botFrameworkHttpAdapter);
            });
        }