Esempio n. 1
0
        public CalendarSkillWebSocketBotAdapter(
            BotSettings settings,
            UserState userState,
            ConversationState conversationState,
            ResponseManager responseManager,
            TelemetryInitializerMiddleware telemetryMiddleware,
            IBotTelemetryClient telemetryClient)
            : base(null, telemetryClient)
        {
            OnTurnError = async(context, exception) =>
            {
                CultureInfo.CurrentUICulture = new CultureInfo(context.Activity.Locale);
                await context.SendActivityAsync(responseManager.GetResponse(CalendarSharedResponses.CalendarErrorMessage));

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

                telemetryClient.TrackException(exception);
            };

            Use(telemetryMiddleware);

            Use(new TranscriptLoggerMiddleware(new AzureBlobTranscriptStore(settings.BlobStorage.ConnectionString, settings.BlobStorage.Container)));
            Use(new TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: true));
            Use(new SetLocaleMiddleware(settings.DefaultLocale ?? "en-us"));
            Use(new EventDebuggerMiddleware());
            Use(new SkillMiddleware(userState, conversationState, conversationState.CreateProperty <DialogState>(nameof(DialogState))));
        }
        public DefaultAdapter(
            BotSettings settings,
            ICredentialProvider credentialProvider,
            TelemetryInitializerMiddleware telemetryMiddleware,
            IBotTelemetryClient telemetryClient,
            ResponseManager responseManager)
            : base(credentialProvider)
        {
            OnTurnError = async(context, exception) =>
            {
                await context.SendActivityAsync(responseManager.GetResponse(SharedResponses.ErrorMessage));

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

                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 TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: true));
            Use(new ShowTypingMiddleware());
            Use(new SetLocaleMiddleware(settings.DefaultLocale ?? "en-us"));
            Use(new EventDebuggerMiddleware());
        }
        public DefaultAdapter(
            BotSettings settings,
            ICredentialProvider credentialProvider,
            IChannelProvider channelProvider,
            LocaleTemplateManager templateFile,
            ConversationState conversationState,
            TelemetryInitializerMiddleware telemetryMiddleware,
            IBotTelemetryClient telemetryClient)
            : 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 FeedbackMiddleware(conversationState, telemetryClient, new FeedbackOptions()));
            Use(new SetSpeakMiddleware());
        }
        public DefaultAdapter(
            BotSettings settings,
            ICredentialProvider credentialProvider,
            IChannelProvider channelProvider,
            AuthenticationConfiguration authConfig,
            LocaleTemplateManager templateEngine,
            ConversationState conversationState,
            TelemetryInitializerMiddleware telemetryMiddleware,
            IBotTelemetryClient telemetryClient,
            ILogger <BotFrameworkHttpAdapter> logger)
            : 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));

            OnTurnError = HandleTurnErrorAsync;

            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 TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: true));
            Use(new ShowTypingMiddleware());
            Use(new SetLocaleMiddleware(settings.DefaultLocale ?? "en-us"));
            Use(new EventDebuggerMiddleware());
            Use(new SetSpeakMiddleware());
        }
        public DefaultAdapter(
            BotSettings settings,
            ICredentialProvider credentialProvider,
            IBotTelemetryClient telemetryClient,
            ResponseManager responseManager,
            TelemetryInitializerMiddleware telemetryMiddleware)
            : base(credentialProvider)
        {
            OnTurnError = async(context, exception) =>
            {
                CultureInfo.CurrentUICulture = new CultureInfo(context.Activity.Locale);
                await context.SendActivityAsync(responseManager.GetResponse(ToDoSharedResponses.ToDoErrorMessage));

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

                telemetryClient.TrackException(exception);
            };

            Use(telemetryMiddleware);
            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());
        }
