Merge branch 'master' into connectorclientex

This commit is contained in:
Tom Laird-McConnell 2018-02-27 14:24:23 -08:00 коммит произвёл GitHub
Родитель 3ed3b2cf1f 371c36ecbe
Коммит 127107b7f6
25 изменённых файлов: 298 добавлений и 396 удалений

11
.gitignore поставляемый
Просмотреть файл

@ -376,14 +376,6 @@ ModelManifest.xml
/PublishScripts/Scripts/Deploy-AzureResourceGroup-5.ps1
/PublishScripts
# User-specific files
Documentation/Doxygen_warnings.txt
@ -393,4 +385,5 @@ Documentation/docs/
# Azure publish profiles
*.pubxml
PublishProfiles/
>>>>>>> adc0f559ad838ead705dbdd88fcbfae8980f2662
appsettings.local.json

Просмотреть файл

@ -1,7 +1,4 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27130.2036
isualStudioVersion = 15.0.27004.2010
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Libraries", "Libraries", "{4269F3C3-6B42-419B-B64A-3E6DC0F1574A}"
EndProject
@ -33,14 +30,14 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Bot.Builder", "li
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Bot.Samples.Connector.EchoBot", "samples\Microsoft.Bot.Samples.Connector.EchoBot\Microsoft.Bot.Samples.Connector.EchoBot.csproj", "{92DFB040-DC80-4AC7-A0CB-A2DDF4844B9B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Bot.Samples.CustomMiddleware", "samples\Microsoft.Bot.Samples.CustomMiddleware\Microsoft.Bot.Samples.CustomMiddleware.csproj", "{C6485617-FBD0-4E7B-894A-214D11D2425F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Bot.Samples.EchoBot-AspNet461", "samples\Microsoft.Bot.Samples.EchoBot-AspNet461\Microsoft.Bot.Samples.EchoBot-AspNet461.csproj", "{AAC0F76C-4114-4D64-A99E-8BE4C43982F9}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Bot.Samples.EchoBot-Console", "samples\Microsoft.Bot.Samples.EchoBot-Console\Microsoft.Bot.Samples.EchoBot-Console.csproj", "{C8DF8AE3-0A4D-445D-993E-F7A1784BFDD4}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Bot.Connector.Tests", "tests\Microsoft.Bot.Connector.Tests\Microsoft.Bot.Connector.Tests.csproj", "{BF414C86-DB3B-4022-9B29-DCE8AA954C12}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Bot.Samples.Ai.QnA", "samples\Microsoft.Bot.Samples.Ai.QnA\Microsoft.Bot.Samples.Ai.QnA.csproj", "{A8CE6B0F-E054-45F7-B4D7-23D2C65D2D26}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -95,10 +92,6 @@ Global
{92DFB040-DC80-4AC7-A0CB-A2DDF4844B9B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{92DFB040-DC80-4AC7-A0CB-A2DDF4844B9B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{92DFB040-DC80-4AC7-A0CB-A2DDF4844B9B}.Release|Any CPU.Build.0 = Release|Any CPU
{C6485617-FBD0-4E7B-894A-214D11D2425F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C6485617-FBD0-4E7B-894A-214D11D2425F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C6485617-FBD0-4E7B-894A-214D11D2425F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C6485617-FBD0-4E7B-894A-214D11D2425F}.Release|Any CPU.Build.0 = Release|Any CPU
{AAC0F76C-4114-4D64-A99E-8BE4C43982F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AAC0F76C-4114-4D64-A99E-8BE4C43982F9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AAC0F76C-4114-4D64-A99E-8BE4C43982F9}.Release|Any CPU.ActiveCfg = Release|Any CPU
@ -111,6 +104,10 @@ Global
{BF414C86-DB3B-4022-9B29-DCE8AA954C12}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BF414C86-DB3B-4022-9B29-DCE8AA954C12}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BF414C86-DB3B-4022-9B29-DCE8AA954C12}.Release|Any CPU.Build.0 = Release|Any CPU
{A8CE6B0F-E054-45F7-B4D7-23D2C65D2D26}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A8CE6B0F-E054-45F7-B4D7-23D2C65D2D26}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A8CE6B0F-E054-45F7-B4D7-23D2C65D2D26}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A8CE6B0F-E054-45F7-B4D7-23D2C65D2D26}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -128,10 +125,10 @@ Global
{F0C150E2-9B8A-444C-B70E-97AD918CB3D4} = {4269F3C3-6B42-419B-B64A-3E6DC0F1574A}
{ADA8AB8B-2066-4193-B8F7-985669B23E00} = {4269F3C3-6B42-419B-B64A-3E6DC0F1574A}
{92DFB040-DC80-4AC7-A0CB-A2DDF4844B9B} = {3ADFB27A-95FA-4330-B211-1D66A29A17AB}
{C6485617-FBD0-4E7B-894A-214D11D2425F} = {3ADFB27A-95FA-4330-B211-1D66A29A17AB}
{AAC0F76C-4114-4D64-A99E-8BE4C43982F9} = {3ADFB27A-95FA-4330-B211-1D66A29A17AB}
{C8DF8AE3-0A4D-445D-993E-F7A1784BFDD4} = {3ADFB27A-95FA-4330-B211-1D66A29A17AB}
{BF414C86-DB3B-4022-9B29-DCE8AA954C12} = {AD743B78-D61F-4FBF-B620-FA83CE599A50}
{A8CE6B0F-E054-45F7-B4D7-23D2C65D2D26} = {3ADFB27A-95FA-4330-B211-1D66A29A17AB}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {7173C9F3-A7F9-496E-9078-9156E35D6E16}

