enhance simple alarm bot to have some useful state

This commit is contained in:
Will Portnoy 2016-03-26 17:20:32 -07:00
Родитель deaf2935be
Коммит 969a41421f
5 изменённых файлов: 379 добавлений и 232 удалений

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

@ -74,17 +74,26 @@ namespace Microsoft.Bot.Builder
public Models.EntityRecommendation[] Entities { get; set; }
}
public static partial class Extensions
{
public static bool TryFindEntity(this LuisResult result, string type, out Models.EntityRecommendation entity)
{
entity = result.Entities?.FirstOrDefault(e => e.Type == type);
return entity != null;
}
}
public delegate Task IntentHandler(IDialogContext context, LuisResult luisResult);
[Serializable]
public class LuisDialog : IDialog, ISerializable
public class LuisDialog : IDialog
{
public readonly string subscriptionKey;
public readonly string modelID;
public readonly string luisUrl;
protected readonly Dictionary<string, IntentHandler> handlerByIntent = new Dictionary<string, IntentHandler>();
protected const string DefaultIntentHandler = "87DBD4FD7736";
[NonSerialized]
protected Dictionary<string, IntentHandler> handlerByIntent;
public LuisDialog()
{
@ -109,22 +118,6 @@ namespace Microsoft.Bot.Builder
this.luisUrl = string.Format("https://api.projectoxford.ai/luis/v1/application?id={0}&subscription-key={1}&q=", this.modelID, this.subscriptionKey);
}
protected LuisDialog(SerializationInfo info, StreamingContext context)
{
Field.SetNotNullFrom(out this.luisUrl, nameof(this.luisUrl), info);
Field.SetFrom(out this.subscriptionKey, nameof(this.subscriptionKey), info);
Field.SetFrom(out this.modelID, nameof(this.modelID), info);
this.AddAttributeBasedHandlers();
}
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(nameof(this.subscriptionKey), this.subscriptionKey);
info.AddValue(nameof(this.luisUrl), this.luisUrl);
info.AddValue(nameof(this.modelID), this.modelID);
}
public virtual async Task StartAsync(IDialogContext context)
{
context.Wait(MessageReceived);
@ -149,10 +142,16 @@ namespace Microsoft.Bot.Builder
var message = await item;
var luisRes = await GetLuisResult(this.luisUrl, message.Text);
var intent = luisRes.Intents.FirstOrDefault(i => i.Score == luisRes.Intents.Select(t => t.Score).Max());
if (this.handlerByIntent == null)
{
this.AddAttributeBasedHandlers();
}
IntentHandler handler;
if (intent == null || !this.handlerByIntent.TryGetValue(intent.Intent, out handler))
{
handler = this.handlerByIntent[DefaultIntentHandler];
handler = this.handlerByIntent[string.Empty];
}
if (handler != null)
@ -168,6 +167,13 @@ namespace Microsoft.Bot.Builder
private void AddAttributeBasedHandlers()
{
if (this.handlerByIntent != null)
{
throw new InvalidOperationException();
}
this.handlerByIntent = new Dictionary<string, IntentHandler>();
var methods = from m in this.GetType().GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
let attr = m.GetCustomAttributes(typeof(LuisIntent), true)
where attr.Length > 0
@ -191,7 +197,7 @@ namespace Microsoft.Bot.Builder
foreach (var intent in handler.intents)
{
var key = string.IsNullOrEmpty(intent) ? DefaultIntentHandler : intent;
var key = string.IsNullOrWhiteSpace(intent) ? string.Empty : intent;
this.handlerByIntent.Add(key, intentHandler);
}
}

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

@ -22,18 +22,6 @@ namespace Microsoft.Bot.Sample.PizzaBot
this.MakePizzaForm = makePizzaForm;
}
protected PizzaOrderDialog(SerializationInfo info, StreamingContext context)
: base(info, context)
{
Field.SetNotNullFrom(out this.MakePizzaForm, nameof(MakePizzaForm), info);
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue(nameof(this.MakePizzaForm), MakePizzaForm);
}
[LuisIntent("")]
public async Task None(IDialogContext context, LuisResult result)
{

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

@ -1,176 +1,180 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props" Condition="Exists('..\..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>
</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{A8BA1066-5695-4D71-ABB4-65E5A5E0C3D4}</ProjectGuid>
<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Microsoft.Bot.Sample.SimpleAlarmBot</RootNamespace>
<AssemblyName>Microsoft.Bot.Sample.SimpleAlarmBot</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<UseIISExpress>true</UseIISExpress>
<IISExpressSSLPort />
<IISExpressAnonymousAuthentication />
<IISExpressWindowsAuthentication />
<IISExpressUseClassicPipelineMode />
<UseGlobalApplicationHostFile />
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoWarn>CS1998</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Bot.Connector, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Bot.Connector.1.0.0.0\lib\net45\Microsoft.Bot.Connector.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Bot.Connector.Utilities, Version=0.9.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Bot.Connector.1.0.0.0\lib\net45\Microsoft.Bot.Connector.Utilities.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Microsoft.Diagnostics.Tracing.EventSource, Version=1.1.28.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Diagnostics.Tracing.EventSource.Redist.1.1.28\lib\net46\Microsoft.Diagnostics.Tracing.EventSource.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Rest.ClientRuntime, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Rest.ClientRuntime.1.8.2\lib\net45\Microsoft.Rest.ClientRuntime.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.WindowsAzure.Configuration, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.WindowsAzure.ConfigurationManager.3.2.1\lib\net40\Microsoft.WindowsAzure.Configuration.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=8.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Net" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Net.Http.Formatting, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Net.Http.WebRequest" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Web.DynamicData" />
<Reference Include="System.Web.Entity" />
<Reference Include="System.Web.ApplicationServices" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Drawing" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Http, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Web.Http.WebHost, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Xml" />
<Reference Include="System.Configuration" />
<Reference Include="System.Web.Services" />
<Reference Include="System.EnterpriseServices" />
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Content Include="default.htm" />
<Content Include="Global.asax" />
<Content Include="Web.config">
<SubType>Designer</SubType>
</Content>
</ItemGroup>
<ItemGroup>
<Compile Include="App_Start\WebApiConfig.cs" />
<Compile Include="Controllers\MessagesController.cs" />
<Compile Include="Global.asax.cs">
<DependentUpon>Global.asax</DependentUpon>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SimpleAlarmBot.cs" />
</ItemGroup>
<ItemGroup>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props" Condition="Exists('..\..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>
</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{A8BA1066-5695-4D71-ABB4-65E5A5E0C3D4}</ProjectGuid>
<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Microsoft.Bot.Sample.SimpleAlarmBot</RootNamespace>
<AssemblyName>Microsoft.Bot.Sample.SimpleAlarmBot</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<UseIISExpress>true</UseIISExpress>
<IISExpressSSLPort />
<IISExpressAnonymousAuthentication />
<IISExpressWindowsAuthentication />
<IISExpressUseClassicPipelineMode />
<UseGlobalApplicationHostFile />
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoWarn>CS1998</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Chronic, Version=0.2.1.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\Chronic.0.3.1\lib\net40\Chronic.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Bot.Connector, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Bot.Connector.1.0.0.0\lib\net45\Microsoft.Bot.Connector.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Bot.Connector.Utilities, Version=0.9.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Bot.Connector.1.0.0.0\lib\net45\Microsoft.Bot.Connector.Utilities.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Microsoft.Diagnostics.Tracing.EventSource, Version=1.1.28.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Diagnostics.Tracing.EventSource.Redist.1.1.28\lib\net46\Microsoft.Diagnostics.Tracing.EventSource.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Rest.ClientRuntime, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Rest.ClientRuntime.1.8.2\lib\net45\Microsoft.Rest.ClientRuntime.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.WindowsAzure.Configuration, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.WindowsAzure.ConfigurationManager.3.2.1\lib\net40\Microsoft.WindowsAzure.Configuration.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=8.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Net" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Net.Http.Formatting, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Net.Http.WebRequest" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Web.DynamicData" />
<Reference Include="System.Web.Entity" />
<Reference Include="System.Web.ApplicationServices" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Drawing" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Http, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Web.Http.WebHost, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Xml" />
<Reference Include="System.Configuration" />
<Reference Include="System.Web.Services" />
<Reference Include="System.EnterpriseServices" />
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Content Include="default.htm" />
<Content Include="Global.asax" />
<Content Include="Web.config">
<SubType>Designer</SubType>
</Content>
</ItemGroup>
<ItemGroup>
<Compile Include="App_Start\WebApiConfig.cs" />
<Compile Include="Controllers\MessagesController.cs" />
<Compile Include="Global.asax.cs">
<DependentUpon>Global.asax</DependentUpon>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SimpleAlarmBot.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="packages.config">
<SubType>Designer</SubType>
</Content>
<None Include="Web.Debug.config">
<DependentUpon>Web.config</DependentUpon>
</None>
<None Include="Web.Release.config">
<DependentUpon>Web.config</DependentUpon>
<SubType>Designer</SubType>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Library\Microsoft.Bot.Builder.csproj">
<Project>{cdfec7d6-847e-4c13-956b-0a960ae3eb60}</Project>
<Name>Microsoft.Bot.Builder</Name>
</ProjectReference>
</ItemGroup>
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />
<ProjectExtensions>
<VisualStudio>
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
<WebProjectProperties>
<UseIIS>True</UseIIS>
<AutoAssignPort>True</AutoAssignPort>
<DevelopmentServerPort>3978</DevelopmentServerPort>
<DevelopmentServerVPath>/</DevelopmentServerVPath>
<IISUrl>http://localhost:3979/</IISUrl>
<NTLMAuthentication>False</NTLMAuthentication>
<UseCustomServer>False</UseCustomServer>
<CustomServerUrl>
</CustomServerUrl>
<SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
</WebProjectProperties>
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props'))" />
</Target>
<None Include="Web.Debug.config">
<DependentUpon>Web.config</DependentUpon>
</None>
<None Include="Web.Release.config">
<DependentUpon>Web.config</DependentUpon>
<SubType>Designer</SubType>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Library\Microsoft.Bot.Builder.csproj">
<Project>{cdfec7d6-847e-4c13-956b-0a960ae3eb60}</Project>
<Name>Microsoft.Bot.Builder</Name>
</ProjectReference>
</ItemGroup>
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />
<ProjectExtensions>
<VisualStudio>
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
<WebProjectProperties>
<UseIIS>True</UseIIS>
<AutoAssignPort>True</AutoAssignPort>
<DevelopmentServerPort>3978</DevelopmentServerPort>
<DevelopmentServerVPath>/</DevelopmentServerVPath>
<IISUrl>http://localhost:3979/</IISUrl>
<NTLMAuthentication>False</NTLMAuthentication>
<UseCustomServer>False</UseCustomServer>
<CustomServerUrl>
</CustomServerUrl>
<SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
</WebProjectProperties>
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props'))" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
-->
</Project>

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

@ -1,97 +1,192 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Bot.Sample.SimpleAlarmBot
{
[LuisModel("https://api.projectoxford.ai/luis/v1/application?id=c413b2ef-382c-45bd-8ff0-f76d60e2a821&subscription-key=fe054e042fd14754a83f0a205f6552a5&q=")]
[Serializable]
public class SimpleAlarmBot : LuisDialog
public class SimpleAlarmBot : LuisDialog, ISerializable
{
public SimpleAlarmBot()
private readonly List<Alarm> alarms = new List<Alarm>();
public const string DefaultAlarmWhat = "default";
public bool TryFindAlarm(LuisResult result, out Alarm alarm)
{
alarm = null;
string what;
EntityRecommendation title;
if (result.TryFindEntity(Entity_Alarm_Title, out title))
{
what = title.Entity;
}
else
{
what = DefaultAlarmWhat;
}
alarm = this.alarms.FirstOrDefault(a => a.What == what);
return alarm != null;
}
protected SimpleAlarmBot(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
private const string Entity_Alarm_Title = "builtin.alarm.title";
private const string Entity_Alarm_Start_Time = "builtin.alarm.start_time";
private const string Entity_Alarm_Start_Date = "builtin.alarm.start_date";
/// <summary>
/// default intent handler because it is marked by [LuisIntent("")]
/// </summary>
/// <param name="session"></param>
/// <param name="result"></param>
/// <returns></returns>
[LuisIntent("")]
public async Task None(IDialogContext context, LuisResult result)
{
await context.PostAsync("I'm sorry. I didn't understand you.");
context.Wait(MessageReceived);
}
[LuisIntent("builtin.intent.alarm.alarm_other")]
public async Task AlarmOther(IDialogContext context, LuisResult result)
{
string reply = "alarm changed!";
await context.PostAsync(reply);
string message = $"Sorry I did not understand: " + string.Join(", ", result.Intents.Select(i => i.Intent));
await context.PostAsync(message);
context.Wait(MessageReceived);
}
[LuisIntent("builtin.intent.alarm.delete_alarm")]
public async Task DeleteAlarm(IDialogContext context, LuisResult result)
{
string reply = "alarm deleted!";
await context.PostAsync(reply);
Alarm alarm;
if (TryFindAlarm(result, out alarm))
{
this.alarms.Remove(alarm);
await context.PostAsync($"alarm {alarm} deleted");
}
else
{
await context.PostAsync("did not find alarm");
}
context.Wait(MessageReceived);
}
[LuisIntent("builtin.intent.alarm.find_alarm")]
public async Task FindAlarm(IDialogContext context, LuisResult result)
{
string reply = "alarm found!";
await context.PostAsync(reply);
Alarm alarm;
if (TryFindAlarm(result, out alarm))
{
await context.PostAsync($"found alarm {alarm}");
}
else
{
await context.PostAsync("did not find alarm");
}
context.Wait(MessageReceived);
}
[LuisIntent("builtin.intent.alarm.set_alarm")]
public async Task SetAlarm(IDialogContext context, LuisResult result)
{
string reply = "alarm created!";
await context.PostAsync(reply);
EntityRecommendation title;
if (! result.TryFindEntity(Entity_Alarm_Title, out title))
{
title = new EntityRecommendation(Entity_Alarm_Title) { Entity = DefaultAlarmWhat };
}
EntityRecommendation date;
if (! result.TryFindEntity(Entity_Alarm_Start_Date, out date))
{
date = new EntityRecommendation() { Entity = string.Empty };
}
EntityRecommendation time;
if (!result.TryFindEntity(Entity_Alarm_Start_Time, out time))
{
time = new EntityRecommendation() { Entity = string.Empty };
}
var parser = new Chronic.Parser();
var span = parser.Parse(date.Entity + " " + time.Entity);
if (span != null)
{
var when = span.Start ?? span.End;
var alarm = new Alarm() { What = title.Entity, When = when.Value };
this.alarms.Add(alarm);
string reply = $"alarm {alarm} created";
await context.PostAsync(reply);
}
else
{
await context.PostAsync("could not find time for alarm");
}
context.Wait(MessageReceived);
}
[LuisIntent("builtin.intent.alarm.snooze")]
public async Task AlarmSnooze(IDialogContext context, LuisResult result)
{
string reply = "alarm snoozed!";
await context.PostAsync(reply);
Alarm alarm;
if (TryFindAlarm(result, out alarm))
{
alarm.When = alarm.When.Add(TimeSpan.FromMinutes(7));
await context.PostAsync($"alarm {alarm} snoozed!");
}
else
{
await context.PostAsync("did not find alarm");
}
context.Wait(MessageReceived);
}
[LuisIntent("builtin.intent.alarm.time_remaining")]
public async Task TimeRemaining(IDialogContext context, LuisResult result)
{
string reply = "There are 5 minutes remaining.";
await context.PostAsync(reply);
Alarm alarm;
if (TryFindAlarm(result, out alarm))
{
var now = DateTime.UtcNow;
if (alarm.When > now)
{
var remaining = alarm.When.Subtract(DateTime.UtcNow);
await context.PostAsync($"There is {remaining} remaining for alarm {alarm}.");
}
else
{
await context.PostAsync($"The alarm {alarm} expired already.");
}
}
else
{
await context.PostAsync("did not find alarm");
}
context.Wait(MessageReceived);
}
private Alarm turnOff;
[LuisIntent("builtin.intent.alarm.turn_off_alarm")]
public async Task TurnOffAlarm(IDialogContext context, LuisResult result)
{
Prompts.Confirm(context, AfterConfirming_TurnOffAlarm, "Are you sure?");
if (TryFindAlarm(result, out this.turnOff))
{
Prompts.Confirm(context, AfterConfirming_TurnOffAlarm, "Are you sure?");
}
else
{
await context.PostAsync("did not find alarm");
}
}
public async Task AfterConfirming_TurnOffAlarm(IDialogContext context, IAwaitable<bool> confirmation)
{
if (await confirmation)
{
await context.PostAsync("Ok, alarm disabled.");
this.alarms.Remove(this.turnOff);
await context.PostAsync($"Ok, alarm {this.turnOff} disabled.");
}
else
{
@ -100,5 +195,58 @@ namespace Microsoft.Bot.Sample.SimpleAlarmBot
context.Wait(MessageReceived);
}
[LuisIntent("builtin.intent.alarm.alarm_other")]
public async Task AlarmOther(IDialogContext context, LuisResult result)
{
await context.PostAsync("what ?");
context.Wait(MessageReceived);
}
public SimpleAlarmBot()
{
}
protected SimpleAlarmBot(SerializationInfo info, StreamingContext context)
{
var json = info.GetValue<string>(nameof(this.alarms));
this.alarms = JArray.Parse(json).ToObject<List<Alarm>>();
this.turnOff = info.GetValue<Alarm>(nameof(this.turnOff));
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(nameof(this.alarms), JArray.FromObject(this.alarms).ToString());
info.AddValue(nameof(this.turnOff), turnOff);
}
[Serializable]
public sealed class Alarm : IEquatable<Alarm>
{
public DateTime When { get; set; }
public string What { get; set; }
public override string ToString()
{
return $"[{this.What} at {this.When}]";
}
public bool Equals(Alarm other)
{
return other != null
&& this.When == other.When
&& this.What == other.What;
}
public override bool Equals(object other)
{
return Equals(other as Alarm);
}
public override int GetHashCode()
{
return this.What.GetHashCode();
}
}
}
}

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

@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Chronic" version="0.3.1" targetFramework="net46" />
<package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net46" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net46" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net46" />