Esempio n. 6
0
 public AdapterWithErrorHandler(IConfiguration configuration,
                                ILogger <BotFrameworkHttpAdapter> logger, TranslationMiddleware translationMiddleware,
                                TelemetryInitializerMiddleware telemetryInitializerMiddleware, ConversationState conversationState = null)
     : base(configuration, logger)
 {
     Use(telemetryInitializerMiddleware);
     Use(translationMiddleware);
     OnTurnError = async(turnContext, exception) =>
     {
         logger.LogError($"Exception caught : {exception.Message}");
         await turnContext.SendActivityAsync("Sorry, it looks like something went wrong.");
     };
 }
        public DefaultAdapter(
            BotSettings settings,
            UserState userState,
            ConversationState conversationState,
            IChannelProvider channelProvider,
            ICredentialProvider credentialProvider,
            TelemetryInitializerMiddleware telemetryMiddleware,
            IBotTelemetryClient telemetryClient)
            : base(credentialProvider, channelProvider)
        {
            OnTurnError = async(turnContext, exception) =>
            {
                try
                {
                    await turnContext.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : $"Exception Message: {exception.Message}, Stack: {exception.StackTrace}"));

                    await turnContext.SendActivityAsync($"Exception Message: {exception.Message}, Stack: {exception.StackTrace}");

                    telemetryClient.TrackException(exception);

                    if (turnContext.IsSkill())
                    {
                        // Send and EndOfConversation activity to the skill caller with the error to end the conversation
                        // and let the caller decide what to do.
                        var endOfConversation = Activity.CreateEndOfConversationActivity();
                        endOfConversation.Code = "SkillError";
                        endOfConversation.Text = exception.Message;
                        await turnContext.SendActivityAsync(endOfConversation);
                    }
                }
                catch
                {
                    System.Diagnostics.Trace.TraceError("MATKY PICI");
                    throw 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 TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: true));
            Use(new ShowTypingMiddleware());
            Use(new SetLocaleMiddleware(settings.DefaultLocale ?? "en-us"));
            Use(new EventDebuggerMiddleware());
            Use(new SkillMiddleware(userState, conversationState, conversationState.CreateProperty <DialogState>(nameof(DialogState))));
            Use(new SetSpeakMiddleware());
        }
        public AdapterWithErrorHandler(IConfiguration configuration, ILogger <BotFrameworkHttpAdapter> logger,
                                       TelemetryInitializerMiddleware telemetryInitializerMiddleware, AutoSaveStateMiddleware autoSaveStateMiddleware)
            : base(configuration, logger)
        {
            Use(telemetryInitializerMiddleware);
            Use(autoSaveStateMiddleware);

            OnTurnError = async(turnContext, exception) =>
            {
                // Log any leaked exception from the application.
                logger.LogError(exception, $"Exception caught : {exception.Message}");

                // Send a catch-all apology to the user.
                await turnContext.SendActivityAsync("Sorry, it looks like something went wrong.");
            };
        }
Esempio n. 9
0
        // https://github.com/microsoft/BotBuilder-Samples/blob/main/samples/csharp_dotnetcore/13.core-bot/AdapterWithErrorHandler.cs
        // https://docs.microsoft.com/ja-jp/azure/bot-service/bot-builder-telemetry?view=azure-bot-service-4.0&tabs=csharp
        public TwitterConversationAdapterWithErrorHandler(
            TwitterService twitterService,
            IOptions <TwitterConversationAdapterOptions> options,
            ILogger <BotFrameworkHttpAdapter> logger,
            TelemetryInitializerMiddleware telemetryInitializerMiddleware,
            ConversationState conversationState = null
            ) : base(twitterService, options)
        {
            Use(telemetryInitializerMiddleware);
            OnTurnError = async(turnContext, exception) =>
            {
                // Log any leaked exception from the application.
                // NOTE: In production environment, you should consider logging this to
                // Azure Application Insights. Visit https://aka.ms/bottelemetry to see how
                // to add telemetry capture to your bot.
                logger.LogError(exception, $"[OnTurnError] unhandled error : {exception.Message}");

                // Send a message to the user
                var errorMessageText = "The bot encountered an error or bug.";
                var errorMessage     = MessageFactory.Text(errorMessageText, errorMessageText, InputHints.IgnoringInput);
                await turnContext.SendActivityAsync(errorMessage);

                errorMessageText = "To continue to run this bot, please fix the bot source code.";
                errorMessage     = MessageFactory.Text(errorMessageText, errorMessageText, InputHints.ExpectingInput);
                await turnContext.SendActivityAsync(errorMessage);

                if (conversationState != null)
                {
                    try
                    {
                        // Delete the conversationState for the current conversation to prevent the
                        // bot from getting stuck in a error-loop caused by being in a bad state.
                        // ConversationState should be thought of as similar to "cookie-state" in a Web pages.
                        await conversationState.DeleteAsync(turnContext);
                    }
                    catch (Exception e)
                    {
                        logger.LogError(e, $"Exception caught on attempting to Delete ConversationState : {e.Message}");
                    }
                }

                // Send a trace activity, which will be displayed in the Bot Framework Emulator
                await turnContext.TraceActivityAsync("OnTurnError Trace", exception.Message, "https://www.botframework.com/schemas/error", "TurnError");
            };
        }