Просмотреть файл

@ -81,18 +81,7 @@ namespace Microsoft.Bot.Builder
// Call any registered Middleware Components looking for ReceiveActivity()
if (context.Request != null)
{
bool didAllMiddlewareRun = await _middlewareSet.ReceiveActivityWithStatus(context).ConfigureAwait(false);
if (didAllMiddlewareRun && callback != null)
{
await callback(context).ConfigureAwait(false);
}
else
{
// One of the middleware instances did not call Next(). When this happens,
// by design, we do NOT call the callback handler. This allows
// Middleware interceptors to be written that activly prevent certain
// Activites from being run.
}
await _middlewareSet.ReceiveActivityWithStatus(context, callback).ConfigureAwait(false);
}
else
{

Просмотреть файл

@ -34,9 +34,9 @@ namespace Microsoft.Bot.Builder
};
}
public BotContext(BotAdapter bot, ConversationReference conversationReference)
public BotContext(BotAdapter adapter, ConversationReference conversationReference)
{
_adapter = bot ?? throw new ArgumentNullException(nameof(bot));
_adapter = adapter ?? throw new ArgumentNullException(nameof(adapter));
_conversationReference = conversationReference ?? throw new ArgumentNullException(nameof(conversationReference));
}

Просмотреть файл

@ -232,8 +232,11 @@ namespace Microsoft.Bot.Builder
private static void SetTextAndSpeak(IMessageActivity ma, string text = null, string ssml = null, string inputHint = null)
{
ma.Text = !string.IsNullOrWhiteSpace(text) ? text : string.Empty;
ma.Speak = !string.IsNullOrWhiteSpace(ssml) ? ssml : string.Empty;
// Note: we must put NULL in the fields, as the clients will happily render
// an empty string, which is not the behavior people expect to see.
ma.Text = !string.IsNullOrWhiteSpace(text) ? text : null;
ma.Speak = !string.IsNullOrWhiteSpace(ssml) ? ssml : null;
ma.InputHint = inputHint;
}
}

Просмотреть файл

