Skip to content

Commit

Permalink
Code Optimization for samples
Browse files Browse the repository at this point in the history
  • Loading branch information
AjayJ-MSFT committed Feb 18, 2025
1 parent 640a665 commit a93c686
Show file tree
Hide file tree
Showing 51 changed files with 1,699 additions and 1,456 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ namespace Microsoft.BotBuilderSamples
// can tap to provide input.
public class AdaptiveCardActionsBot : ActivityHandler
{
public string commandString = "Please use one of these commands: **Card Actions** for Adaptive Card Actions, **Suggested Actions** for Bot Suggested Actions and **ToggleVisibility** for Action ToggleVisible Card";
private const string CommandString = "Please use one of these commands: **Card Actions** for Adaptive Card Actions, **Suggested Actions** for Bot Suggested Actions and **ToggleVisibility** for Action ToggleVisible Card";

/// <summary>
/// provide logic for when members other than the bot join the conversation
Expand All @@ -30,8 +30,7 @@ protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersA

// Sends an activity to the sender of the incoming activity.
await turnContext.SendActivityAsync(MessageFactory.Text(welcomeText), cancellationToken);

await turnContext.SendActivityAsync(MessageFactory.Text(commandString), cancellationToken);
await turnContext.SendActivityAsync(MessageFactory.Text(CommandString), cancellationToken);
}

/// <summary>
Expand All @@ -46,70 +45,48 @@ protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivi

if (text.Contains("card actions"))
{
string[] path = { ".", "Cards", "AdaptiveCardActions.json" };
var adaptiveCardForPersonalScope = GetFirstOptionsAdaptiveCard(path, turnContext.Activity.From.Name);
await turnContext.SendActivityAsync(MessageFactory.Attachment(adaptiveCardForPersonalScope), cancellationToken);
await SendAdaptiveCardAsync(turnContext, cancellationToken, "AdaptiveCardActions.json");
}
else if (text.Contains("suggested actions"))
{
//Respond to the user.
// Respond to the user.
await turnContext.SendActivityAsync("Please Enter a color from the suggested action choices", cancellationToken: cancellationToken);

string[] path = { ".", "Cards", "SuggestedActions.json" };
var adaptiveCardForPersonalScope = GetFirstOptionsAdaptiveCard(path, turnContext.Activity.From.Name);

// Sends an activity to the sender of the incoming activity.
await turnContext.SendActivityAsync(MessageFactory.Attachment(adaptiveCardForPersonalScope), cancellationToken);

//sends a suggested action card
await SendAdaptiveCardAsync(turnContext, cancellationToken, "SuggestedActions.json");
// Sends a suggested action card
await SendSuggestedActionsAsync(turnContext, cancellationToken);

}
else if (text.Contains("togglevisibility"))
{
string[] path = { ".", "Cards", "ToggleVisibleCard.json" };
var adaptiveCardForPersonalScope = GetFirstOptionsAdaptiveCard(path, turnContext.Activity.From.Name);
await turnContext.SendActivityAsync(MessageFactory.Attachment(adaptiveCardForPersonalScope), cancellationToken);
await SendAdaptiveCardAsync(turnContext, cancellationToken, "ToggleVisibleCard.json");
}
else if (text.Contains("red") || (text.Contains("blue")) || text.Contains("yellow"))
else if (text.Contains("red") || text.Contains("blue") || text.Contains("yellow"))
{
var responseText = ProcessInput(text);
await turnContext.SendActivityAsync(responseText, cancellationToken: cancellationToken);
await SendSuggestedActionsAsync(turnContext, cancellationToken);
}
else
{
await turnContext.SendActivityAsync(MessageFactory.Text(commandString), cancellationToken);
await turnContext.SendActivityAsync(MessageFactory.Text(CommandString), cancellationToken);
}
}
await SendDataOnCardActions(turnContext, cancellationToken);
await SendDataOnCardActionsAsync(turnContext, cancellationToken);
}

/// <summary>
/// ProcessInput takes input string and returns message
/// <summary>
/// </summary>
private static string ProcessInput(string text)
{
const string colorText = "is the best color, I agree.";
switch (text)
{
case "red":
{
return $"Red {colorText}";
}
case "yellow":
{
return $"Yellow {colorText}";
}
case "blue":
{
return $"Blue {colorText}";
}
default:
{
return "Please select a color from the suggested action choices";
}
}
var colorResponses = new Dictionary<string, string>
{
{ "red", $"Red {colorText}" },
{ "yellow", $"Yellow {colorText}" },
{ "blue", $"Blue {colorText}" }
};

return colorResponses.TryGetValue(text, out var response) ? response : "Please select a color from the suggested action choices";
}

/// <summary>
Expand All @@ -120,63 +97,63 @@ private static string ProcessInput(string text)
/// </summary>
private static async Task SendSuggestedActionsAsync(ITurnContext turnContext, CancellationToken cancellationToken)
{
try
var reply = MessageFactory.Text("What is your favorite color?");
reply.SuggestedActions = new SuggestedActions
{
var reply = MessageFactory.Text("What is your favorite color?");
reply.SuggestedActions = new SuggestedActions()
{
Actions = new List<CardAction>()
Actions = new List<CardAction>
{
new CardAction() { Title = "Red", Type = ActionTypes.ImBack, Value = "Red" },
new CardAction() { Title = "Yellow", Type = ActionTypes.ImBack, Value = "Yellow" },
new CardAction() { Title = "Blue", Type = ActionTypes.ImBack, Value = "Blue" },
new CardAction { Title = "Red", Type = ActionTypes.ImBack, Value = "Red" },
new CardAction { Title = "Yellow", Type = ActionTypes.ImBack, Value = "Yellow" },
new CardAction { Title = "Blue", Type = ActionTypes.ImBack, Value = "Blue" }
},
To = new List<string> { turnContext.Activity.From.Id },
};
To = new List<string> { turnContext.Activity.From.Id }
};

await turnContext.SendActivityAsync(reply, cancellationToken);
}
catch (Exception e)
{
throw (e);
}
await turnContext.SendActivityAsync(reply, cancellationToken);
}