Esempio n. 10
0
        public DefaultAdapter(
            BotSettings settings,
            ICredentialProvider credentialProvider,
            IChannelProvider channelProvider,
            AuthenticationConfiguration authConfig,
            LocaleTemplateManager templateEngine,
            ConversationState conversationState,
            TelemetryInitializerMiddleware telemetryMiddleware,
            IBotTelemetryClient telemetryClient,
            ILogger <BotFrameworkHttpAdapter> logger,
            IStorage storage,
            UserState userState,
            IConfiguration configuration,
            SkillConversationIdFactoryBase skillConversationIdFactoryBase,
            BotFrameworkClient botFrameworkClient)
            : 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));
            _skillConversationIdFactoryBase = skillConversationIdFactoryBase;

            OnTurnError = HandleTurnErrorAsync;

            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 TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: true));
            Use(new ShowTypingMiddleware());
            Use(new SetLocaleMiddleware(settings.DefaultLocale ?? "en-us"));
            Use(new EventDebuggerMiddleware());
            Use(new SetSpeakMiddleware());
            Use(new RegisterClassMiddleware <SkillConversationIdFactoryBase>(_skillConversationIdFactoryBase));
            Use(new RegisterClassMiddleware <BotFrameworkClient>(botFrameworkClient));

            //from instructions: https://microsoft.github.io/botframework-solutions/skills/handbook/experimental-add-composer/
            this.Use(new RegisterClassMiddleware <IConfiguration>(configuration));
            this.UseStorage(storage);
            this.UseBotState(userState);
            this.UseBotState(conversationState);
        }
        public DefaultAdapter(
            BotSettings settings,
            UserState userState,
            ConversationState conversationState,
            ICredentialProvider credentialProvider,
            TelemetryInitializerMiddleware telemetryMiddleware,
            IBotTelemetryClient telemetryClient,
            ResponseManager responseManager)
            : base(credentialProvider)
        {
            OnTurnError = async(context, exception) =>
            {
                CultureInfo.CurrentUICulture = new CultureInfo(context.Activity.Locale ?? "en-us");
                await context.SendActivityAsync(responseManager.GetResponse(POISharedResponses.PointOfInterestErrorMessage));

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

                telemetryClient.TrackException(exception);

                if (context.IsSkill())
                {
                    // Send and EndOfConversation activity to the skill caller with the error to end the conversation
                    // and let the caller decide what to do.
                    var endOfConversation = Activity.CreateEndOfConversationActivity();
                    endOfConversation.Code = "SkillError";
                    endOfConversation.Text = exception.Message;
                    await context.SendActivityAsync(endOfConversation);
                }
            };

            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 TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: true));
            Use(new ShowTypingMiddleware());
            Use(new SetLocaleMiddleware(settings.DefaultLocale ?? "en-us"));
            Use(new EventDebuggerMiddleware());
            Use(new SkillMiddleware(userState, conversationState, conversationState.CreateProperty <DialogState>(nameof(DialogState))));
            Use(new SetSpeakMiddleware());
        }
        public DefaultAdapter(
            BotSettings settings,
            UserState userState,
            ConversationState conversationState,
            ICredentialProvider credentialProvider,
            LocaleTemplateEngineManager localeTemplateEngineManager,
            TelemetryInitializerMiddleware telemetryMiddleware,
            IBotTelemetryClient telemetryClient)
            : base(credentialProvider)
        {
            OnTurnError = async(context, exception) =>
            {
                var activity = localeTemplateEngineManager.GenerateActivityForLocale(CalendarSharedResponses.CalendarErrorMessage);
                await context.SendActivityAsync(activity);

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

                telemetryClient.TrackException(exception);

                if (context.IsSkill())
                {
                    // Send and EndOfConversation activity to the skill caller with the error to end the conversation
                    // and let the caller decide what to do.
                    var endOfConversation = Activity.CreateEndOfConversationActivity();
                    endOfConversation.Code = "SkillError";
                    endOfConversation.Text = exception.Message;
                    await context.SendActivityAsync(endOfConversation);
                }
            };

            Use(telemetryMiddleware);

            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 SkillMiddleware(userState, conversationState, conversationState.CreateProperty <DialogState>(nameof(DialogState))));
            Use(new SetSpeakMiddleware());
        }
        public DefaultAdapter(
            ICredentialProvider credentialProvider,
            IChannelProvider channelProvider,
            AuthenticationConfiguration authConfig,
            ConversationState conversationState,
            UserState userState,
            TelemetryInitializerMiddleware telemetryMiddleware,
            IBotTelemetryClient telemetryClient,
            ILogger <BotFrameworkHttpAdapter> logger)
            : base(credentialProvider, authConfig, channelProvider, logger: logger)
        {
            _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState));
            _userState         = userState ?? throw new ArgumentNullException(nameof(userState));
            _logger            = logger ?? throw new ArgumentNullException(nameof(logger));
            _telemetryClient   = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));

            OnTurnError = HandleTurnErrorAsync;

            Use(telemetryMiddleware);

            //Use(new TranscriptLoggerMiddleware(new AzureBlobTranscriptStore(settings.BlobStorage.ConnectionString, settings.BlobStorage.Container)));
            Use(new TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: true));
            Use(new ShowTypingMiddleware());
        }