@ -52,13 +52,13 @@ namespace Microsoft.Bot.Builder.Middleware
public async Task ReceiveActivity(IBotContext context)
{
await ReceiveActivityInternal(context, this._middleware.OfType<IReceiveActivity>().ToArray()).ConfigureAwait(false);
await ReceiveActivityInternal(context, this._middleware.OfType<IReceiveActivity>().ToArray(), null).ConfigureAwait(false);
}
public async Task ReceiveActivity(IBotContext context, NextDelegate next)
{
await ReceiveActivityInternal(context, this._middleware.OfType<IReceiveActivity>().ToArray()).ConfigureAwait(false);
await next().ConfigureAwait(false);
await ReceiveActivityInternal(context, this._middleware.OfType<IReceiveActivity>().ToArray(), null).ConfigureAwait(false);
await next().ConfigureAwait(false);
}
/// <summary>
@ -69,20 +69,30 @@ namespace Microsoft.Bot.Builder.Middleware
/// <returns>True, if all executed middleware in the pipeline called Next().
/// False, if one of the middleware instances did not call Next().
/// </returns>
public async Task<bool> ReceiveActivityWithStatus(IBotContext context)
public async Task ReceiveActivityWithStatus(IBotContext context, Func<IBotContext, Task> callback)
{
return await ReceiveActivityInternal(context, this._middleware.OfType<IReceiveActivity>().ToArray()).ConfigureAwait(false);
await ReceiveActivityInternal(context, this._middleware.OfType<IReceiveActivity>().ToArray(), callback).ConfigureAwait(false);
}
private async Task<bool> ReceiveActivityInternal(IBotContext context, IReceiveActivity[] middleware)
private async Task ReceiveActivityInternal(IBotContext context, IReceiveActivity[] middleware, Func<IBotContext, Task> callback)
{
BotAssert.MiddlewareNotNull(middleware);
bool didAllRun = false;
if (middleware.Length == 0) // No middleware to run.
{
// If all the Middlware ran, let the caller know.
return true;
// If all the Middlware ran, the "leading edge" of the tree is now complete.
// This means it's time to run any developer specified callback.
// Once this callback is done, the "trailing edge" calls are then completed. This
// allows code that looks like:
// console.print("before");
// await next();
// console.print("after");
// to run as expected.
if (callback != null)
await callback(context);
return;
}
// Default to "No more Middleware after this"
@ -91,12 +101,11 @@ namespace Microsoft.Bot.Builder.Middleware
// Remove the first item from the list of middleware to call,
// so that the next call just has the remaining items to worry about.
IReceiveActivity[] remainingMiddleware = middleware.Skip(1).ToArray();
didAllRun |= await ReceiveActivityInternal(context, remainingMiddleware).ConfigureAwait(false);
await ReceiveActivityInternal(context, remainingMiddleware, callback).ConfigureAwait(false);
}
// Grab the current middleware, which is the 1st element in the array, and execute it
await middleware[0].ReceiveActivity(context, next).ConfigureAwait(false);
return didAllRun;
}
public async Task SendActivity(IBotContext context, IList<IActivity> activities)

Просмотреть файл