/// <summary>
/// sends the response on card action.submit
/// </summary>
private async Task SendDataOnCardActions(ITurnContext turnContext, CancellationToken cancellationToken)
private async Task SendDataOnCardActionsAsync(ITurnContext turnContext, CancellationToken cancellationToken)
{
if (turnContext.Activity.Value != null)
{
var reply = MessageFactory.Text("");
reply.Text = $"Data Submitted : {turnContext.Activity.Value}";
await turnContext.SendActivityAsync(MessageFactory.Text(reply.Text), cancellationToken);
var reply = MessageFactory.Text($"Data Submitted: {turnContext.Activity.Value}");
await turnContext.SendActivityAsync(reply, cancellationToken);
}
}

/// <summary>
/// Sends an adaptive card to the user.
/// </summary>
private async Task SendAdaptiveCardAsync(ITurnContext turnContext, CancellationToken cancellationToken, string cardFileName)
{
string[] path = { ".", "Cards", cardFileName };
var adaptiveCard = GetFirstOptionsAdaptiveCard(path, turnContext.Activity.From.Name);
await turnContext.SendActivityAsync(MessageFactory.Attachment(adaptiveCard), cancellationToken);
}

/// <summary>
/// Get the initial card
/// </summary>
private Attachment GetFirstOptionsAdaptiveCard(string[] filepath, string name = null, string userMRI = null)
{
var adaptiveCardJson = File.ReadAllText(Path.Combine(filepath));
AdaptiveCardTemplate template = new AdaptiveCardTemplate(adaptiveCardJson);
var template = new AdaptiveCardTemplate(adaptiveCardJson);
var payloadData = new
{
createdById = userMRI,
createdBy = name
};

//"Expand" the template -this generates the final Adaptive Card payload
var cardJsonstring = template.Expand(payloadData);
var adaptiveCardAttachment = new Attachment()
// "Expand" the template - this generates the final Adaptive Card payload
var cardJsonString = template.Expand(payloadData);
return new Attachment
{
ContentType = "application/vnd.microsoft.card.adaptive",
Content = JsonConvert.DeserializeObject(cardJsonstring),
Content = JsonConvert.DeserializeObject(cardJsonString)
};

return adaptiveCardAttachment;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,33 @@

namespace Microsoft.BotBuilderSamples
{
// This ASP Controller is created to handle a request. Dependency Injection will provide the Adapter and IBot
// implementation at runtime. Multiple different IBot implementations running at different endpoints can be
// achieved by specifying a more specific type for the bot constructor argument.
/// <summary>
/// This ASP Controller is created to handle a request. Dependency Injection will provide the Adapter and IBot
/// implementation at runtime. Multiple different IBot implementations running at different endpoints can be
/// achieved by specifying a more specific type for the bot constructor argument.
/// </summary>
[Route("api/messages")]
[ApiController]
public class BotController : ControllerBase
{
private readonly IBotFrameworkHttpAdapter _adapter;
private readonly IBot _bot;

/// <summary>
/// Initializes a new instance of the <see cref="BotController"/> class.
/// </summary>
/// <param name="adapter">The bot framework HTTP adapter.</param>
/// <param name="bot">The bot instance.</param>
public BotController(IBotFrameworkHttpAdapter adapter, IBot bot)
{
_adapter = adapter;
_bot = bot;
}

/// <summary>
/// Handles the HTTP POST request to process bot messages.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[HttpPost]
public async Task PostAsync()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,37 @@

namespace Microsoft.BotBuilderSamples
{
/// <summary>
/// The main entry point for the application.
/// </summary>
public class Program
{
/// <summary>
/// The main method which is the entry point of the application.
/// </summary>
/// <param name="args">The command-line arguments.</param>
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

/// <summary>
/// Creates and configures a host builder.
/// </summary>
/// <param name="args">The command-line arguments.</param>
/// <returns>An initialized <see cref="IHostBuilder"/> instance.</returns>
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureLogging((logging) =>
// Configure logging to include debug and console outputs
webBuilder.ConfigureLogging(logging =>
{
logging.AddDebug();
logging.AddConsole();
});

// Specify the startup class to use
webBuilder.UseStartup<Startup>();
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,28 +10,41 @@

namespace Microsoft.BotBuilderSamples
{
/// <summary>
/// Configures services and the app's request pipeline.
/// </summary>
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services">The collection of service descriptors.</param>
public void ConfigureServices(IServiceCollection services)
{
// Add HTTP client and controllers with NewtonsoftJson support
services.AddHttpClient().AddControllers().AddNewtonsoftJson();

// Create the Bot Framework Adapter with error handling enabled.
services.AddSingleton<IBotFrameworkHttpAdapter, AdapterWithErrorHandler>();

// Create the bot as a transient. In this case the ASP Controller is expecting an IBot.
// Create the bot as a transient. In this case, the ASP Controller is expecting an IBot.
services.AddTransient<IBot, AdaptiveCardActionsBot>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
/// <param name="app">The application builder.</param>
/// <param name="env">The web hosting environment.</param>
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
// Use developer exception page in development environment
app.UseDeveloperExceptionPage();
}

// Configure the HTTP request pipeline
app.UseDefaultFiles()
.UseStaticFiles()
.UseRouting()
Expand Down
Loading

0 comments on commit a93c686

Please sign in to comment.