Esempio n. 14
0
        public AdapterWithErrorHandler(IConfiguration configuration, ILogger <BotFrameworkHttpAdapter> logger, TelemetryInitializerMiddleware telemetryInitializerMiddleware, ConversationState conversationState = null)
            : base(configuration, logger)

        {
            OnTurnError = async(turnContext, exception) =>
            {
                // Log any leaked exception from the application.
                logger.LogError(exception, $"[OnTurnError] unhandled error : {exception.Message}");

                // Send a message to the user
                await turnContext.SendActivityAsync("The bot encountered an error or bug.");

                await turnContext.SendActivityAsync("To continue to run this bot, please fix the bot source code.");

                if (conversationState != null)
                {
                    try
                    {
                        // Delete the conversationState for the current conversation to prevent the
                        // bot from getting stuck in a error-loop caused by being in a bad state.
                        // ConversationState should be thought of as similar to "cookie-state" in a Web pages.
                        await conversationState.DeleteAsync(turnContext);
                    }
                    catch (Exception e)
                    {
                        logger.LogError(e, $"Exception caught on attempting to Delete ConversationState : {e.Message}");
                    }
                }

                // Send a trace activity, which will be displayed in the Bot Framework Emulator
                await turnContext.TraceActivityAsync("OnTurnError Trace", exception.Message, "https://www.botframework.com/schemas/error", "TurnError");
            };
            Use(telemetryInitializerMiddleware);
        }
Esempio n. 15
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            // Get assets directory.
            var assetsDirectory = GetAssetsDirectory();

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

            var settings = new BotSettings();

            config.Bind(settings);

            var services = builder.Services;

            services.AddSingleton <IConfiguration>(config);

            services.AddLogging();

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

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

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

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

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

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

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

            // Storage
            IStorage storage;

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

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

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

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

            services.AddSingleton(resourceExplorer);

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

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

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

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

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

                return(adapter);
            });

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

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

            // Bot
            services.AddSingleton <IBot>(s =>
                                         new ComposerBot(
                                             s.GetService <ConversationState>(),
                                             s.GetService <UserState>(),
                                             s.GetService <ResourceExplorer>(),
                                             s.GetService <BotFrameworkClient>(),
                                             s.GetService <SkillConversationIdFactoryBase>(),
                                             s.GetService <IBotTelemetryClient>(),
                                             GetRootDialog(assetsDirectory.FullName),
                                             defaultLocale,
                                             removeRecipientMention));
        }
        public AdapterWithErrorHandler(IConfiguration configuration, ILogger <BotFrameworkHttpAdapter> logger, TelemetryInitializerMiddleware telemetryInitializerMiddleware, IBotTelemetryClient botTelemetryClient, ConversationState conversationState = null)
            : base(configuration, logger)
        {
            Use(telemetryInitializerMiddleware);

            //Use telemetry client so that we can trace exceptions into Application Insights
            _adapterBotTelemetryClient = botTelemetryClient;

            OnTurnError = async(turnContext, exception) =>
            {
                // Track exceptions into Application Insights
                // Set up some properties for our exception tracing to give more information
                var properties = new Dictionary <string, string>
                {
                    { "Bot exception caught in", $"{nameof(AdapterWithErrorHandler)} - {nameof(OnTurnError)}" }
                };

                //Send the exception telemetry:
                _adapterBotTelemetryClient.TrackException(exception, properties);

                // Log any leaked exception from the application.
                // NOTE: In production environment, you should consider logging this to
                // Azure Application Insights. Visit https://aka.ms/bottelemetry to see how
                // to add telemetry capture to your bot.
                logger.LogError(exception, $"[OnTurnError] unhandled error : {exception.Message}");

                // Send a message to the user
                var errorMessageText = "The bot encountered an error or bug.";
                var errorMessage     = MessageFactory.Text(errorMessageText, errorMessageText, InputHints.IgnoringInput);
                await turnContext.SendActivityAsync(errorMessage);

                errorMessageText = "To continue to run this bot, please fix the bot source code.";
                errorMessage     = MessageFactory.Text(errorMessageText, errorMessageText, InputHints.ExpectingInput);
                await turnContext.SendActivityAsync(errorMessage);

                if (conversationState != null)
                {
                    try
                    {
                        // Delete the conversationState for the current conversation to prevent the
                        // bot from getting stuck in a error-loop caused by being in a bad state.
                        // ConversationState should be thought of as similar to "cookie-state" in a Web pages.
                        await conversationState.DeleteAsync(turnContext);
                    }
                    catch (Exception e)
                    {
                        logger.LogError(e, $"Exception caught on attempting to Delete ConversationState : {e.Message}");
                    }
                }

                // Send a trace activity, which will be displayed in the Bot Framework Emulator
                await turnContext.TraceActivityAsync("OnTurnError Trace", exception.Message, "https://www.botframework.com/schemas/error", "TurnError");
            };
        }