@ -40,7 +40,7 @@ namespace Microsoft.Bot.Builder.Adapters
return this;
}
public async Task ProcessActivty(string authHeader, Activity activity, Func<IBotContext, Task> callback)
public async Task ProcessActivity(string authHeader, Activity activity, Func<IBotContext, Task> callback)
{
BotAssert.ActivityNotNull(activity);
await JwtTokenValidation.AssertValidActivity(activity, authHeader, _credentialProvider, _httpClient);

Просмотреть файл

@ -28,7 +28,7 @@ namespace Microsoft.Bot.Builder
{
try
{
await _adapter.ProcessActivty(this.Request.Headers["Authorization"].FirstOrDefault(), activity, OnReceiveActivity);
await _adapter.ProcessActivity(this.Request.Headers["Authorization"].FirstOrDefault(), activity, OnReceiveActivity);
return this.Ok();
}
catch (UnauthorizedAccessException)

Просмотреть файл

@ -28,7 +28,7 @@ namespace Microsoft.Bot.Builder
{
try
{
await _adapter.ProcessActivty(this.Request.Headers["Authorization"].FirstOrDefault(), activity, OnReceiveActivity);
await _adapter.ProcessActivity(this.Request.Headers["Authorization"].FirstOrDefault(), activity, OnReceiveActivity);
return this.Ok();
}
catch (UnauthorizedAccessException)

Просмотреть файл

@ -1,65 +1,65 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Ai;
using Microsoft.Bot.Builder.BotFramework;
using Microsoft.Bot.Schema;
using Microsoft.Extensions.Configuration;
namespace Microsoft.Bot.Samples.Ai.QnA.Controllers
{
[Route("api/[controller]")]
public class MessagesController : Controller
{
private static readonly HttpClient _httpClient = new HttpClient();
static BotFrameworkAdapter adapter;
public MessagesController(IConfiguration configuration)
{
if (adapter == null)
{
var qnaOptions = new QnAMakerMiddlewareOptions
{
// add subscription key and knowledge base id
SubscriptionKey = "xxxxxx",
KnowledgeBaseId = "xxxxxx"
};
adapter = new BotFrameworkAdapter(configuration)
// add QnA middleware
.Use(new QnAMakerMiddleware(qnaOptions, _httpClient));
}
}
private Task BotReceiveHandler(IBotContext context)
{
if (context.Request.Type == ActivityTypes.Message && context.Responses.Count == 0)
{
// add app logic when QnA Maker doesn't find an answer
context.Reply("No good match found in the KB.");
}
return Task.CompletedTask;
}
[HttpPost]
public async Task<IActionResult> Post([FromBody]Activity activity)
{
try
{
await adapter.ProcessActivty(this.Request.Headers["Authorization"].FirstOrDefault(), activity, BotReceiveHandler);
return this.Ok();
}
catch (UnauthorizedAccessException)
{
return this.Unauthorized();
}
}
}
}
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Adapters;
using Microsoft.Bot.Builder.Ai;
using Microsoft.Bot.Schema;
using Microsoft.Extensions.Configuration;
namespace Microsoft.Bot.Samples.Ai.QnA.Controllers
{
[Route("api/[controller]")]
public class MessagesController : Controller
{
private static readonly HttpClient _httpClient = new HttpClient();
static BotFrameworkAdapter adapter;
public MessagesController(IConfiguration configuration)
{
if (adapter == null)
{
var qnaOptions = new QnAMakerMiddlewareOptions
{
// add subscription key and knowledge base id
SubscriptionKey = "xxxxxx",
KnowledgeBaseId = "xxxxxx"
};
adapter = new BotFrameworkAdapter(configuration)
// add QnA middleware
.Use(new QnAMakerMiddleware(qnaOptions, _httpClient));
}
}
private Task BotReceiveHandler(IBotContext context)
{
if (context.Request.Type == ActivityTypes.Message && context.Responses.Count == 0)
{
// add app logic when QnA Maker doesn't find an answer
context.Reply("No good match found in the KB.");
}
return Task.CompletedTask;
}
[HttpPost]
public async Task<IActionResult> Post([FromBody]Activity activity)
{
try
{
await adapter.ProcessActivity(this.Request.Headers["Authorization"].FirstOrDefault(), activity, BotReceiveHandler);
return this.Ok();
}
catch (UnauthorizedAccessException)
{
return this.Unauthorized();
}
}
}
}

Просмотреть файл

@ -14,7 +14,6 @@
<ItemGroup>
<ProjectReference Include="..\..\libraries\Microsoft.Bot.Builder.Ai\Microsoft.Bot.Builder.Ai.csproj" />
<ProjectReference Include="..\..\libraries\Microsoft.Bot.Builder.BotFramework\Microsoft.Bot.Builder.BotFramework.csproj" />
<ProjectReference Include="..\..\libraries\Microsoft.Bot.Builder\Microsoft.Bot.Builder.csproj" />
<ProjectReference Include="..\..\libraries\Microsoft.Bot.Connector\Microsoft.Bot.Connector.csproj" />
<ProjectReference Include="..\..\libraries\Microsoft.Bot.Schema\Microsoft.Bot.Schema.csproj" />

Просмотреть файл

@ -1,62 +0,0 @@
// Copyright(c) Microsoft Corporation.All rights reserved.
// Licensed under the MIT License.
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Adapters;
using Microsoft.Bot.Builder.Middleware;
using Microsoft.Bot.Schema;
using Microsoft.Extensions.Configuration;
namespace Microsoft.Bot.Samples.CustomMiddleware
{
[Route("api/[controller]")]
public class MessagesController : Controller
{
private static BotFrameworkAdapter adapter;
/// <summary>
/// In this sample Bot, a new instance of the Bot is created by the controller
/// on every incoming HTTP reques. The bot is constructed using the credentials
/// found in the config file. Note that no credentials are needed if testing
/// the bot locally using the emulator.
/// </summary>
public MessagesController(IConfiguration configuration)
{
if (adapter == null)
{
adapter = new BotFrameworkAdapter(configuration)
.Use(new ExampleMiddleware("X"))
.Use(new ExampleMiddleware("\tY"))
.Use(new ExampleMiddleware("\t\tZ"));
}
}
private Task BotReceiveHandler(IBotContext context)
{
if (context.Request.Type == ActivityTypes.Message)
{
context.Reply("hello");
}
return Task.CompletedTask;
}
[HttpPost]
public async Task<IActionResult> Post([FromBody]Activity activity)
{
try
{
await adapter.ProcessActivty(this.Request.Headers["Authorization"].FirstOrDefault(), activity, BotReceiveHandler);
return this.Ok();
}
catch (UnauthorizedAccessException)
{
return this.Unauthorized();
}
}
}
}

Просмотреть файл

@ -1,23 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.3" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\libraries\Microsoft.Bot.Builder.Core\Microsoft.Bot.Builder.Core.csproj" />
<ProjectReference Include="..\..\libraries\Microsoft.Bot.Builder\Microsoft.Bot.Builder.csproj" />
<ProjectReference Include="..\..\libraries\Microsoft.Bot.Connector\Microsoft.Bot.Connector.csproj" />
<ProjectReference Include="..\..\libraries\Microsoft.Bot.Schema\Microsoft.Bot.Schema.csproj" />
</ItemGroup>
</Project>

Просмотреть файл

@ -1,75 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Middleware;
using Microsoft.Bot.Schema;
namespace Microsoft.Bot.Samples.CustomMiddleware
{
public class ExampleMiddleware : IContextCreated, IReceiveActivity, ISendActivity
{
private string _name;
private static object _syncRoot = new object();
public ExampleMiddleware(string name)
{
_name = name;
}
public async Task ContextCreated(IBotContext context, MiddlewareSet.NextDelegate next)
{
Write($"BEFORE ContextCreated");
await next();
Write($"AFTER ContextCreated");
}
public async Task ReceiveActivity(IBotContext context, MiddlewareSet.NextDelegate next)
{
Write($"BEFORE ReceiveActivity {PrettyPrint(context.Request)}");
await next();
Write($"AFTER ReceiveActivity {PrettyPrint(context.Request)}");
}
public async Task SendActivity(IBotContext context, IList<IActivity> activities, MiddlewareSet.NextDelegate next)
{
Write($"BEFORE SendActivity {PrettyPrint(context.Responses)}");
await next();
Write($"AFTER SendActivity {PrettyPrint(context.Responses)}");
}
private void Write(string message)
{
lock (_syncRoot)
{
using (var writer = new StreamWriter(@"C:\Users\Public\ExampleMiddleware.txt", true))
{
writer.WriteLine($"{_name} {message}");
}
}
}
private string PrettyPrint(IActivity activity)
{
if (activity.Type == ActivityTypes.Message)
{
return $"{ActivityTypes.Message}({((IMessageActivity)activity).Text})";
}
return activity.Type;
}
private string PrettyPrint(IList<IActivity> activities)
{
var s = new StringBuilder();
foreach (var activity in activities)
{
s.AppendFormat($"{PrettyPrint(activity)} ");
}
return s.ToString();
}
}
}

Просмотреть файл

@ -1,21 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace Microsoft.Bot.Samples.CustomMiddleware
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}

Просмотреть файл

@ -1,46 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Microsoft.Bot.Samples.CustomMiddleware
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(_ => Configuration);
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc();
}
}
}

