Skip to content

Commit

Permalink
update .21 core app insights sample with core bot 4.5.1 changes (micr…
Browse files Browse the repository at this point in the history
…osoft#2031)

* - Update bot with 4.5.1 changes to core bot sample
- Update to pass TelemetryClient via property on ComponentDialog (in startup.cs) instead of by constructor
- Update FlightBookingRecgnizer to pass TelemetryClient to LuisRecognizer

* Small fixes

* Set LangVersion to latest to ensure build does not fail with C# 7.1 features

* - Remove unnecessary setting of TelemetryClient when adding child dialogs
- Made TelemetryInitializerMiddleware DI scope narrower as per comment from Gabo
- Added missing copyright header
- Reverted pattern to pass TelemetryClient into Main dialog via DI

* Removed remaining redundant TelemetryClient setters when adding new dialogs

* Update comment for setting TelemetryClient in MainDialog
  • Loading branch information
garypretty authored Dec 18, 2019
1 parent b58352d commit 6ca6255
Show file tree
Hide file tree
Showing 33 changed files with 960 additions and 592 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,35 @@

using System;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Integration.ApplicationInsights.Core;
using Microsoft.Bot.Builder.Integration.AspNet.Core;
using Microsoft.Bot.Builder.TraceExtensions;
using Microsoft.Bot.Connector.Authentication;
using Microsoft.Bot.Schema;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace Microsoft.BotBuilderSamples
{
public class AdapterWithErrorHandler : BotFrameworkHttpAdapter
{
public AdapterWithErrorHandler(ICredentialProvider credentialProvider, ILogger<BotFrameworkHttpAdapter> logger, IMiddleware middleware, ConversationState conversationState = null)
: base(credentialProvider)
public AdapterWithErrorHandler(IConfiguration configuration, ILogger<BotFrameworkHttpAdapter> logger, TelemetryInitializerMiddleware telemetryInitializerMiddleware, ConversationState conversationState = null)
: base(configuration, logger)
{
Use(middleware);
Use(telemetryInitializerMiddleware);

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.");
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)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,32 +29,30 @@ protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersA
if (member.Id != turnContext.Activity.Recipient.Id)
{
var welcomeCard = CreateAdaptiveCardAttachment();
var response = CreateResponse(turnContext.Activity, welcomeCard);
var response = MessageFactory.Attachment(welcomeCard, ssml: "Welcome to Bot Framework!");
await turnContext.SendActivityAsync(response, cancellationToken);
await Dialog.RunAsync(turnContext, ConversationState.CreateProperty<DialogState>("DialogState"), cancellationToken);
}
}
}

// Create an attachment message response.
private Activity CreateResponse(IActivity activity, Attachment attachment)
{
var response = ((Activity)activity).CreateReply();
response.Attachments = new List<Attachment>() { attachment };
return response;
}

// Load attachment from file.
// Load attachment from embedded resource.
private Attachment CreateAdaptiveCardAttachment()
{
// combine path for cross platform support
string[] paths = { ".", "Cards", "welcomeCard.json" };
string fullPath = Path.Combine(paths);
var adaptiveCard = File.ReadAllText(fullPath);
return new Attachment()
var cardResourcePath = "CoreBot-App-Insights.Cards.welcomeCard.json";

using (var stream = GetType().Assembly.GetManifestResourceStream(cardResourcePath))
{
ContentType = "application/vnd.microsoft.card.adaptive",
Content = JsonConvert.DeserializeObject(adaptiveCard),
};
using (var reader = new StreamReader(stream))
{
var adaptiveCard = reader.ReadToEnd();
return new Attachment()
{
ContentType = "application/vnd.microsoft.card.adaptive",
Content = JsonConvert.DeserializeObject(adaptiveCard),
};
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivi
Logger.LogInformation("Running dialog with Message Activity.");

// Run the Dialog with the new message Activity.
await Dialog.Run(turnContext, ConversationState.CreateProperty<DialogState>("DialogState"), cancellationToken);
await Dialog.RunAsync(turnContext, ConversationState.CreateProperty<DialogState>("DialogState"), cancellationToken);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
// <auto-generated>
// Code generated by LUISGen .\FlightBooking.json -cs Luis.FlightBooking -o .
// Tool github: https://github.com/microsoft/botbuilder-tools
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
using Newtonsoft.Json;
using System.Collections.Generic;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.AI.Luis;

namespace Microsoft.BotBuilderSamples
{
public partial class FlightBooking: IRecognizerConvert
{
public string Text;
public string AlteredText;
public enum Intent {
BookFlight,
Cancel,
GetWeather,
None
};
public Dictionary<Intent, IntentScore> Intents;

public class _Entities
{

// Built-in entities
public DateTimeSpec[] datetime;

// Lists
public string[][] Airport;

// Composites
public class _InstanceFrom
{
public InstanceData[] Airport;
}
public class FromClass
{
public string[][] Airport;
[JsonProperty("$instance")]
public _InstanceFrom _instance;
}
public FromClass[] From;

public class _InstanceTo
{
public InstanceData[] Airport;
}
public class ToClass
{
public string[][] Airport;
[JsonProperty("$instance")]
public _InstanceTo _instance;
}
public ToClass[] To;

// Instance
public class _Instance
{
public InstanceData[] datetime;
public InstanceData[] Airport;
public InstanceData[] From;
public InstanceData[] To;
}
[JsonProperty("$instance")]
public _Instance _instance;
}
public _Entities Entities;

[JsonExtensionData(ReadData = true, WriteData = true)]
public IDictionary<string, object> Properties {get; set; }

public void Convert(dynamic result)
{
var app = JsonConvert.DeserializeObject<FlightBooking>(JsonConvert.SerializeObject(result, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }));
Text = app.Text;
AlteredText = app.AlteredText;
Intents = app.Intents;
Entities = app.Entities;
Properties = app.Properties;
}

public (Intent intent, double score) TopIntent()
{
Intent maxIntent = Intent.None;
var max = 0.0;
foreach (var entry in Intents)
{
if (entry.Value.Score > max)
{
maxIntent = entry.Key;
max = entry.Value.Score.Value;
}
}
return (maxIntent, max);
}
}
}
Loading

0 comments on commit 6ca6255

Please sign in to comment.