Esempio n. 17
0
        public AdapterWithErrorHandler(IConfiguration configuration, ILogger <BotFrameworkHttpAdapter> logger, TemplateManager templateManager, TelemetryInitializerMiddleware telemetryInitializerMiddleware, ConversationState conversationState = null, UserState userState = null)
            : base(configuration, logger)
        {
            OnTurnError = async(turnContext, exception) =>
            {
                // Log any leaked exception from the application.
                logger.LogError($"Exception caught : {exception.Message}");

                // Send a catch-all apology to the user.
                var errorMessage = templateManager.GenerateActivity("ErrorMessage");
                await turnContext.SendActivityAsync(errorMessage);

                if (conversationState != null)
                {
                    try
                    {
                        // Delete the conversationState for the current conversation to prevent the
                        // bot from getting stuck in a error-loop caused by being in a bad state.
                        // ConversationState should be thought of as similar to "cookie-state" in a Web pages.
                        await conversationState.DeleteAsync(turnContext);
                    }
                    catch (Exception e)
                    {
                        logger.LogError($"Exception caught on attempting to Delete ConversationState : {e.Message}");
                    }
                }
            };

            Use(telemetryInitializerMiddleware);
            Use(new AutoSaveStateMiddleware(conversationState, userState));
        }
Esempio n. 18
0
        public BotFrameworkHttpAdapter GetBotAdapter(IStorage storage, BotSettings settings, UserState userState, ConversationState conversationState, IServiceProvider s, TelemetryInitializerMiddleware telemetryInitializerMiddleware)
        {
            var adapter = new BotFrameworkHttpAdapter(new ConfigurationCredentialProvider(this.Configuration));

            SetBotAdapter(adapter, storage, settings, userState, conversationState, s, telemetryInitializerMiddleware);
            return(adapter);
        }
Esempio n. 19
0
        public void SetBotAdapter(BotAdapter adapter, IStorage storage, BotSettings settings, UserState userState, ConversationState conversationState, IServiceProvider s, TelemetryInitializerMiddleware telemetryInitializerMiddleware)
        {
            adapter
            .UseStorage(storage)
            .UseBotState(userState)
            .Use(new RegisterClassMiddleware <ConversationState>(conversationState, typeof(ConversationState).FullName))
            .Use(new RegisterClassMiddleware <IConfiguration>(Configuration))
            .Use(new RegisterClassMiddleware <BotAdapter>(adapter))
            .Use(new RegisterClassMiddleware <TaskManager>(new TaskManager()))
            .Use(new HandleGroupMentionMiddleware())
            .Use(new ReferenceMiddleware())
            .Use(telemetryInitializerMiddleware);

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

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

                await conversationState.ClearStateAsync(turnContext).ConfigureAwait(false);

                await conversationState.SaveChangesAsync(turnContext).ConfigureAwait(false);
            };
        }
Esempio n. 20
0
        public BotFrameworkHttpAdapter GetBotAdapter(IStorage storage, BotSettings settings, UserState userState, ConversationState conversationState, IServiceProvider s, TelemetryInitializerMiddleware telemetryInitializerMiddleware)
        {
            var adapter = new BotFrameworkHttpAdapter(new ConfigurationCredentialProvider(this.Configuration));

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

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

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

                await conversationState.ClearStateAsync(turnContext).ConfigureAwait(false);

                await conversationState.SaveChangesAsync(turnContext).ConfigureAwait(false);
            };
            return(adapter);
        }