Просмотреть файл

@ -1,10 +0,0 @@
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}

Просмотреть файл

@ -1,15 +0,0 @@
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
}
}

Просмотреть файл

@ -1,4 +0,0 @@
# Custom Middleware sample
This sample shows a Microsoft.Bot.Builder middleware class ( ~Middleware/ExampleMiddleware.cs ) which writes to log on every incoming and outgoing
activity

Просмотреть файл

@ -1,10 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Sample Bot with Custom Middleware</title>
</head>
<body>
Sample Bot with Custom Middleware
</body>
</html>

Просмотреть файл

@ -29,7 +29,7 @@ namespace Microsoft.Bot.Builder
{
try
{
await _adapter.ProcessActivty(this.Request.Headers.Authorization?.Parameter, activity, OnReceiveActivity);
await _adapter.ProcessActivity(this.Request.Headers.Authorization?.Parameter, activity, OnReceiveActivity);
return this.Request.CreateResponse(HttpStatusCode.OK);
}
catch (UnauthorizedAccessException e)

Просмотреть файл

@ -1,5 +0,0 @@
{
"MICROSOFT_TRANSLATOR_KEY": "150ae69ac1e94d99ac4d0ea9781de17a",
"MICROSOFT_LUIS_APP_ID": "029ad101-c978-4bbe-b2ae-e95c193ad580",
"MICROSOFT_LUIS_APP_PASSWORD": "c8a9779afc5f4143b11181b997416914"
}

Просмотреть файл

@ -1,11 +1,13 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.Bot.Builder.Adapters;
using Microsoft.Bot.Schema;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Net.Mime;
using System.Threading.Tasks;
namespace Microsoft.Bot.Builder.Tests
{
@ -17,7 +19,7 @@ namespace Microsoft.Bot.Builder.Tests
public void NullText()
{
IMessageActivity message = MessageFactory.Text(null);
Assert.AreEqual(message.Text, string.Empty, "Message Text is not an empty string");
Assert.IsNull(message.Text, "Message Text is not null. Null must have been passed through.");
Assert.AreEqual(message.Type, ActivityTypes.Message, "Incorrect Activity Type");
}
@ -244,5 +246,77 @@ namespace Microsoft.Bot.Builder.Tests
Assert.IsTrue(message.Attachments[0].ContentType == contentType, "Incorrect contentType");
Assert.IsTrue(message.Attachments[0].ContentUrl == uri, "Incorrect Uri");
}
[TestMethod]
public async Task ValidateIMBackWithText()
{
TestAdapter adapter = new TestAdapter();
async Task ReplyWithimBackBack(IBotContext ctx)
{
if (ctx.Request.AsMessageActivity().Text == "test")
{
var activity = MessageFactory.SuggestedActions(new CardAction[]
{
new CardAction(type: "imBack", text: "red", title: "redTitle")
}, "Select color");
ctx.Reply(activity);
}
}
void ValidateIMBack(IActivity activity)
{
Assert.IsTrue(activity.Type == ActivityTypes.Message);
var messageActivity = activity.AsMessageActivity();
Assert.IsTrue(messageActivity.Text == "Select color");
Assert.IsTrue(messageActivity.SuggestedActions.Actions.Count == 1, "Incorrect Count");
Assert.IsTrue(messageActivity.SuggestedActions.Actions[0].Type == ActionTypes.ImBack, "Incorrect Action Type");
Assert.IsTrue(messageActivity.SuggestedActions.Actions[0].Text == "red", "incorrect text");
Assert.IsTrue(messageActivity.SuggestedActions.Actions[0].Title == "redTitle", "incorrect text");
}
await new TestFlow(adapter, ReplyWithimBackBack)
.Send("test")
.AssertReply(ValidateIMBack, "IMBack Did not validate")
.StartTest();
}
[TestMethod]
public async Task ValidateIMBackWithNoTest()
{
TestAdapter adapter = new TestAdapter();
async Task ReplyWithimBackBack(IBotContext ctx)
{
if (ctx.Request.AsMessageActivity().Text == "test")
{
var activity = MessageFactory.SuggestedActions(new CardAction[]
{
new CardAction(type: "imBack", text: "red", title: "redTitle")
}, "");
ctx.Reply(activity);
}
}
void ValidateIMBack(IActivity activity)
{
Assert.IsTrue(activity.Type == ActivityTypes.Message);
var messageActivity = activity.AsMessageActivity();
Assert.IsTrue(messageActivity.Text == null);
Assert.IsTrue(messageActivity.SuggestedActions.Actions.Count == 1, "Incorrect Count");
Assert.IsTrue(messageActivity.SuggestedActions.Actions[0].Type == ActionTypes.ImBack, "Incorrect Action Type");
Assert.IsTrue(messageActivity.SuggestedActions.Actions[0].Text== "red", "incorrect text");
Assert.IsTrue(messageActivity.SuggestedActions.Actions[0].Title == "redTitle", "incorrect text");
}
await new TestFlow(adapter, ReplyWithimBackBack)
.Send("test")
.AssertReply(ValidateIMBack, "IMBack Did not validate")
.StartTest();
}
}
}

