/// <summary> /// To parse the incoming json from QnA Maker in to a reply /// </summary> /// <param name="customResponse"></param> /// <param name="responseJson"></param> /// <param name="telemetryClient"></param> /// <returns></returns> public static Activity getAnswer(Activity customResponse, string responseJson, IBotTelemetryClient telemetryClient) { Answers answersHolder = null; CardMaker _cardMaker = new CardMaker(telemetryClient); try { answersHolder = JsonConvert.DeserializeObject <Answers>(responseJson.Trim()); } catch (Exception e) { telemetryClient.TrackException(e, TelemetryMetaData.BindExceptionEvent(TelemetryKey.JsonDeserializationError, "QnA Answer Json to Answer Model")); } switch (answersHolder.Type) { case "Multi_Response": customResponse = MessageFactory.Text(answersHolder.Content[RandomSelector.Rand(answersHolder.Content.Count())]); break; case "Image_Response": try { var response = customResponse.CreateReply(); response.Attachments = new List <Attachment>() { _cardMaker.getCardAttachment(_cardMaker.getImage_ResponseCardJson(answersHolder)) }; return(response); } catch (Exception e) { telemetryClient.TrackException(e, TelemetryMetaData.BindExceptionEvent(TelemetryKey.CardRenderError, "Image_Response card error", customResponse.Conversation.Id, responseJson)); } break; case "Card_Response": try { var response = customResponse.CreateReply(); response.Attachments = new List <Attachment>() { _cardMaker.getCardAttachment(_cardMaker.getCard_ResponseCardJson(answersHolder)) }; return(response); } catch (Exception e) { telemetryClient.TrackException(e, TelemetryMetaData.BindExceptionEvent(TelemetryKey.CardRenderError, "Card_Response card error", customResponse.Conversation.Id, responseJson)); } break; default: customResponse = MessageFactory.Text(answersHolder.Content.First()); break; } return(customResponse); }
public DefaultAdapter( BotSettings settings, ICredentialProvider credentialProvider, IBotTelemetryClient telemetryClient, IConfiguration Configuration, BotStateSet botStateSet) : 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); }; 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 AutoSaveStateMiddleware(botStateSet)); Use(new HandoffMiddleware(Configuration)); Use(new CatchExceptionMiddleware <Exception>(async(context, exception) => { await context.TraceActivityAsync("Bot Exception", exception); await context.SendActivityAsync($"Sorry, it looks like something went wrong: {exception.Message}"); })); }
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 CustomSkillAdapter( BotSettings settings, UserState userState, ConversationState conversationState, ResponseManager responseManager, TelemetryInitializerMiddleware telemetryMiddleware, IBotTelemetryClient telemetryClient) : base(null, telemetryClient) { 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 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(POISharedResponses.PointOfInterestErrorMessage)); await context.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : $"PointOfInterest 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 DefaultWebSocketAdapter( IConfiguration config, BotSettings settings, ICredentialProvider credentialProvider, IBotTelemetryClient telemetryClient) : base(config, 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 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(settings.DefaultLocale ?? "en-us")); }
public NewsSkillWebSocketBotAdapter( BotSettings settings, UserState userState, ConversationState conversationState, TelemetryInitializerMiddleware telemetryMiddleware, IBotTelemetryClient telemetryClient) : base(null, telemetryClient) { OnTurnError = async(context, exception) => { CultureInfo.CurrentUICulture = new CultureInfo(context.Activity.Locale); await context.SendActivityAsync(MainStrings.ERROR); await context.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : $"News 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, BotStateSet botStateSet, IBotTelemetryClient telemetryClient, ResponseManager responseManager) : base(credentialProvider) { OnTurnError = async(context, exception) => { CultureInfo.CurrentUICulture = new CultureInfo(context.Activity.Locale); 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(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 AutoSaveStateMiddleware(botStateSet)); }
public AdapterWithErrorHandler(ICredentialProvider creds, ILogger <BotFrameworkHttpAdapter> logger, IMiddleware middleware, IBotTelemetryClient botTelemetery, ConversationState conversationState = null) : base(creds, null, logger) { OnTurnError = async(turnContext, exception) => { botTelemetery.TrackException(exception); // Log any leaked exception from the application. logger.LogError($"Exception caught : {exception.Message}"); // Send a catch-all apology to the user. await turnContext.SendActivityAsync("Sorry, it looks like something went wrong."); 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(middleware); }
public DefaultWebSocketAdapter( IConfiguration config, BotSettings settings, ICredentialProvider credentialProvider, IBotTelemetryClient telemetryClient, BotStateSet botStateSet) : base(config, 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); }; 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 AutoSaveStateMiddleware(botStateSet)); Use(new SetSpeakMiddleware(settings.DefaultLocale ?? "en-us", "Microsoft Server Speech Text to Speech Voice (en-US, JessaNeural)")); }
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)); }
public DefaultAdapter( BotSettings settings, LocaleTemplateEngineManager templateEngine, ICredentialProvider credentialProvider, TelemetryInitializerMiddleware telemetryMiddleware, IBotTelemetryClient telemetryClient) : base(credentialProvider) { OnTurnError = async(turnContext, exception) => { await turnContext.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : $"Exception Message: {exception.Message}, Stack: {exception.StackTrace}")); await turnContext.SendActivityAsync(templateEngine.GenerateActivityForLocale("ErrorMessage")); 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 RestaurantSkillWebSocketBotAdapter( BotSettings settings, UserState userState, ConversationState conversationState, BotStateSet botStateSet, ResponseManager responseManager, IBotTelemetryClient telemetryClient) { OnTurnError = async(context, exception) => { CultureInfo.CurrentUICulture = new CultureInfo(context.Activity.Locale); await context.SendActivityAsync(responseManager.GetResponse(RestaurantBookingSharedResponses.ErrorMessage)); await context.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : $"Restaurant Booking Skill Error: {exception.Message} | {exception.StackTrace}")); telemetryClient.TrackException(exception); }; 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 AutoSaveStateMiddleware(botStateSet)); Use(new SkillMiddleware(userState, conversationState, conversationState.CreateProperty <DialogState>(nameof(RestaurantBooking)))); }
private async Task <T> SendRequestAsync <T>(Request request, CancellationToken cancellation = default(CancellationToken)) { try { var serverResponse = await this.Server.SendAsync(request, cancellation).ConfigureAwait(false); if (serverResponse.StatusCode == (int)HttpStatusCode.OK) { return(serverResponse.ReadBodyAsJson <T>()); } } catch (Exception ex) { _botTelemetryClient.TrackException(ex); throw ex; } return(default(T)); }
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"); }; }
// Invoked when a "task/fetch" event is received to invoke task module. protected override async Task <TaskModuleResponse> OnTeamsTaskModuleFetchAsync(ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken) { try { string skillId = (turnContext.Activity as Activity).GetSkillId(); var skill = _skillsConfig.Skills.Where(s => s.Value.AppId == skillId).FirstOrDefault().Value; // Forward request to correct skill var invokeResponse = await _skillHttpClient.PostActivityAsync(this._appId, skill, _skillsConfig.SkillHostEndpoint, turnContext.Activity as Activity, cancellationToken); return(invokeResponse.GetTaskModuleRespose()); } catch (Exception exception) { await turnContext.SendActivityAsync(_templateEngine.GenerateActivityForLocale("ErrorMessage")); _telemetryClient.TrackException(exception); return(null); } }
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()); }
private async Task SendErrorMessageAsync(ITurnContext turnContext, Exception exception) { try { _telemetryClient.TrackException(exception); // Send a message to the user. await turnContext.SendActivityAsync(_templateEngine.GenerateActivityForLocale(RestaurantBookingSharedResponses.ErrorMessage)); // Send a trace activity, which will be displayed in the Bot Framework Emulator. // Note: we return the entire exception in the value property to help the developer; // this should not be done in production. await turnContext.TraceActivityAsync("OnTurnError Trace", exception.ToString(), "https://www.botframework.com/schemas/error", "TurnError"); } catch (Exception ex) { _logger.LogError(ex, $"Exception caught in SendErrorMessageAsync : {ex}"); } }
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()); }
//When a new chat session starts protected override async Task OnMembersAddedAsync(IList <ChannelAccount> membersAdded, ITurnContext <IConversationUpdateActivity> turnContext, CancellationToken cancellationToken) { foreach (var member in membersAdded) { if (member.Id != turnContext.Activity.Recipient.Id) { //Make welcome card Attachment attachmennt = null; try { var cardjson = File.ReadAllText(Path.Combine(new string[] { ".", @"wwwroot/WelcomeCard.json" })); attachmennt = (new CardMaker(TelemetryClient)).getCardAttachment(cardjson); } catch (Exception e) { TelemetryClient.TrackException(e, TelemetryMetaData.BindExceptionEvent(TelemetryKey.CardRenderError, "Welcome Card Error")); } await turnContext.SendActivityAsync(MessageFactory.Attachment(attachmennt), cancellationToken); } } }
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()); }
private async Task SendErrorMessageAsync(ITurnContext turnContext, Exception exception) { try { // Send a message to the user. CultureInfo.CurrentUICulture = new CultureInfo(turnContext.Activity.Locale ?? "en-us"); await turnContext.SendActivityAsync(_templateManager.GenerateActivity(PhoneSharedResponses.ErrorMessage)); await turnContext.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : $"Phone Skill Error: {exception.Message} | {exception.StackTrace}")); _telemetryClient.TrackException(exception); // Send a trace activity, which will be displayed in the Bot Framework Emulator. // Note: we return the entire exception in the value property to help the developer; // this should not be done in production. await turnContext.TraceActivityAsync("OnTurnError Trace", exception.ToString(), "https://www.botframework.com/schemas/error", "TurnError"); } catch (Exception ex) { _logger.LogError(ex, $"Exception caught in SendErrorMessageAsync : {ex}"); } }
public override async Task <StreamingResponse> ProcessRequestAsync(ReceiveRequest request, ILogger <RequestHandler> logger, object context = null, CancellationToken cancellationToken = default) { var routeContext = _router.Route(request); if (routeContext != null) { try { var responseBody = await routeContext.Action.Action(request, routeContext.RouteData).ConfigureAwait(false); return(StreamingResponse.OK(new StringContent(JsonConvert.SerializeObject(responseBody, SerializationSettings.DefaultSerializationSettings), Encoding.UTF8, SerializationSettings.ApplicationJson))); } catch (Exception ex) { _botTelemetryClient.TrackException(ex); return(StreamingResponse.InternalServerError()); } } else { return(StreamingResponse.NotFound()); } }
public void ConfigureServices(IServiceCollection services) { // Load the connected services from .bot file. string botFilePath = Configuration.GetSection("botFilePath")?.Value; string botFileSecret = Configuration.GetSection("botFileSecret")?.Value; BotConfiguration botConfig = BotConfiguration.Load(botFilePath, botFileSecret); services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot config file could not be loaded.")); // Get default locale from appsettings.json string defaultLocale = Configuration.GetSection("defaultLocale").Get <string>(); // Use Application Insights services.AddBotApplicationInsights(botConfig); // Initializes your bot service clients and adds a singleton that your Bot can access through dependency injection. BotServices connectedServices = new BotServices(botConfig); services.AddSingleton(sp => connectedServices); // Initialize Bot State ConnectedService cosmosDbService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.CosmosDB) ?? throw new Exception("Please configure your CosmosDb service in your .bot file."); CosmosDbService cosmosDb = cosmosDbService as CosmosDbService; CosmosDbStorageOptions cosmosOptions = new CosmosDbStorageOptions() { CosmosDBEndpoint = new Uri(cosmosDb.Endpoint), AuthKey = cosmosDb.Key, CollectionId = cosmosDb.Collection, DatabaseId = cosmosDb.Database, }; CosmosDbStorage dataStore = new CosmosDbStorage(cosmosOptions); UserState userState = new UserState(dataStore); ConversationState conversationState = new ConversationState(dataStore); services.AddSingleton(dataStore); services.AddSingleton(userState); services.AddSingleton(conversationState); services.AddSingleton(new BotStateSet(userState, conversationState)); // Add the bot with options services.AddBot <Bot>(options => { // Load the connected services from .bot file. string environment = _isProduction ? "production" : "development"; ConnectedService service = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.Endpoint && s.Name == environment); if (!(service is EndpointService endpointService)) { throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{environment}'."); } options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword); // Telemetry Middleware (logs activity messages in Application Insights) ServiceProvider sp = services.BuildServiceProvider(); IBotTelemetryClient telemetryClient = sp.GetService <IBotTelemetryClient>(); TelemetryLoggerMiddleware 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) => { telemetryClient.TrackException(exception); //await context.SendActivityAsync(MainStrings.ERROR); await context.SendActivityAsync(exception.ToString()); }; // Transcript Middleware (saves conversation history in a standard format) ConnectedService storageService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.BlobStorage) ?? throw new Exception("Please configure your Azure Storage service in your .bot file."); BlobStorageService blobStorage = storageService as BlobStorageService; AzureBlobTranscriptStore transcriptStore = new AzureBlobTranscriptStore(blobStorage.ConnectionString, blobStorage.Container); TranscriptLoggerMiddleware transcriptMiddleware = new TranscriptLoggerMiddleware(transcriptStore); options.Middleware.Add(transcriptMiddleware); // Typing Middleware (automatically shows typing when the bot is responding/working) options.Middleware.Add(new ShowTypingMiddleware()); // Locale Middleware (sets UI culture based on Activity.Locale) options.Middleware.Add(new SetLocaleMiddleware(defaultLocale ?? "en-us")); // Autosave State Middleware (saves bot state after each turn) options.Middleware.Add(new AutoSaveStateMiddleware(userState, conversationState)); }); }
public static void TrackExceptionEx(this IBotTelemetryClient telemetryClient, Exception exception, Activity activity, string dialogId = null, IDictionary <string, string> properties = null, IDictionary <string, double> metrics = null) { telemetryClient.TrackException(exception, GetFinalProperties(activity, dialogId, properties), metrics); }
public async override Task <Response> ProcessRequestAsync(ReceiveRequest request, object context = null, ILogger <RequestHandler> logger = null) { if (Bot == null) { throw new ArgumentNullException(nameof(Bot)); } if (SkillWebSocketBotAdapter == null) { throw new ArgumentNullException(nameof(SkillWebSocketBotAdapter)); } var response = new Response(); var body = await request.ReadBodyAsString().ConfigureAwait(false); if (string.IsNullOrEmpty(body) || request.Streams?.Count == 0) { response.StatusCode = (int)HttpStatusCode.BadRequest; response.SetBody("Empty request body."); return(response); } if (request.Streams.Where(x => x.Type != "application/json; charset=utf-8").Any()) { response.StatusCode = (int)HttpStatusCode.NotAcceptable; return(response); } Activity activity = null; try { activity = JsonConvert.DeserializeObject <Activity>(body, Serialization.Settings); } catch (Exception ex) { _botTelemetryClient.TrackException(ex); response.StatusCode = (int)HttpStatusCode.BadRequest; response.SetBody("Request body is not an Activity instance."); return(response); } try { var cancellationTokenSource = new CancellationTokenSource(); _stopWatch.Start(); var invokeResponse = await this.SkillWebSocketBotAdapter.ProcessActivityAsync(activity, new BotCallbackHandler(this.Bot.OnTurnAsync), cancellationTokenSource.Token).ConfigureAwait(false); _stopWatch.Stop(); _botTelemetryClient.TrackEvent("SkillWebSocketProcessRequestLatency", null, new Dictionary <string, double> { { "Latency", _stopWatch.ElapsedMilliseconds }, }); // trigger cancel token after activity is handled. this will stop the typing indicator cancellationTokenSource.Cancel(); if (invokeResponse == null) { response.StatusCode = (int)HttpStatusCode.OK; } else { response.StatusCode = invokeResponse.Status; if (invokeResponse.Body != null) { response.SetBody(invokeResponse.Body); } } } catch (SkillWebSocketCallbackException ex) { _botTelemetryClient.TrackException(ex); response.StatusCode = (int)HttpStatusCode.InternalServerError; response.SetBody(ex.Message); return(response); } catch (Exception ex) { _botTelemetryClient.TrackException(ex); response.StatusCode = (int)HttpStatusCode.InternalServerError; } return(response); }