Просмотреть файл

@ -0,0 +1,105 @@
using System;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Adapters;
using Microsoft.Bot.Builder.Middleware;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Bot.Builder.Tests
{
[TestClass]
[TestCategory("Middleware")]
public class Middleware_BracketingTest
{
/// <summary>
/// Developer authored Middleware that looks like this:
/// public async Task ReceiveActivity(IBotContext context,
/// MiddlewareSet.NextDelegate next)
/// {
/// context.Reply("BEFORE");
/// await next(); // User Says Hello
/// context.Reply("AFTER");
/// }
/// Should result in an output that looks like:
/// BEFORE
/// ECHO:Hello
/// AFTER
/// </summary>
[TestMethod]
public async Task Middlware_BracketingValidation()
{
TestAdapter adapter = new TestAdapter()
.Use(new BeforeAFterMiddlware());
async Task Echo(IBotContext ctx)
{
ctx.Reply("ECHO:" + ctx.Request.AsMessageActivity().Text);
}
await new TestFlow(adapter, Echo)
.Send("test")
.AssertReply("BEFORE")
.AssertReply("ECHO:test")
.AssertReply("AFTER")
.StartTest();
}
/// <summary>
/// Exceptions thrown during the processing of an Activity should
/// be catchable by Middleware that has wrapped the next() method.
/// This tests verifies that, and makes sure the order of messages
/// coming back is correct.
/// </summary>
[TestMethod]
public async Task Middlware_ThrowException()
{
string uniqueId = Guid.NewGuid().ToString();
TestAdapter adapter = new TestAdapter()
.Use(new CatchExceptionMiddleware());
async Task EchoWithException(IBotContext ctx)
{
ctx.Reply("ECHO:" + ctx.Request.AsMessageActivity().Text);
throw new Exception(uniqueId);
}
await new TestFlow(adapter, EchoWithException)
.Send("test")
.AssertReply("BEFORE")
.AssertReply("ECHO:test")
.AssertReply("CAUGHT:" + uniqueId)
.AssertReply("AFTER")
.StartTest();
}
public class CatchExceptionMiddleware : IMiddleware, IReceiveActivity
{
public async Task ReceiveActivity(IBotContext context, MiddlewareSet.NextDelegate next)
{
context.Reply("BEFORE");
try
{
await next();
}
catch (Exception ex)
{
context.Reply("CAUGHT:" + ex.Message);
}
context.Reply("AFTER");
}
}
public class BeforeAFterMiddlware : IMiddleware, IReceiveActivity
{
public async Task ReceiveActivity(IBotContext context, MiddlewareSet.NextDelegate next)
{
context.Reply("BEFORE");
await next();
context.Reply("AFTER");
}
}
}
}

Просмотреть файл

@ -102,7 +102,8 @@ namespace Microsoft.Bot.Builder.Tests
// The middlware in this pipeline calls next(), so the resulting
// status should be TRUE.
bool didAllRun = await m.ReceiveActivityWithStatus(null);
bool didAllRun = false;
await m.ReceiveActivityWithStatus(null, async (ctx) => didAllRun = true);
Assert.IsTrue(called1);
Assert.IsTrue(didAllRun);
@ -112,11 +113,13 @@ namespace Microsoft.Bot.Builder.Tests
public async Task Status_RunAtEndEmptyPipeline()
{
Middleware.MiddlewareSet m = new Middleware.MiddlewareSet();
bool didAllRun = false;
// This middlware pipeline has no entries. This should result in
// the status being TRUE.
bool didAllRun = await m.ReceiveActivityWithStatus(null);
await m.ReceiveActivityWithStatus(null, async (ctx) => didAllRun = true);
Assert.IsTrue(didAllRun);
}
[TestMethod]
@ -141,7 +144,8 @@ namespace Microsoft.Bot.Builder.Tests
m.Use(one);
m.Use(two);
bool didAllRun = await m.ReceiveActivityWithStatus(null);
bool didAllRun = false;
await m.ReceiveActivityWithStatus(null, async (ctx) => didAllRun = true);
Assert.IsTrue(called1);
Assert.IsTrue(called2);
@ -159,9 +163,9 @@ namespace Microsoft.Bot.Builder.Tests
Middleware.MiddlewareSet m = new Middleware.MiddlewareSet();
m.Use(one);
// The middlware in this pipeline calls next(), so this must
// be called as the final activity.
bool didAllRun = await m.ReceiveActivityWithStatus(null);
// The middlware in this pipeline DOES NOT call next(), so this must not be called
bool didAllRun = false;
await m.ReceiveActivityWithStatus(null, async (ctx) => didAllRun = true);
Assert.IsTrue(called1);
@ -348,7 +352,7 @@ namespace Microsoft.Bot.Builder.Tests
await m.ReceiveActivity(null);
Assert.IsTrue(caughtException);
}
}
public class WasCalledMiddlware : Middleware.IMiddleware, Middleware.IReceiveActivity
{