Move DialogStateManager/Memory/Scope into dialogs dialogContext.State (#3570)

* clean up caps constant names

* * Add DialogContext.State as DialogStateManager/Remove GetState() extension method
* Move DialogStateManager/ScopesPathResolvers into Dialogs assembly
* Make all IMemory implementations evaluate ExpressionProperties
* Fix layering between expressions and dialogs via MemoryFactory.Create() and internal ducktyping memory
* Move ComponentRegistration into Builder assembly
* Fix path CAPS names in paths: NOTE I have marked old values as [Obsolete]  We should remove these obsolete properties right before we release or we will get broken builds for every PR because of backward compat issues.
This commit is contained in:
Tom Laird-McConnell 2020-03-18 12:36:03 -07:00 коммит произвёл GitHub
Родитель f5111031da
Коммит 43fd9e6050
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
117 изменённых файлов: 821 добавлений и 786 удалений

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

@ -311,7 +311,7 @@ namespace AdaptiveExpressions
/// </param>
/// <returns>Computed value and an error string. If the string is non-null, then there was an evaluation error.</returns>
public (object value, string error) TryEvaluate(object state)
=> this.TryEvaluate<object>(state);
=> this.TryEvaluate<object>(MemoryFactory.Create(state));
/// <summary>
/// Evaluate the expression.
@ -334,7 +334,7 @@ namespace AdaptiveExpressions
/// </param>
/// <returns>Computed value and an error string. If the string is non-null, then there was an evaluation error.</returns>
public (T value, string error) TryEvaluate<T>(object state)
=> this.TryEvaluate<T>(SimpleObjectMemory.Wrap(state));
=> this.TryEvaluate<T>(MemoryFactory.Create(state));
/// <summary>
/// Evaluate the expression.

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

@ -16,6 +16,7 @@ using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using AdaptiveExpressions.Memory;
using AdaptiveExpressions.Properties;
using Microsoft.Recognizers.Text.DataTypes.TimexExpression;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
@ -1089,7 +1090,7 @@ namespace AdaptiveExpressions
return (null, err);
}
return WrapGetValue(new SimpleObjectMemory(newScope), path);
return WrapGetValue(MemoryFactory.Create(newScope), path);
}
}
@ -1107,7 +1108,7 @@ namespace AdaptiveExpressions
(property, error) = children[1].TryEvaluate(state);
if (error == null)
{
(value, error) = WrapGetValue(new SimpleObjectMemory(instance), (string)property);
(value, error) = WrapGetValue(MemoryFactory.Create(instance), (string)property);
}
}
@ -1471,7 +1472,7 @@ namespace AdaptiveExpressions
};
// the local iterator is pushed as one memory layer in the memory stack
stackedMemory.Push(SimpleObjectMemory.Wrap(local));
stackedMemory.Push(new SimpleObjectMemory(local));
(var r, var e) = expression.Children[2].TryEvaluate(stackedMemory);
stackedMemory.Pop();
@ -1530,7 +1531,7 @@ namespace AdaptiveExpressions
};
// the local iterator is pushed as one memory layer in the memory stack
stackedMemory.Push(SimpleObjectMemory.Wrap(local));
stackedMemory.Push(new SimpleObjectMemory(local));
var (r, _) = expression.Children[2].TryEvaluate<bool>(stackedMemory);
stackedMemory.Pop();

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

@ -1,18 +0,0 @@
// Licensed under the MIT License.
// Copyright (c) Microsoft Corporation. All rights reserved.
using System.Collections.Generic;
namespace AdaptiveExpressions
{
/// <summary>
/// Interface for adding custom functions to the expression parser.
/// </summary>
public interface IComponentExpressionFunctions
{
/// <summary>
/// Return collection of ExpressionEvaluators.
/// </summary>
/// <returns>enumeration of custom ExpressionEvaluators.</returns>
public IEnumerable<ExpressionEvaluator> GetExpressionEvaluators();
}
}

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

@ -0,0 +1,34 @@
using System;
using System.Collections.Concurrent;
using System.Reflection;
namespace AdaptiveExpressions.Memory
{
public static class MemoryFactory
{
/// <summary>
/// Get an appropriate IMemory implementation for an object.
/// </summary>
/// <param name="obj">Common object.</param>
/// <returns>IMemory.</returns>
public static IMemory Create(object obj)
{
if (obj != null)
{
if (obj is IMemory)
{
return (IMemory)obj;
}
// if this is ducktype of IMemory
var memory = ReflectionMemory.Create(obj);
if (memory != null)
{
return memory;
}
}
return new SimpleObjectMemory(obj);
}
}
}

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

@ -0,0 +1,102 @@
using System;
using System.Collections.Concurrent;
using System.Reflection;
using AdaptiveExpressions.Properties;
namespace AdaptiveExpressions.Memory
{
/// <summary>
/// Internal class to duck type IMemory interface via reflection.
/// </summary>
internal class ReflectionMemory : IMemory
{
// cache of type => either Methods or null
private static ConcurrentDictionary<Type, Methods> methodsCache = new ConcurrentDictionary<Type, Methods>();
private object obj;
private Methods methods;
private ReflectionMemory(object obj, Methods methods)
{
this.obj = obj;
this.methods = methods;
}
public void SetValue(string path, object value)
{
this.methods.SetValue.Invoke(obj, new object[] { value });
}
public bool TryGetValue(string path, out object value)
{
value = null;
var args = new object[] { path, null };
var result = (bool)this.methods.TryGetValue.Invoke(obj, args);
if (result)
{
value = args[1];
if (value is IExpressionProperty ep)
{
value = ep.GetObject(obj);
}
}
return result;
}
public string Version()
{
return (string)this.methods.Version.Invoke(obj, Array.Empty<object>());
}
internal static ReflectionMemory Create(object obj)
{
if (methodsCache.TryGetValue(obj.GetType(), out Methods methods))
{
if (methods != null)
{
return new ReflectionMemory(obj, methods);
}
// cached negative result
return null;
}
// if we can Duck type to IMemory contract
var version = obj.GetType().GetMethod("Version", BindingFlags.Public | BindingFlags.Instance);
if (version != null)
{
var setValue = obj.GetType().GetMethod("SetValue", BindingFlags.Public | BindingFlags.Instance);
if (setValue != null)
{
var tryGetValue = obj.GetType().GetMethod("TryGetValue", new Type[] { typeof(string), typeof(object).MakeByRefType() });
if (tryGetValue != null)
{
methods = new Methods()
{
Version = version,
TryGetValue = tryGetValue,
SetValue = setValue
};
methodsCache.TryAdd(obj.GetType(), methods);
return new ReflectionMemory(obj, methods);
}
}
}
// remember this isn't IMemory object
methodsCache.TryAdd(obj.GetType(), null);
return null;
}
private class Methods
{
public MethodInfo TryGetValue { get; set; }
public MethodInfo SetValue { get; set; }
public MethodInfo Version { get; set; }
}
}
}

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

@ -3,6 +3,8 @@
using System;
using System.Linq;
using System.Reflection;
using AdaptiveExpressions.Properties;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
@ -26,21 +28,6 @@ namespace AdaptiveExpressions.Memory
this.memory = memory;
}
/// <summary>
/// Transfer an common object to simple memory.
/// </summary>
/// <param name="obj">Common object.</param>
/// <returns>Simple memory instance.</returns>
public static IMemory Wrap(object obj)
{
if (obj is IMemory)
{
return (IMemory)obj;
}
return new SimpleObjectMemory(obj);
}
/// <summary>
/// Try get value from a given path.
/// </summary>
@ -57,7 +44,7 @@ namespace AdaptiveExpressions.Memory
var parts = path.Split(".[]".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Trim('\'', '"'))
.ToArray();
.ToArray();
var curScope = memory;
@ -83,6 +70,11 @@ namespace AdaptiveExpressions.Memory
curScope = value;
}
if (value is IExpressionProperty ep)
{
value = ep.GetObject(memory);
}
return true;
}

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

@ -3,6 +3,7 @@
using System;
using System.Collections.Generic;
using AdaptiveExpressions.Properties;
namespace AdaptiveExpressions.Memory
{
@ -48,6 +49,12 @@ namespace AdaptiveExpressions.Memory
if (memory.TryGetValue(path, out var result) && result != null)
{
value = result;
if (value is IExpressionProperty ep)
{
value = ep.GetObject(memory);
}
return true;
}
}

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

@ -39,12 +39,10 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Testing.Actions
public async override Task<DialogTurnResult> BeginDialogAsync(DialogContext dc, object options = null, CancellationToken cancellationToken = default)
{
var dcState = dc.GetState();
var (result, error) = Condition.TryEvaluate(dcState);
var (result, error) = Condition.TryEvaluate(dc.State);
if ((bool)result == false)
{
var desc = Description?.GetValue(dcState) ?? Condition.ToString();
var desc = Description?.GetValue(dc.State) ?? Condition.ToString();
throw new Exception(desc);
}

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

@ -78,8 +78,6 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
/// <returns>True if there were any changes to apply. </returns>
public async Task<bool> ApplyChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var dcState = this.GetState();
// Retrieve queued changes from turn context
var changes = this.Changes ?? new List<ActionChangeList>();
@ -96,7 +94,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
{
foreach (var keyValue in change.Turn)
{
dcState.SetValue($"turn.{keyValue.Key}", keyValue.Value);
this.State.SetValue($"turn.{keyValue.Key}", keyValue.Value);
}
}

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

@ -147,8 +147,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
}
// Increment our offset into the actions and being the next action
var dcState = dc.GetState();
var nextOffset = dcState.GetIntValue(OFFSETKEY, 0) + 1;
var nextOffset = dc.State.GetIntValue(OFFSETKEY, 0) + 1;
if (nextOffset < this.Actions.Count)
{
return await this.BeginActionAsync(dc, nextOffset, cancellationToken: cancellationToken).ConfigureAwait(false);
@ -172,9 +171,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
protected virtual async Task<DialogTurnResult> BeginActionAsync(DialogContext dc, int offset, CancellationToken cancellationToken = default)
{
// get the action for the offset
var dcState = dc.GetState();
dcState.SetValue(OFFSETKEY, offset);
dc.State.SetValue(OFFSETKEY, offset);
var action = this.Actions[offset];
var actionName = action.GetType().Name.ToString();

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

@ -78,27 +78,23 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
return this.Dialog.Value;
}
var dcState = dc.GetState();
// NOTE: we call TryEvaluate instead of TryGetValue because we want the result of the expression as a string so we can
// look up the string using external FindDialog().
var se = new StringExpression($"={this.Dialog.ExpressionText}");
var dialogId = se.GetValue(dcState);
var dialogId = se.GetValue(dc.State);
return dc.FindDialog(dialogId ?? throw new Exception($"{this.Dialog.ToString()} not found."));
}
protected object BindOptions(DialogContext dc, object options)
{
var dcState = dc.GetState();
// binding options are static definition of options with overlay of passed in options);
var bindingOptions = (JObject)ObjectPath.Merge(this.Options.GetValue(dcState), options ?? new JObject());
var bindingOptions = (JObject)ObjectPath.Merge(this.Options.GetValue(dc.State), options ?? new JObject());
var boundOptions = new JObject();
foreach (var binding in bindingOptions)
{
// evalute the value
var (value, error) = new ValueExpression(binding.Value).TryGetValue(dcState);
var (value, error) = new ValueExpression(binding.Value).TryGetValue(dc.State);
if (error != null)
{

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

@ -53,9 +53,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
@ -66,7 +64,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
var boundOptions = BindOptions(dc, options);
// set the activity processed state (default is true)
dcState.SetValue(TurnPath.ACTIVITYPROCESSED, this.ActivityProcessed.GetValue(dcState));
dc.State.SetValue(TurnPath.ActivityProcessed, this.ActivityProcessed.GetValue(dc.State));
// start dialog with bound options passed in as the options
return await dc.BeginDialogAsync(dialog.Id, options: boundOptions, cancellationToken: cancellationToken).ConfigureAwait(false);
@ -74,11 +72,9 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
public override async Task<DialogTurnResult> ResumeDialogAsync(DialogContext dc, DialogReason reason, object result = null, CancellationToken cancellationToken = default(CancellationToken))
{
var dcState = dc.GetState();
if (this.ResultProperty != null)
{
dcState.SetValue(this.ResultProperty.GetValue(dcState), result);
dc.State.SetValue(this.ResultProperty.GetValue(dc.State), result);
}
// By default just end the current dialog and return result to parent.

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

@ -42,9 +42,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}

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

@ -62,20 +62,18 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
if (dc.Parent == null)
{
return await dc.CancelAllDialogsAsync(true, EventName?.GetValue(dcState), this.EventValue?.GetValue(dcState), cancellationToken).ConfigureAwait(false);
return await dc.CancelAllDialogsAsync(true, EventName?.GetValue(dc.State), this.EventValue?.GetValue(dc.State), cancellationToken).ConfigureAwait(false);
}
else
{
var turnResult = await dc.Parent.CancelAllDialogsAsync(true, EventName?.GetValue(dcState), this.EventValue?.GetValue(dcState), cancellationToken).ConfigureAwait(false);
var turnResult = await dc.Parent.CancelAllDialogsAsync(true, EventName?.GetValue(dc.State), this.EventValue?.GetValue(dc.State), cancellationToken).ConfigureAwait(false);
turnResult.ParentEnded = true;
return turnResult;
}

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

@ -42,9 +42,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}

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

@ -42,9 +42,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}

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

@ -42,9 +42,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}

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

@ -50,14 +50,12 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
var (result, error) = this.ActivityId.TryGetValue(dcState);
var (result, error) = this.ActivityId.TryGetValue(dc.State);
if (error != null)
{
throw new ArgumentException(error);

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

@ -58,9 +58,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
@ -69,7 +67,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
{
foreach (var property in this.Properties)
{
dcState.RemoveValue(property.GetValue(dcState));
dc.State.RemoveValue(property.GetValue(dc.State));
}
}

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

@ -66,14 +66,12 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
dcState.RemoveValue(Property.GetValue(dcState));
dc.State.RemoveValue(Property.GetValue(dc.State));
return await dc.EndDialogAsync();
}
}

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

@ -69,9 +69,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
public override async Task<DialogTurnResult> BeginDialogAsync(DialogContext dc, object options = null, CancellationToken cancellationToken = default(CancellationToken))
{
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
@ -87,7 +85,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
var changes = new ActionChangeList()
{
ChangeType = ChangeType.GetValue(dcState),
ChangeType = ChangeType.GetValue(dc.State),
Actions = planActions.ToList()
};

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

@ -152,9 +152,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState))
if (this.Disabled != null && this.Disabled.GetValue(dc.State))
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
@ -164,12 +162,12 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new Exception($"EditArray: \"{ChangeType}\" operation couldn't be performed because the arrayProperty wasn't specified.");
}
var array = dcState.GetValue<JArray>(this.ItemsProperty.GetValue(dcState), () => new JArray());
var array = dc.State.GetValue<JArray>(this.ItemsProperty.GetValue(dc.State), () => new JArray());
object item = null;
object result = null;
switch (ChangeType.GetValue(dcState))
switch (ChangeType.GetValue(dc.State))
{
case ArrayChangeType.Pop:
item = array[array.Count - 1];
@ -178,7 +176,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
break;
case ArrayChangeType.Push:
EnsureValue();
var (itemResult, error) = this.Value.TryGetValue(dcState);
var (itemResult, error) = this.Value.TryGetValue(dc.State);
if (error == null && itemResult != null)
{
array.Add(itemResult);
@ -197,7 +195,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
break;
case ArrayChangeType.Remove:
EnsureValue();
(itemResult, error) = this.Value.TryGetValue(dcState);
(itemResult, error) = this.Value.TryGetValue(dc.State);
if (error == null && itemResult != null)
{
result = false;
@ -219,11 +217,11 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
break;
}
dcState.SetValue(this.ItemsProperty.GetValue(dcState), array);
dc.State.SetValue(this.ItemsProperty.GetValue(dc.State), array);
if (ResultProperty != null)
{
dcState.SetValue(this.ResultProperty.GetValue(dcState), result);
dc.State.SetValue(this.ResultProperty.GetValue(dc.State), result);
}
return await dc.EndDialogAsync(result);

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

@ -83,21 +83,19 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
bool handled;
var eventName = EventName?.GetValue(dcState);
var bubbleEvent = BubbleEvent.GetValue(dcState);
var eventName = EventName?.GetValue(dc.State);
var bubbleEvent = BubbleEvent.GetValue(dc.State);
object value = null;
if (EventValue != null)
{
value = this.EventValue.GetValue(dcState);
value = this.EventValue.GetValue(dc.State);
}
if (dc.Parent != null)

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

@ -58,16 +58,14 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
if (this.Value != null)
{
var (result, error) = this.Value.TryGetValue(dcState);
var (result, error) = this.Value.TryGetValue(dc.State);
return await EndParentDialogAsync(dc, result, cancellationToken).ConfigureAwait(false);
}

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

@ -45,9 +45,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return dc.EndDialogAsync(cancellationToken: cancellationToken);
}

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

@ -57,14 +57,12 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
dcState.SetValue(INDEX, -1);
dc.State.SetValue(INDEX, -1);
return await this.NextItemAsync(dc, cancellationToken).ConfigureAwait(false);
}
@ -86,16 +84,15 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
protected virtual async Task<DialogTurnResult> NextItemAsync(DialogContext dc, CancellationToken cancellationToken = default)
{
// Get list information
var dcState = dc.GetState();
var list = dcState.GetValue<JArray>(this.ItemsProperty.GetValue(dcState));
var index = dcState.GetIntValue(INDEX);
var list = dc.State.GetValue<JArray>(this.ItemsProperty.GetValue(dc.State));
var index = dc.State.GetIntValue(INDEX);
// Next item
if (++index < list.Count)
{
// Persist index and value
dcState.SetValue(VALUE, list[index]);
dcState.SetValue(INDEX, index);
dc.State.SetValue(VALUE, list[index]);
dc.State.SetValue(INDEX, index);
// Start loop
return await this.BeginActionAsync(dc, 0, cancellationToken).ConfigureAwait(false);

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

@ -57,9 +57,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
@ -89,20 +87,19 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
private async Task<DialogTurnResult> NextPageAsync(DialogContext dc, CancellationToken cancellationToken)
{
var dcState = dc.GetState();
int pageIndex = dcState.GetIntValue(FOREACHPAGEINDEX, 0);
int pageSize = this.PageSize.GetValue(dcState);
int pageIndex = dc.State.GetIntValue(FOREACHPAGEINDEX, 0);
int pageSize = this.PageSize.GetValue(dc.State);
int itemOffset = pageSize * pageIndex;
var itemsProperty = this.ItemsProperty.GetValue(dcState);
if (dcState.TryGetValue<object>(itemsProperty, out object items))
var itemsProperty = this.ItemsProperty.GetValue(dc.State);
if (dc.State.TryGetValue<object>(itemsProperty, out object items))
{
var page = this.GetPage(items, itemOffset, pageSize);
if (page.Any())
{
dcState.SetValue(FOREACHPAGE, page);
dcState.SetValue(FOREACHPAGEINDEX, ++pageIndex);
dc.State.SetValue(FOREACHPAGE, page);
dc.State.SetValue(FOREACHPAGEINDEX, ++pageIndex);
return await this.BeginActionAsync(dc, 0, cancellationToken).ConfigureAwait(false);
}
}

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

@ -62,9 +62,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
@ -78,7 +76,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
string id = dc.Context.Activity.Id;
if (this.ActivityId != null)
{
var (value, valueError) = this.ActivityId.TryGetValue(dcState);
var (value, valueError) = this.ActivityId.TryGetValue(dc.State);
if (valueError != null)
{
throw new Exception($"Expression evaluation resulted in an error. Expression: {this.ActivityId}. Error: {valueError}");
@ -89,7 +87,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
var result = await bfAdapter.GetActivityMembersAsync(dc.Context, id, cancellationToken).ConfigureAwait(false);
dcState.SetValue(this.Property.GetValue(dcState), result);
dc.State.SetValue(this.Property.GetValue(dc.State), result);
return await dc.EndDialogAsync(result, cancellationToken: cancellationToken).ConfigureAwait(false);
}

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

@ -53,9 +53,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
@ -70,7 +68,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
if (this.Property != null)
{
dcState.SetValue(this.Property.GetValue(dcState), result);
dc.State.SetValue(this.Property.GetValue(dc.State), result);
}
return await dc.EndDialogAsync(result, cancellationToken: cancellationToken).ConfigureAwait(false);

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

@ -49,9 +49,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
@ -60,7 +58,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
var actionScopeResult = new ActionScopeResult()
{
ActionScopeCommand = ActionScopeCommands.GotoAction,
ActionId = this.ActionId?.GetValue(dcState) ?? throw new ArgumentNullException(nameof(ActionId))
ActionId = this.ActionId?.GetValue(dc.State) ?? throw new ArgumentNullException(nameof(ActionId))
};
return await dc.EndDialogAsync(result: actionScopeResult, cancellationToken: cancellationToken).ConfigureAwait(false);

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

@ -184,9 +184,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
@ -199,7 +197,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
JToken instanceBody = null;
if (this.Body != null)
{
var (body, err) = this.Body.TryGetValue(dcState);
var (body, err) = this.Body.TryGetValue(dc.State);
if (err != null)
{
throw new ArgumentException(err);
@ -208,9 +206,9 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
instanceBody = (JToken)JToken.FromObject(body).DeepClone();
}
var instanceHeaders = Headers == null ? null : Headers.ToDictionary(kv => kv.Key, kv => kv.Value.GetValue(dcState));
var instanceHeaders = Headers == null ? null : Headers.ToDictionary(kv => kv.Key, kv => kv.Value.GetValue(dc.State));
var (instanceUrl, instanceUrlError) = this.Url.TryGetValue(dcState);
var (instanceUrl, instanceUrlError) = this.Url.TryGetValue(dc.State);
if (instanceUrlError != null)
{
throw new ArgumentException(instanceUrlError);
@ -238,7 +236,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
traceInfo.request.url = instanceUrl;
HttpResponseMessage response = null;
string contentType = ContentType?.GetValue(dcState) ?? "application/json";
string contentType = ContentType?.GetValue(dc.State) ?? "application/json";
switch (this.Method)
{
@ -306,7 +304,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
object content = (object)await response.Content.ReadAsStringAsync();
switch (this.ResponseType.GetValue(dcState))
switch (this.ResponseType.GetValue(dc.State))
{
case ResponseTypes.Activity:
var activity = JsonConvert.DeserializeObject<Activity>((string)content);
@ -346,7 +344,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
if (this.ResultProperty != null)
{
dcState.SetValue(this.ResultProperty.GetValue(dcState), requestResult);
dc.State.SetValue(this.ResultProperty.GetValue(dc.State), requestResult);
}
// return the actionResult as the result of this operation
@ -360,8 +358,6 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
private async Task ReplaceJTokenRecursively(DialogContext dc, JToken token)
{
var dcState = dc.GetState();
switch (token.Type)
{
case JTokenType.Object:
@ -391,7 +387,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
var text = token.ToString();
// if it is a "{bindingpath}" then run through expression parser and treat as a value
var (result, error) = new ValueExpression(text).TryGetValue(dcState);
var (result, error) = new ValueExpression(text).TryGetValue(dc.State);
if (error == null)
{
token.Replace(JToken.FromObject(result));

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

@ -99,14 +99,12 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
var (conditionResult, error) = this.Condition.TryGetValue(dcState);
var (conditionResult, error) = this.Condition.TryGetValue(dc.State);
if (error == null && conditionResult == true && TrueScope.Actions.Any())
{
// replace dialog with If True Action Scope

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

@ -75,14 +75,12 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
var text = await Text.BindToData(dc.Context, dcState).ConfigureAwait(false);
var text = await Text.BindToData(dc.Context, dc.State).ConfigureAwait(false);
var properties = new Dictionary<string, string>()
{
@ -93,9 +91,9 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
System.Diagnostics.Trace.TraceInformation(text);
if (this.TraceActivity.GetValue(dcState))
if (this.TraceActivity.GetValue(dc.State))
{
var traceActivity = Activity.CreateTraceActivity(name: "Log", valueType: "Text", value: text, label: this.Label?.GetValue(dcState) ?? dc.Parent?.ActiveDialog?.Id);
var traceActivity = Activity.CreateTraceActivity(name: "Log", valueType: "Text", value: text, label: this.Label?.GetValue(dc.State) ?? dc.Parent?.ActiveDialog?.Id);
await dc.Context.SendActivityAsync(traceActivity, cancellationToken).ConfigureAwait(false);
}

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

@ -45,9 +45,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
@ -57,17 +55,17 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
var targetDialogId = dc.Parent.ActiveDialog.Id;
var repeatedIds = dcState.GetValue<List<string>>(TurnPath.REPEATEDIDS, () => new List<string>());
var repeatedIds = dc.State.GetValue<List<string>>(TurnPath.RepeatedIds, () => new List<string>());
if (repeatedIds.Contains(targetDialogId))
{
throw new ArgumentException($"Recursive loop detected, {targetDialogId} cannot be repeated twice in one turn.");
}
repeatedIds.Add(targetDialogId);
dcState.SetValue(TurnPath.REPEATEDIDS, repeatedIds);
dc.State.SetValue(TurnPath.RepeatedIds, repeatedIds);
// set the activity processed state (default is true)
dcState.SetValue(TurnPath.ACTIVITYPROCESSED, this.ActivityProcessed.GetValue(dcState));
dc.State.SetValue(TurnPath.ActivityProcessed, this.ActivityProcessed.GetValue(dc.State));
var turnResult = await dc.Parent.ReplaceDialogAsync(dc.Parent.ActiveDialog.Id, boundOptions, cancellationToken).ConfigureAwait(false);
turnResult.ParentEnded = true;

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

@ -44,9 +44,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
@ -57,7 +55,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
var boundOptions = BindOptions(dc, options);
// set the activity processed state (default is true)
dcState.SetValue(TurnPath.ACTIVITYPROCESSED, this.ActivityProcessed.GetValue(dcState));
dc.State.SetValue(TurnPath.ActivityProcessed, this.ActivityProcessed.GetValue(dc.State));
// replace dialog with bound options passed in as the options
return await dc.ReplaceDialogAsync(dialog.Id, options: boundOptions, cancellationToken: cancellationToken).ConfigureAwait(false);

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

@ -63,14 +63,12 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
var activity = await Activity.BindToData(dc.Context, dcState).ConfigureAwait(false);
var activity = await Activity.BindToData(dc.Context, dc.State).ConfigureAwait(false);
var properties = new Dictionary<string, string>()
{
{ "template", JsonConvert.SerializeObject(Activity) },

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

@ -54,22 +54,20 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
foreach (var propValue in this.Assignments)
{
var (value, valueError) = propValue.Value.TryGetValue(dcState);
var (value, valueError) = propValue.Value.TryGetValue(dc.State);
if (valueError != null)
{
throw new Exception($"Expression evaluation resulted in an error. Expression: {propValue.Value.ToString()}. Error: {valueError}");
}
dcState.SetValue(propValue.Property.GetValue(dcState), value);
dc.State.SetValue(propValue.Property.GetValue(dc.State), value);
}
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);

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

@ -62,8 +62,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState))
if (this.Disabled != null && this.Disabled.GetValue(dc.State))
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
@ -72,7 +71,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
object value = null;
if (this.Value != null)
{
var (val, valueError) = this.Value.TryGetValue(dcState);
var (val, valueError) = this.Value.TryGetValue(dc.State);
if (valueError != null)
{
throw new Exception($"Expression evaluation resulted in an error. Expression: {this.Value.ToString()}. Error: {valueError}");
@ -81,9 +80,9 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
value = val;
}
dcState.SetValue(this.Property.GetValue(dcState), value);
dc.State.SetValue(this.Property.GetValue(dc.State), value);
dcState.SetValue(DialogPath.Retries, 0);
dc.State.SetValue(DialogPath.Retries, 0);
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}

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

@ -57,21 +57,19 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
string userId = this.UserId?.GetValue(dcState);
string userId = this.UserId?.GetValue(dc.State);
if (!(dc.Context.Adapter is IUserTokenProvider adapter))
{
throw new InvalidOperationException("SignoutUser(): not supported by the current adapter");
}
var connectionName = this.ConnectionName?.GetValue(dcState);
var connectionName = this.ConnectionName?.GetValue(dc.State);
await adapter.SignOutUserAsync(dc.Context, connectionName, (string)userId, cancellationToken).ConfigureAwait(false);
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);

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

@ -103,9 +103,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
@ -150,7 +148,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
foreach (var caseScope in this.Cases)
{
var (value, error) = this.caseExpressions[caseScope.Value].TryEvaluate(dcState);
var (value, error) = this.caseExpressions[caseScope.Value].TryEvaluate(dc.State);
if (error != null)
{

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

@ -78,9 +78,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
@ -88,7 +86,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
object value = null;
if (this.Value != null)
{
var (val, valError) = this.Value.TryGetValue(dcState);
var (val, valError) = this.Value.TryGetValue(dc.State);
if (valError != null)
{
throw new Exception(valError);
@ -98,12 +96,12 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
}
else
{
value = dcState.GetMemorySnapshot();
value = dc.State.GetMemorySnapshot();
}
var name = this.Name?.GetValue(dcState);
var valueType = this.ValueType?.GetValue(dcState);
var label = this.Label?.GetValue(dcState);
var name = this.Name?.GetValue(dc.State);
var valueType = this.ValueType?.GetValue(dc.State);
var label = this.Label?.GetValue(dc.State);
var traceActivity = Activity.CreateTraceActivity(name ?? "Trace", valueType: valueType ?? "State", value: value, label: label ?? name ?? dc.Parent?.ActiveDialog?.Id);
await dc.Context.SendActivityAsync(traceActivity, cancellationToken).ConfigureAwait(false);

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

@ -69,14 +69,12 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
var activity = await Activity.BindToData(dc.Context, dcState).ConfigureAwait(false);
var activity = await Activity.BindToData(dc.Context, dc.State).ConfigureAwait(false);
var properties = new Dictionary<string, string>()
{
@ -85,7 +83,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
};
TelemetryClient.TrackEvent("GeneratorResult", properties);
var (result, error) = this.ActivityId.TryGetValue(dcState);
var (result, error) = this.ActivityId.TryGetValue(dc.State);
if (error != null)
{
throw new ArgumentException(error);

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

@ -23,7 +23,7 @@ using Newtonsoft.Json;
namespace Microsoft.Bot.Builder.Dialogs.Adaptive
{
public class AdaptiveComponentRegistration : ComponentRegistration, IComponentDeclarativeTypes, IComponentMemoryScopes, IComponentPathResolvers, IComponentExpressionFunctions
public class AdaptiveComponentRegistration : ComponentRegistration, IComponentDeclarativeTypes, IComponentMemoryScopes, IComponentPathResolvers
{
public virtual IEnumerable<DeclarativeType> GetDeclarativeTypes()
{
@ -198,10 +198,5 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
yield return new AtPathResolver();
yield return new PercentPathResolver();
}
public IEnumerable<ExpressionEvaluator> GetExpressionEvaluators()
{
yield break;
}
}
}

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

@ -146,32 +146,30 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
EnsureDependenciesInstalled();
var dcState = dc.GetState();
if (!dcState.ContainsKey(DialogPath.EventCounter))
if (!dc.State.ContainsKey(DialogPath.EventCounter))
{
dcState.SetValue(DialogPath.EventCounter, 0u);
dc.State.SetValue(DialogPath.EventCounter, 0u);
}
if (dialogSchema != null && !dcState.ContainsKey(DialogPath.RequiredProperties))
if (dialogSchema != null && !dc.State.ContainsKey(DialogPath.RequiredProperties))
{
// RequiredProperties control what properties must be filled in.
// Initialize if not present from schema.
dcState.SetValue(DialogPath.RequiredProperties, dialogSchema.Required());
dc.State.SetValue(DialogPath.RequiredProperties, dialogSchema.Required());
}
if (needsTracker)
{
if (!dcState.ContainsKey(ConditionTracker))
if (!dc.State.ContainsKey(ConditionTracker))
{
foreach (var trigger in Triggers)
{
if (trigger.RunOnce && trigger.Condition != null)
{
var paths = dcState.TrackPaths(trigger.Condition.ToExpression().References());
var paths = dc.State.TrackPaths(trigger.Condition.ToExpression().References());
var triggerPath = $"{ConditionTracker}.{trigger.Id}.";
dcState.SetValue(triggerPath + "paths", paths);
dcState.SetValue(triggerPath + "lastRun", 0u);
dc.State.SetValue(triggerPath + "paths", paths);
dc.State.SetValue(triggerPath + "lastRun", 0u);
}
}
}
@ -318,12 +316,10 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
protected virtual async Task<bool> ProcessEventAsync(ActionContext actionContext, DialogEvent dialogEvent, bool preBubble, CancellationToken cancellationToken = default(CancellationToken))
{
var dcState = actionContext.GetState();
// Save into turn
dcState.SetValue(TurnPath.DIALOGEVENT, dialogEvent);
actionContext.State.SetValue(TurnPath.DialogEvent, dialogEvent);
var activity = dcState.GetValue<Activity>(TurnPath.ACTIVITY);
var activity = actionContext.State.GetValue<Activity>(TurnPath.Activity);
// some dialogevents get promoted into turn state for general access outside of the dialogevent.
// This allows events to be fired (in the case of ChooseIntent), or in interruption (Activity)
@ -335,12 +331,12 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
{
// we have received a RecognizedIntent event
// get the value and promote to turn.recognized, topintent,topscore and lastintent
var recognizedResult = dcState.GetValue<RecognizerResult>($"{TurnPath.DIALOGEVENT}.value");
var recognizedResult = actionContext.State.GetValue<RecognizerResult>($"{TurnPath.DialogEvent}.value");
var (name, score) = recognizedResult.GetTopScoringIntent();
dcState.SetValue(TurnPath.RECOGNIZED, recognizedResult);
dcState.SetValue(TurnPath.TOPINTENT, name);
dcState.SetValue(TurnPath.TOPSCORE, score);
dcState.SetValue(DialogPath.LastIntent, name);
actionContext.State.SetValue(TurnPath.Recognized, recognizedResult);
actionContext.State.SetValue(TurnPath.TopIntent, name);
actionContext.State.SetValue(TurnPath.TopScore, score);
actionContext.State.SetValue(DialogPath.LastIntent, name);
// process entities for ambiguity processing (We do this regardless of who handles the event)
ProcessEntities(actionContext, activity);
@ -350,7 +346,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
case AdaptiveEvents.ActivityReceived:
{
// We received an ActivityReceived event, promote the activity into turn.activity
dcState.SetValue(TurnPath.ACTIVITY, dialogEvent.Value);
actionContext.State.SetValue(TurnPath.Activity, dialogEvent.Value);
activity = ObjectPath.GetPathValue<Activity>(dialogEvent, "Value");
break;
}
@ -359,8 +355,8 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
EnsureDependenciesInstalled();
// Count of events processed
var count = dcState.GetValue<uint>(DialogPath.EventCounter);
dcState.SetValue(DialogPath.EventCounter, ++count);
var count = actionContext.State.GetValue<uint>(DialogPath.EventCounter);
actionContext.State.SetValue(DialogPath.EventCounter, ++count);
// Look for triggered evt
var handled = await QueueFirstMatchAsync(actionContext, dialogEvent, preBubble, cancellationToken).ConfigureAwait(false);
@ -376,7 +372,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
switch (dialogEvent.Name)
{
case AdaptiveEvents.BeginDialog:
if (dcState.GetBoolValue(TurnPath.ACTIVITYPROCESSED) == false)
if (actionContext.State.GetBoolValue(TurnPath.ActivityProcessed) == false)
{
// Emit leading ActivityReceived event
var activityReceivedEvent = new DialogEvent()
@ -404,7 +400,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
await ProcessEventAsync(actionContext, dialogEvent: recognizeUtteranceEvent, preBubble: true, cancellationToken: cancellationToken).ConfigureAwait(false);
// Emit leading RecognizedIntent event
var recognized = dcState.GetValue<RecognizerResult>(TurnPath.RECOGNIZED);
var recognized = actionContext.State.GetValue<RecognizerResult>(TurnPath.Recognized);
var recognizedIntentEvent = new DialogEvent
{
Name = AdaptiveEvents.RecognizedIntent,
@ -420,7 +416,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
// process the users uterrance when its continued.
if (handled)
{
dcState.SetValue(TurnPath.INTERRUPTED, true);
actionContext.State.SetValue(TurnPath.Interrupted, true);
}
break;
@ -433,7 +429,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
var recognized = await OnRecognize(actionContext, activity, cancellationToken).ConfigureAwait(false);
// TODO figure out way to not use turn state to pass this value back to caller.
dcState.SetValue(TurnPath.RECOGNIZED, recognized);
actionContext.State.SetValue(TurnPath.Recognized, recognized);
if (Recognizer != null)
{
@ -452,7 +448,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
switch (dialogEvent.Name)
{
case AdaptiveEvents.BeginDialog:
if (dcState.GetBoolValue(TurnPath.ACTIVITYPROCESSED) == false)
if (actionContext.State.GetBoolValue(TurnPath.ActivityProcessed) == false)
{
var activityReceivedEvent = new DialogEvent
{
@ -492,7 +488,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
// process the users uterrance when its continued.
if (handled)
{
dcState.SetValue(TurnPath.INTERRUPTED, true);
actionContext.State.SetValue(TurnPath.Interrupted, true);
}
break;
@ -597,8 +593,6 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
// Is the current dialog still on the stack?
if (actionContext.ActiveDialog != null)
{
var dcState = actionContext.GetState();
// Completed actions so continue processing entity queues
var handled = await ProcessQueuesAsync(actionContext, cancellationToken).ConfigureAwait(false);
@ -610,7 +604,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
else if (ShouldEnd(actionContext))
{
RestoreParentGenerator(actionContext.Context);
dcState.TryGetValue<object>(DefaultResultProperty, out var result);
actionContext.State.TryGetValue<object>(DefaultResultProperty, out var result);
return await actionContext.EndDialogAsync(result, cancellationToken).ConfigureAwait(false);
}
@ -663,8 +657,6 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
// In order ClearProperties, AssignEntity, ChooseProperties, ChooseEntity, EndOfActions.
private async Task<bool> ProcessQueuesAsync(ActionContext actionContext, CancellationToken cancellationToken)
{
var dcState = actionContext.GetState();
DialogEvent evt;
var queues = EntityEvents.Read(actionContext);
var changed = false;
@ -687,7 +679,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
entity = new object[] { entity };
}
dcState.SetValue($"{TurnPath.RECOGNIZED}.entities.{val.Entity.Name}", entity);
actionContext.State.SetValue($"{TurnPath.Recognized}.entities.{val.Entity.Name}", entity);
changed = true;
}
else if (queues.ChooseProperties.Any())
@ -708,7 +700,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
queues.Write(actionContext);
}
dcState.SetValue(DialogPath.LastEvent, evt.Name);
actionContext.State.SetValue(DialogPath.LastEvent, evt.Name);
var handled = await this.ProcessEventAsync(actionContext, dialogEvent: evt, preBubble: true, cancellationToken: cancellationToken).ConfigureAwait(false);
if (!handled)
{
@ -865,36 +857,34 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
// Check to see if an entity is in response to a previous ambiguity event
// Assign entities to possible properties
// Merge new queues into existing queues of ambiguity events
private void ProcessEntities(ActionContext context, Activity activity)
private void ProcessEntities(ActionContext actionContext, Activity activity)
{
var dcState = context.GetState();
if (dialogSchema != null)
{
if (dcState.TryGetValue<string>(DialogPath.LastEvent, out var lastEvent))
if (actionContext.State.TryGetValue<string>(DialogPath.LastEvent, out var lastEvent))
{
dcState.RemoveValue(DialogPath.LastEvent);
actionContext.State.RemoveValue(DialogPath.LastEvent);
}
var queues = EntityEvents.Read(context);
var entities = NormalizeEntities(context);
var queues = EntityEvents.Read(actionContext);
var entities = NormalizeEntities(actionContext);
var utterance = activity?.AsMessageActivity()?.Text;
if (!dcState.TryGetValue<string[]>(DialogPath.ExpectedProperties, out var expected))
if (!actionContext.State.TryGetValue<string[]>(DialogPath.ExpectedProperties, out var expected))
{
expected = new string[0];
}
// Utterance is a special entity that corresponds to the full utterance
entities["utterance"] = new List<EntityInfo> { new EntityInfo { Priority = int.MaxValue, Coverage = 1.0, Start = 0, End = utterance.Length, Name = "utterance", Score = 0.0, Type = "string", Value = utterance, Text = utterance } };
var recognized = AssignEntities(context, entities, expected, queues, lastEvent);
var recognized = AssignEntities(actionContext, entities, expected, queues, lastEvent);
var unrecognized = SplitUtterance(utterance, recognized);
// TODO: Is this actually useful information?
dcState.SetValue(TurnPath.UNRECOGNIZEDTEXT, unrecognized);
dcState.SetValue(TurnPath.RECOGNIZEDENTITIES, recognized);
var turn = dcState.GetValue<uint>(DialogPath.EventCounter);
actionContext.State.SetValue(TurnPath.UnrecognizedText, unrecognized);
actionContext.State.SetValue(TurnPath.RecognizedEntities, recognized);
var turn = actionContext.State.GetValue<uint>(DialogPath.EventCounter);
CombineOldEntityToProperties(queues, turn);
queues.Write(context);
queues.Write(actionContext);
}
}
@ -928,14 +918,13 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
// * Property: Which property should an entity go to? Resolve by expected, then ask.
// Combine entity values and $instance meta-data
private Dictionary<string, List<EntityInfo>> NormalizeEntities(ActionContext context)
private Dictionary<string, List<EntityInfo>> NormalizeEntities(ActionContext actionContext)
{
var dcState = context.GetState();
var entityToInfo = new Dictionary<string, List<EntityInfo>>();
var text = dcState.GetValue<string>(TurnPath.RECOGNIZED + ".text");
if (dcState.TryGetValue<dynamic>(TurnPath.RECOGNIZED + ".entities", out var entities))
var text = actionContext.State.GetValue<string>(TurnPath.Recognized + ".text");
if (actionContext.State.TryGetValue<dynamic>(TurnPath.Recognized + ".entities", out var entities))
{
var turn = dcState.GetValue<uint>(DialogPath.EventCounter);
var turn = actionContext.State.GetValue<uint>(DialogPath.EventCounter);
var metaData = entities["$instance"];
foreach (var entry in entities)
{
@ -1141,9 +1130,8 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
}
}
private List<EntityInfo> AddToQueues(ActionContext context, Dictionary<string, List<EntityInfo>> entities, string[] expected, EntityEvents queues, string lastEvent)
private List<EntityInfo> AddToQueues(ActionContext actionContext, Dictionary<string, List<EntityInfo>> entities, string[] expected, EntityEvents queues, string lastEvent)
{
var dcState = context.GetState();
var candidates = (from candidate in RemoveOverlappingPerProperty(Candidates(entities, expected))
orderby candidate.IsExpected descending
select candidate).ToList();
@ -1206,7 +1194,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
if (expectedChoices.Any())
{
// When choosing between property assignments, make the assignments be expected.
dcState.SetValue(DialogPath.ExpectedProperties, expectedChoices);
actionContext.State.SetValue(DialogPath.ExpectedProperties, expectedChoices);
var choices = queues.ChooseProperties[0];
// Add back in any non-overlapping choices

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

@ -231,7 +231,7 @@ namespace Microsoft.Bot.Builder.Dialogs
await botStateSet.SaveAllChangesAsync(dc.Context, false, cancellationToken).ConfigureAwait(false);
// send trace of memory
var snapshot = dc.GetState().GetMemorySnapshot();
var snapshot = dc.State.GetMemorySnapshot();
var traceActivity = (Activity)Activity.CreateTraceActivity("BotState", "https://www.botframework.com/schemas/botState", snapshot, "Bot State");
await dc.Context.SendActivityAsync(traceActivity).ConfigureAwait(false);

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

@ -1,5 +1,6 @@
// Licensed under the MIT License.
// Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
@ -55,9 +56,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
/// <returns>Event queues.</returns>
public static EntityEvents Read(ActionContext actionContext)
{
var dcState = actionContext.GetState();
if (!dcState.TryGetValue<EntityEvents>(Events, out var queues))
if (!actionContext.State.TryGetValue<EntityEvents>(Events, out var queues))
{
queues = new EntityEvents();
}
@ -70,7 +69,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive
/// </summary>
/// <param name="actionContext">Memory context.</param>
public void Write(ActionContext actionContext)
=> actionContext.GetState().SetValue(Events, this);
=> actionContext.State.SetValue(Events, this);
/// <summary>
/// Remove an event result from queues.

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

@ -50,22 +50,20 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
public override async Task<DialogTurnResult> BeginDialogAsync(DialogContext dc, object options = null, CancellationToken cancellationToken = default)
{
var dcState = dc.GetState();
//get number of retries from memory
if (!dcState.TryGetValue(DialogPath.Retries, out int retries))
if (!dc.State.TryGetValue(DialogPath.Retries, out int retries))
{
retries = 0;
}
dcState.TryGetValue(TurnPath.DIALOGEVENT, out DialogEvent trigger);
dc.State.TryGetValue(TurnPath.DialogEvent, out DialogEvent trigger);
var expected = this.ExpectedProperties?.GetValue(dcState);
var expected = this.ExpectedProperties?.GetValue(dc.State);
if (expected != null
&& dcState.TryGetValue(DialogPath.ExpectedProperties, out List<string> lastExpectedProperties)
&& dc.State.TryGetValue(DialogPath.ExpectedProperties, out List<string> lastExpectedProperties)
&& !expected.Any(prop => !lastExpectedProperties.Contains(prop))
&& !lastExpectedProperties.Any(prop => !expected.Contains(prop))
&& dcState.TryGetValue(DialogPath.LastTriggerEvent, out DialogEvent lastTrigger)
&& dc.State.TryGetValue(DialogPath.LastTriggerEvent, out DialogEvent lastTrigger)
&& lastTrigger.Name.Equals(trigger.Name))
{
retries++;
@ -75,9 +73,9 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Actions
retries = 0;
}
dcState.SetValue(DialogPath.Retries, retries);
dcState.SetValue(DialogPath.LastTriggerEvent, trigger);
dcState.SetValue(DialogPath.ExpectedProperties, expected);
dc.State.SetValue(DialogPath.Retries, retries);
dc.State.SetValue(DialogPath.LastTriggerEvent, trigger);
dc.State.SetValue(DialogPath.ExpectedProperties, expected);
var result = await base.BeginDialogAsync(dc, options, cancellationToken).ConfigureAwait(false);
result.Status = DialogTurnStatus.CompleteAndWait;
return result;

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

@ -43,8 +43,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
protected override Task<InputState> OnRecognizeInput(DialogContext dc)
{
var dcState = dc.GetState();
var input = dcState.GetValue<List<Attachment>>(VALUE_PROPERTY);
var input = dc.State.GetValue<List<Attachment>>(VALUE_PROPERTY);
var first = input.Count > 0 ? input[0] : null;
if (first == null || (string.IsNullOrEmpty(first.ContentUrl) && first.Content == null))
@ -52,13 +51,13 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
return Task.FromResult(InputState.Unrecognized);
}
switch (this.OutputFormat.GetValue(dcState))
switch (this.OutputFormat.GetValue(dc.State))
{
case AttachmentOutputFormat.All:
dcState.SetValue(VALUE_PROPERTY, input);
dc.State.SetValue(VALUE_PROPERTY, input);
break;
case AttachmentOutputFormat.First:
dcState.SetValue(VALUE_PROPERTY, first);
dc.State.SetValue(VALUE_PROPERTY, first);
break;
}

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

@ -123,13 +123,12 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
var op = options as ChoiceInputOptions;
if (op == null || op.Choices == null || op.Choices.Count == 0)
{
var dcState = dc.GetState();
if (op == null)
{
op = new ChoiceInputOptions();
}
var (choices, error) = this.Choices.TryGetValue(dcState);
var (choices, error) = this.Choices.TryGetValue(dc.State);
if (error != null)
{
throw new Exception(error);
@ -143,17 +142,15 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
protected override Task<InputState> OnRecognizeInput(DialogContext dc)
{
var dcState = dc.GetState();
var input = dcState.GetValue<object>(VALUE_PROPERTY);
var options = dcState.GetValue<ChoiceInputOptions>(ThisPath.OPTIONS);
var input = dc.State.GetValue<object>(VALUE_PROPERTY);
var options = dc.State.GetValue<ChoiceInputOptions>(ThisPath.Options);
var choices = options.Choices;
var result = new PromptRecognizerResult<FoundChoice>();
if (dc.Context.Activity.Type == ActivityTypes.Message)
{
var opt = this.RecognizerOptions?.GetValue(dcState) ?? new FindChoicesOptions();
var opt = this.RecognizerOptions?.GetValue(dc.State) ?? new FindChoicesOptions();
opt.Locale = GetCulture(dc);
var results = ChoiceRecognizers.RecognizeChoices(input.ToString(), choices, opt);
if (results == null || results.Count == 0)
@ -162,14 +159,14 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
}
var foundChoice = results[0].Resolution;
switch (this.OutputFormat.GetValue(dcState))
switch (this.OutputFormat.GetValue(dc.State))
{
case ChoiceOutputFormat.Value:
default:
dcState.SetValue(VALUE_PROPERTY, foundChoice.Value);
dc.State.SetValue(VALUE_PROPERTY, foundChoice.Value);
break;
case ChoiceOutputFormat.Index:
dcState.SetValue(VALUE_PROPERTY, foundChoice.Index);
dc.State.SetValue(VALUE_PROPERTY, foundChoice.Index);
break;
}
}
@ -179,26 +176,23 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
protected override async Task<IActivity> OnRenderPrompt(DialogContext dc, InputState state)
{
var dcState = dc.GetState();
var locale = GetCulture(dc);
var prompt = await base.OnRenderPrompt(dc, state);
var channelId = dc.Context.Activity.ChannelId;
var choicePrompt = new ChoicePrompt(this.Id);
var choiceOptions = this.ChoiceOptions?.GetValue(dcState) ?? ChoiceInput.DefaultChoiceOptions[locale];
var choiceOptions = this.ChoiceOptions?.GetValue(dc.State) ?? ChoiceInput.DefaultChoiceOptions[locale];
var (choices, error) = this.Choices.TryGetValue(dcState);
var (choices, error) = this.Choices.TryGetValue(dc.State);
if (error != null)
{
throw new Exception(error);
}
return this.AppendChoices(prompt.AsMessageActivity(), channelId, choices, this.Style.GetValue(dcState), choiceOptions);
return this.AppendChoices(prompt.AsMessageActivity(), channelId, choices, this.Style.GetValue(dc.State), choiceOptions);
}
private string GetCulture(DialogContext dc)
{
var dcState = dc.GetState();
if (!string.IsNullOrWhiteSpace(dc.Context.Activity.Locale))
{
return dc.Context.Activity.Locale;
@ -206,7 +200,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
if (this.DefaultLocale != null)
{
return this.DefaultLocale.GetValue(dcState);
return this.DefaultLocale.GetValue(dc.State);
}
return English;

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

@ -56,8 +56,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
protected override Task<InputState> OnRecognizeInput(DialogContext dc)
{
var dcState = dc.GetState();
var input = dcState.GetValue<object>(VALUE_PROPERTY);
var input = dc.State.GetValue<object>(VALUE_PROPERTY);
if (dc.Context.Activity.Type == ActivityTypes.Message)
{
// Recognize utterance
@ -68,13 +67,13 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
var first = results[0];
if (bool.TryParse(first.Resolution["value"].ToString(), out var value))
{
dcState.SetValue(VALUE_PROPERTY, value);
dc.State.SetValue(VALUE_PROPERTY, value);
if (OutputFormat != null)
{
var (outputValue, error) = OutputFormat.TryGetValue(dcState);
var (outputValue, error) = OutputFormat.TryGetValue(dc.State);
if (error == null)
{
dcState.SetValue(VALUE_PROPERTY, outputValue);
dc.State.SetValue(VALUE_PROPERTY, outputValue);
}
else
{
@ -93,18 +92,18 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
{
// First check whether the prompt was sent to the user with numbers - if it was we should recognize numbers
var defaults = ChoiceDefaults[culture];
var choiceOptions = ChoiceOptions?.GetValue(dcState) ?? defaults.Item3;
var choiceOptions = ChoiceOptions?.GetValue(dc.State) ?? defaults.Item3;
// This logic reflects the fact that IncludeNumbers is nullable and True is the default set in Inline style
if (!choiceOptions.IncludeNumbers.HasValue || choiceOptions.IncludeNumbers.Value)
{
// The text may be a number in which case we will interpret that as a choice.
var confirmChoices = ConfirmChoices?.GetValue(dcState) ?? new List<Choice>() { defaults.Item1, defaults.Item2 };
var confirmChoices = ConfirmChoices?.GetValue(dc.State) ?? new List<Choice>() { defaults.Item1, defaults.Item2 };
var secondAttemptResults = ChoiceRecognizers.RecognizeChoices(input.ToString(), confirmChoices);
if (secondAttemptResults.Count > 0)
{
input = secondAttemptResults[0].Resolution.Index == 0;
dcState.SetValue(VALUE_PROPERTY, input);
dc.State.SetValue(VALUE_PROPERTY, input);
}
else
{
@ -120,15 +119,14 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
protected override async Task<IActivity> OnRenderPrompt(DialogContext dc, InputState state)
{
// Format prompt to send
var dcState = dc.GetState();
var channelId = dc.Context.Activity.ChannelId;
var culture = GetCulture(dc);
var defaults = ChoiceDefaults[culture];
var choiceOptions = ChoiceOptions?.GetValue(dcState) ?? defaults.Item3;
var confirmChoices = ConfirmChoices?.GetValue(dcState) ?? new List<Choice>() { defaults.Item1, defaults.Item2 };
var choiceOptions = ChoiceOptions?.GetValue(dc.State) ?? defaults.Item3;
var confirmChoices = ConfirmChoices?.GetValue(dc.State) ?? new List<Choice>() { defaults.Item1, defaults.Item2 };
var prompt = await base.OnRenderPrompt(dc, state);
var (style, error) = this.Style.TryGetValue(dcState);
var (style, error) = this.Style.TryGetValue(dc.State);
return this.AppendChoices(prompt.AsMessageActivity(), channelId, confirmChoices, style, choiceOptions);
}
@ -141,8 +139,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
if (this.DefaultLocale != null)
{
var dcState = dc.GetState();
return this.DefaultLocale.GetValue(dcState);
return this.DefaultLocale.GetValue(dc.State);
}
return English;

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

@ -30,8 +30,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
protected override Task<InputState> OnRecognizeInput(DialogContext dc)
{
var dcState = dc.GetState();
var input = dcState.GetValue<object>(VALUE_PROPERTY);
var input = dc.State.GetValue<object>(VALUE_PROPERTY);
var culture = GetCulture(dc);
var refTime = dc.Context.Activity.LocalTimestamp?.LocalDateTime;
var results = DateTimeRecognizer.RecognizeDateTime(input.ToString(), culture, refTime: refTime);
@ -45,14 +44,14 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
result.Add(ReadResolution(value));
}
dcState.SetValue(VALUE_PROPERTY, result);
dc.State.SetValue(VALUE_PROPERTY, result);
if (OutputFormat != null)
{
var (outputValue, error) = this.OutputFormat.TryGetValue(dcState);
var (outputValue, error) = this.OutputFormat.TryGetValue(dc.State);
if (error == null)
{
dcState.SetValue(VALUE_PROPERTY, outputValue);
dc.State.SetValue(VALUE_PROPERTY, outputValue);
}
else
{
@ -104,8 +103,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
if (this.DefaultLocale != null)
{
var dcState = dc.GetState();
return this.DefaultLocale.GetValue(dcState);
return this.DefaultLocale.GetValue(dc.State);
}
return English;

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

@ -151,33 +151,31 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState) == true)
if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
var op = OnInitializeOptions(dc, options);
dcState.SetValue(ThisPath.OPTIONS, op);
dcState.SetValue(TURN_COUNT_PROPERTY, 0);
dc.State.SetValue(ThisPath.Options, op);
dc.State.SetValue(TURN_COUNT_PROPERTY, 0);
var alwaysPrompt = this.AlwaysPrompt?.GetValue(dcState) ?? false;
var alwaysPrompt = this.AlwaysPrompt?.GetValue(dc.State) ?? false;
// If AlwaysPrompt is set to true, then clear Property value for turn 0.
var property = this.Property?.GetValue(dcState);
var property = this.Property?.GetValue(dc.State);
if (property != null && alwaysPrompt)
{
dcState.SetValue(property, null);
dc.State.SetValue(property, null);
}
var state = alwaysPrompt ? InputState.Missing : await this.RecognizeInput(dc, 0);
if (state == InputState.Valid)
{
var input = dcState.GetValue<object>(VALUE_PROPERTY);
var input = dc.State.GetValue<object>(VALUE_PROPERTY);
// set property
dcState.SetValue(property, input);
dc.State.SetValue(property, input);
// return as result too
return await dc.EndDialogAsync(input);
@ -187,7 +185,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
// turnCount should increase here, because you want when nextTurn comes in
// We will set the turn count to 1 so the input will not pick from "dialog.value"
// and instead go with "turn.activity.text"
dcState.SetValue(TURN_COUNT_PROPERTY, 1);
dc.State.SetValue(TURN_COUNT_PROPERTY, 1);
return await this.PromptUser(dc, state);
}
}
@ -200,40 +198,38 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
return Dialog.EndOfTurn;
}
var dcState = dc.GetState();
var interrupted = dcState.GetValue<bool>(TurnPath.INTERRUPTED, () => false);
var turnCount = dcState.GetValue<int>(TURN_COUNT_PROPERTY, () => 0);
var interrupted = dc.State.GetValue<bool>(TurnPath.Interrupted, () => false);
var turnCount = dc.State.GetValue<int>(TURN_COUNT_PROPERTY, () => 0);
// Perform base recognition
var state = await this.RecognizeInput(dc, interrupted ? 0 : turnCount);
if (state == InputState.Valid)
{
var input = dcState.GetValue<object>(VALUE_PROPERTY);
var input = dc.State.GetValue<object>(VALUE_PROPERTY);
// set output property
if (this.Property != null)
{
dcState.SetValue(this.Property.GetValue(dcState), input);
dc.State.SetValue(this.Property.GetValue(dc.State), input);
}
return await dc.EndDialogAsync(input).ConfigureAwait(false);
}
else if (this.MaxTurnCount == null || turnCount < this.MaxTurnCount.GetValue(dcState))
else if (this.MaxTurnCount == null || turnCount < this.MaxTurnCount.GetValue(dc.State))
{
// increase the turnCount as last step
dcState.SetValue(TURN_COUNT_PROPERTY, turnCount + 1);
dc.State.SetValue(TURN_COUNT_PROPERTY, turnCount + 1);
return await this.PromptUser(dc, state).ConfigureAwait(false);
}
else
{
if (this.DefaultValue != null)
{
var (value, error) = this.DefaultValue.TryGetValue(dcState);
var (value, error) = this.DefaultValue.TryGetValue(dc.State);
if (this.DefaultValueResponse != null)
{
var response = await this.DefaultValueResponse.BindToData(dc.Context, dcState).ConfigureAwait(false);
var response = await this.DefaultValueResponse.BindToData(dc.Context, dc.State).ConfigureAwait(false);
var properties = new Dictionary<string, string>()
{
@ -246,7 +242,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
}
// set output property
dcState.SetValue(this.Property.GetValue(dcState), value);
dc.State.SetValue(this.Property.GetValue(dc.State), value);
return await dc.EndDialogAsync(value).ConfigureAwait(false);
}
@ -266,8 +262,6 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
{
if (e.Name == DialogEvents.ActivityReceived && dc.Context.Activity.Type == ActivityTypes.Message)
{
var dcState = dc.GetState();
// Ask parent to perform recognition
await dc.Parent.EmitEventAsync(AdaptiveEvents.RecognizeUtterance, value: dc.Context.Activity, bubble: false, cancellationToken: cancellationToken).ConfigureAwait(false);
@ -275,7 +269,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
var canInterrupt = true;
if (this.AllowInterruptions != null)
{
var (allowInterruptions, error) = this.AllowInterruptions.TryGetValue(dcState);
var (allowInterruptions, error) = this.AllowInterruptions.TryGetValue(dc.State);
canInterrupt = error == null && allowInterruptions;
}
@ -356,8 +350,6 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
protected virtual async Task<IActivity> OnRenderPrompt(DialogContext dc, InputState state)
{
IMessageActivity msg = null;
var dcState = dc.GetState();
ITemplate<Activity> template = null;
switch (state)
{
@ -365,12 +357,12 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
if (this.UnrecognizedPrompt != null)
{
template = this.UnrecognizedPrompt;
msg = await this.UnrecognizedPrompt.BindToData(dc.Context, dcState).ConfigureAwait(false);
msg = await this.UnrecognizedPrompt.BindToData(dc.Context, dc.State).ConfigureAwait(false);
}
else if (this.InvalidPrompt != null)
{
template = this.InvalidPrompt;
msg = await this.InvalidPrompt.BindToData(dc.Context, dcState).ConfigureAwait(false);
msg = await this.InvalidPrompt.BindToData(dc.Context, dc.State).ConfigureAwait(false);
}
break;
@ -379,12 +371,12 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
if (this.InvalidPrompt != null)
{
template = this.InvalidPrompt;
msg = await this.InvalidPrompt.BindToData(dc.Context, dcState).ConfigureAwait(false);
msg = await this.InvalidPrompt.BindToData(dc.Context, dc.State).ConfigureAwait(false);
}
else if (this.UnrecognizedPrompt != null)
{
template = this.UnrecognizedPrompt;
msg = await this.UnrecognizedPrompt.BindToData(dc.Context, dcState).ConfigureAwait(false);
msg = await this.UnrecognizedPrompt.BindToData(dc.Context, dc.State).ConfigureAwait(false);
}
break;
@ -393,7 +385,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
if (msg == null)
{
template = this.Prompt;
msg = await this.Prompt.BindToData(dc.Context, dcState).ConfigureAwait(false);
msg = await this.Prompt.BindToData(dc.Context, dc.State).ConfigureAwait(false);
}
msg.InputHint = InputHints.ExpectingInput;
@ -412,23 +404,21 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
{
dynamic input = null;
var dcState = dc.GetState();
// Use Property expression for input first
if (this.Property != null)
{
var property = this.Property.GetValue(dcState);
dcState.TryGetValue(property, out input);
var property = this.Property.GetValue(dc.State);
dc.State.TryGetValue(property, out input);
// Clear property to avoid it being stuck on the next turn. It will get written
// back if the value passes validations.
dcState.SetValue(property, null);
dc.State.SetValue(property, null);
}
// Use Value expression for input second
if (input == null && this.Value != null)
{
var (value, valueError) = this.Value.TryGetValue(dcState);
var (value, valueError) = this.Value.TryGetValue(dc.State);
if (valueError != null)
{
throw new Exception($"In InputDialog, this.Value expression evaluation resulted in an error. Expression: {this.Value}. Error: {valueError}");
@ -438,7 +428,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
}
// Fallback to using activity
bool activityProcessed = dcState.GetBoolValue(TurnPath.ACTIVITYPROCESSED);
bool activityProcessed = dc.State.GetBoolValue(TurnPath.ActivityProcessed);
if (!activityProcessed && input == null && turnCount > 0)
{
if (this.GetType().Name == nameof(AttachmentInput))
@ -458,7 +448,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
}
// Update "this.value" and perform additional recognition and validations
dcState.SetValue(VALUE_PROPERTY, input);
dc.State.SetValue(VALUE_PROPERTY, input);
if (input != null)
{
var state = await this.OnRecognizeInput(dc).ConfigureAwait(false);
@ -467,14 +457,14 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
foreach (var validation in this.Validations)
{
var exp = Expression.Parse(validation.TrimStart('='));
var (value, error) = exp.TryEvaluate(dcState);
var (value, error) = exp.TryEvaluate(dc.State);
if (value == null || (value is bool && (bool)value == false))
{
return InputState.Invalid;
}
}
dcState.SetValue(TurnPath.ACTIVITYPROCESSED, true);
dc.State.SetValue(TurnPath.ActivityProcessed, true);
return InputState.Valid;
}
else

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

@ -29,8 +29,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
protected override Task<InputState> OnRecognizeInput(DialogContext dc)
{
var dcState = dc.GetState();
var input = dcState.GetValue<object>(VALUE_PROPERTY);
var input = dc.State.GetValue<object>(VALUE_PROPERTY);
var culture = GetCulture(dc);
var results = NumberRecognizer.RecognizeNumber(input.ToString(), culture);
@ -60,14 +59,14 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
return Task.FromResult(InputState.Unrecognized);
}
dcState.SetValue(VALUE_PROPERTY, input);
dc.State.SetValue(VALUE_PROPERTY, input);
if (OutputFormat != null)
{
var (outputValue, error) = this.OutputFormat.TryGetValue(dcState);
var (outputValue, error) = this.OutputFormat.TryGetValue(dc.State);
if (error == null)
{
dcState.SetValue(VALUE_PROPERTY, outputValue);
dc.State.SetValue(VALUE_PROPERTY, outputValue);
}
else
{
@ -87,9 +86,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
if (this.DefaultLocale != null)
{
var dcState = dc.GetState();
return this.DefaultLocale.GetValue(dcState);
return this.DefaultLocale.GetValue(dc.State);
}
return English;

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

@ -79,9 +79,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
}
var dcState = dc.GetState();
if (this.Disabled != null && this.Disabled.GetValue(dcState))
if (this.Disabled != null && this.Disabled.GetValue(dc.State))
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
@ -106,15 +104,15 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
}
var op = OnInitializeOptions(dc, options);
dcState.SetValue(ThisPath.OPTIONS, op);
dcState.SetValue(TURN_COUNT_PROPERTY, 0);
dc.State.SetValue(ThisPath.Options, op);
dc.State.SetValue(TURN_COUNT_PROPERTY, 0);
// If AlwaysPrompt is set to true, then clear Property value for turn 0.
var (alwaysPrompt, _) = this.AlwaysPrompt.TryGetValue(dcState);
var (alwaysPrompt, _) = this.AlwaysPrompt.TryGetValue(dc.State);
if (this.Property != null && alwaysPrompt)
{
dcState.SetValue(this.Property.GetValue(dcState), null);
dc.State.SetValue(this.Property.GetValue(dc.State), null);
}
// Initialize state
@ -125,7 +123,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
{ AttemptCountKey, 0 },
};
state[PersistedExpires] = DateTime.Now.AddMilliseconds(Timeout.GetValue(dcState));
state[PersistedExpires] = DateTime.Now.AddMilliseconds(Timeout.GetValue(dc.State));
// Attempt to get the users token
if (!(dc.Context.Adapter is IUserTokenProvider adapter))
@ -133,12 +131,12 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
throw new InvalidOperationException("OAuthPrompt.Recognize(): not supported by the current adapter");
}
var output = await adapter.GetUserTokenAsync(dc.Context, ConnectionName.GetValue(dcState), null, cancellationToken).ConfigureAwait(false);
var output = await adapter.GetUserTokenAsync(dc.Context, ConnectionName.GetValue(dc.State), null, cancellationToken).ConfigureAwait(false);
if (output != null)
{
if (this.Property != null)
{
dcState.SetValue(this.Property.GetValue(dcState), output);
dc.State.SetValue(this.Property.GetValue(dc.State), output);
}
// Return token
@ -146,7 +144,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
}
else
{
dcState.SetValue(TURN_COUNT_PROPERTY, 1);
dc.State.SetValue(TURN_COUNT_PROPERTY, 1);
// Prompt user to login
await SendOAuthCardAsync(dc, opt?.Prompt, cancellationToken).ConfigureAwait(false);
@ -172,9 +170,8 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
throw new ArgumentNullException(nameof(dc));
}
var dcState = dc.GetState();
var interrupted = dcState.GetValue<bool>(TurnPath.INTERRUPTED, () => false);
var turnCount = dcState.GetValue<int>(TURN_COUNT_PROPERTY, () => 0);
var interrupted = dc.State.GetValue<bool>(TurnPath.Interrupted, () => false);
var turnCount = dc.State.GetValue<int>(TURN_COUNT_PROPERTY, () => 0);
// Recognize token
var recognized = await RecognizeTokenAsync(dc, cancellationToken).ConfigureAwait(false);
@ -189,7 +186,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
{
if (this.Property != null)
{
dcState.SetValue(this.Property.GetValue(dcState), null);
dc.State.SetValue(this.Property.GetValue(dc.State), null);
}
// if the token fetch request times out, complete the prompt with no result.
@ -216,15 +213,15 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
{
if (this.Property != null)
{
dcState.SetValue(this.Property.GetValue(dcState), recognized.Value);
dc.State.SetValue(this.Property.GetValue(dc.State), recognized.Value);
}
return await dc.EndDialogAsync(recognized.Value, cancellationToken).ConfigureAwait(false);
}
else if (this.MaxTurnCount == null || turnCount < this.MaxTurnCount.GetValue(dcState))
else if (this.MaxTurnCount == null || turnCount < this.MaxTurnCount.GetValue(dc.State))
{
// increase the turnCount as last step
dcState.SetValue(TURN_COUNT_PROPERTY, turnCount + 1);
dc.State.SetValue(TURN_COUNT_PROPERTY, turnCount + 1);
var prompt = await this.OnRenderPrompt(dc, inputState).ConfigureAwait(false);
await dc.Context.SendActivityAsync(prompt).ConfigureAwait(false);
await SendOAuthCardAsync(dc, promptOptions?.Prompt, cancellationToken).ConfigureAwait(false);
@ -234,10 +231,10 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
{
if (this.DefaultValue != null)
{
var (value, _) = this.DefaultValue.TryGetValue(dcState);
var (value, _) = this.DefaultValue.TryGetValue(dc.State);
if (this.DefaultValueResponse != null)
{
var response = await this.DefaultValueResponse.BindToData(dc.Context, dcState).ConfigureAwait(false);
var response = await this.DefaultValueResponse.BindToData(dc.Context, dc.State).ConfigureAwait(false);
var properties = new Dictionary<string, string>()
{
{ "template", JsonConvert.SerializeObject(this.DefaultValueResponse) },
@ -248,7 +245,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
}
// set output property
dcState.SetValue(this.Property.GetValue(dcState), value);
dc.State.SetValue(this.Property.GetValue(dc.State), value);
return await dc.EndDialogAsync(value).ConfigureAwait(false);
}
}
@ -273,8 +270,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
throw new InvalidOperationException("OAuthPrompt.GetUserToken(): not supported by the current adapter");
}
var dcState = dc.GetState();
return await adapter.GetUserTokenAsync(dc.Context, ConnectionName.GetValue(dcState), null, cancellationToken).ConfigureAwait(false);
return await adapter.GetUserTokenAsync(dc.Context, ConnectionName.GetValue(dc.State), null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
@ -291,10 +287,8 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
throw new InvalidOperationException("OAuthPrompt.SignOutUser(): not supported by the current adapter");
}
var dcState = dc.GetState();
// Sign out user
await adapter.SignOutUserAsync(dc.Context, ConnectionName.GetValue(dcState), dc.Context.Activity?.From?.Id, cancellationToken).ConfigureAwait(false);
await adapter.SignOutUserAsync(dc.Context, ConnectionName.GetValue(dc.State), dc.Context.Activity?.From?.Id, cancellationToken).ConfigureAwait(false);
}
protected override Task<InputState> OnRecognizeInput(DialogContext dc)
@ -311,8 +305,6 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
throw new InvalidOperationException("OAuthPrompt.Prompt(): not supported by the current adapter");
}
var dcState = dc.GetState();
// Ensure prompt initialized
if (prompt == null)
{
@ -329,18 +321,18 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
{
if (!prompt.Attachments.Any(a => a.Content is SigninCard))
{
var link = await adapter.GetOauthSignInLinkAsync(turnContext, ConnectionName?.GetValue(dcState), cancellationToken).ConfigureAwait(false);
var link = await adapter.GetOauthSignInLinkAsync(turnContext, ConnectionName?.GetValue(dc.State), cancellationToken).ConfigureAwait(false);
prompt.Attachments.Add(new Attachment
{
ContentType = SigninCard.ContentType,
Content = new SigninCard
{
Text = Text?.GetValue(dcState),
Text = Text?.GetValue(dc.State),
Buttons = new[]
{
new CardAction
{
Title = Title?.GetValue(dcState),
Title = Title?.GetValue(dc.State),
Value = link,
Type = ActionTypes.Signin,
},
@ -356,14 +348,14 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
ContentType = OAuthCard.ContentType,
Content = new OAuthCard
{
Text = Text?.GetValue(dcState),
ConnectionName = ConnectionName?.GetValue(dcState),
Text = Text?.GetValue(dc.State),
ConnectionName = ConnectionName?.GetValue(dc.State),
Buttons = new[]
{
new CardAction
{
Title = Title?.GetValue(dcState),
Text = Text?.GetValue(dcState),
Title = Title?.GetValue(dc.State),
Text = Text?.GetValue(dc.State),
Type = ActionTypes.Signin,
},
},
@ -382,8 +374,6 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
private async Task<PromptRecognizerResult<TokenResponse>> RecognizeTokenAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
{
var dcState = dc.GetState();
var result = new PromptRecognizerResult<TokenResponse>();
if (IsTokenResponseEvent(dc.Context))
{
@ -411,7 +401,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
// progress) retry in that case.
try
{
var token = await adapter.GetUserTokenAsync(dc.Context, ConnectionName.GetValue(dcState), magicCode, cancellationToken).ConfigureAwait(false);
var token = await adapter.GetUserTokenAsync(dc.Context, ConnectionName.GetValue(dc.State), magicCode, cancellationToken).ConfigureAwait(false);
if (token != null)
{
@ -440,7 +430,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
throw new InvalidOperationException("OAuthPrompt.Recognize(): not supported by the current adapter");
}
var token = await adapter.GetUserTokenAsync(dc.Context, ConnectionName.GetValue(dcState), matched.Value, cancellationToken).ConfigureAwait(false);
var token = await adapter.GetUserTokenAsync(dc.Context, ConnectionName.GetValue(dc.State), matched.Value, cancellationToken).ConfigureAwait(false);
if (token != null)
{
result.Succeeded = true;

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

@ -27,13 +27,11 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
protected override Task<InputState> OnRecognizeInput(DialogContext dc)
{
var dcState = dc.GetState();
var input = dcState.GetValue<string>(VALUE_PROPERTY);
var input = dc.State.GetValue<string>(VALUE_PROPERTY);
if (this.OutputFormat != null)
{
var (outputValue, error) = this.OutputFormat.TryGetValue(dcState);
var (outputValue, error) = this.OutputFormat.TryGetValue(dc.State);
if (error == null)
{
input = outputValue.ToString();
@ -44,7 +42,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Input
}
}
dcState.SetValue(VALUE_PROPERTY, input);
dc.State.SetValue(VALUE_PROPERTY, input);
return input.Length > 0 ? Task.FromResult(InputState.Valid) : Task.FromResult(InputState.Unrecognized);
}
}

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

@ -113,12 +113,11 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Recognizers
public LuisRecognizerOptionsV3 RecognizerOptions(DialogContext dialogContext)
{
var options = PredictionOptions;
var dcState = dialogContext.GetState();
if (DynamicLists != null)
{
options = new AI.LuisV3.LuisPredictionOptions(options);
var list = new List<AI.LuisV3.DynamicList>();
foreach (var listEntity in DynamicLists.GetValue(dcState))
foreach (var listEntity in DynamicLists.GetValue(dialogContext.State))
{
list.Add(new AI.LuisV3.DynamicList(listEntity.Entity, listEntity.List));
}
@ -126,7 +125,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Recognizers
options.DynamicLists = list;
}
var application = new LuisApplication(ApplicationId.GetValue(dcState), EndpointKey.GetValue(dcState), Endpoint.GetValue(dcState));
var application = new LuisApplication(ApplicationId.GetValue(dialogContext.State), EndpointKey.GetValue(dialogContext.State), Endpoint.GetValue(dialogContext.State));
return new LuisRecognizerOptionsV3(application)
{
ExternalEntityRecognizer = ExternalEntityRecognizer,

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

@ -3,6 +3,7 @@
using System.Collections.Generic;
using AdaptiveExpressions.Converters;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Dialogs.Adaptive.Luis;
using Microsoft.Bot.Builder.Dialogs.Adaptive.Recognizers;
using Microsoft.Bot.Builder.Dialogs.Declarative;

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

@ -1,21 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using Microsoft.Bot.Builder.Dialogs.Memory;
namespace Microsoft.Bot.Builder.Dialogs
{
public static class DialogContextExtensions
{
/// <summary>
/// Get access to the new DialogStateManager for the given context.
/// </summary>
/// <param name="dc">dialog context to get the DialogStateManager for.</param>
/// <returns>DialogStateManager.</returns>
public static DialogStateManager GetState(this DialogContext dc)
{
return new DialogStateManager(dc);
}
}
}

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

@ -3,6 +3,7 @@
using System.Collections.Generic;
using AdaptiveExpressions.Converters;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Dialogs.Adaptive.Conditions;
using Microsoft.Bot.Builder.Dialogs.Adaptive.QnA;
using Microsoft.Bot.Builder.Dialogs.Adaptive.QnA.Recognizers;

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

@ -130,8 +130,6 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.QnA
protected async override Task<IQnAMakerClient> GetQnAMakerClientAsync(DialogContext dc)
{
var dcState = dc.GetState();
var qnaClient = dc.Context.TurnState.Get<IQnAMakerClient>();
if (qnaClient != null)
{
@ -139,9 +137,9 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.QnA
return qnaClient;
}
var (epKey, error) = this.EndpointKey.TryGetValue(dcState);
var (hn, error2) = this.HostName.TryGetValue(dcState);
var (kbId, error3) = this.KnowledgeBaseId.TryGetValue(dcState);
var (epKey, error) = this.EndpointKey.TryGetValue(dc.State);
var (hn, error2) = this.HostName.TryGetValue(dc.State);
var (kbId, error3) = this.KnowledgeBaseId.TryGetValue(dc.State);
var endpoint = new QnAMakerEndpoint
{
@ -155,24 +153,21 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.QnA
protected override Task<QnAMakerOptions> GetQnAMakerOptionsAsync(DialogContext dc)
{
var dcState = dc.GetState();
return Task.FromResult(new QnAMakerOptions
{
ScoreThreshold = this.Threshold.GetValue(dcState),
StrictFilters = this.StrictFilters?.GetValue(dcState)?.ToArray(),
Top = this.Top.GetValue(dcState),
ScoreThreshold = this.Threshold.GetValue(dc.State),
StrictFilters = this.StrictFilters?.GetValue(dc.State)?.ToArray(),
Top = this.Top.GetValue(dc.State),
QnAId = 0,
RankerType = this.RankerType.GetValue(dcState),
RankerType = this.RankerType.GetValue(dc.State),
IsTest = this.IsTest
});
}
protected async override Task<QnADialogResponseOptions> GetQnAResponseOptionsAsync(DialogContext dc)
{
var dcState = dc.GetState();
var noAnswer = (this.NoAnswer != null) ? await this.NoAnswer.BindToData(dc.Context, dcState).ConfigureAwait(false) : null;
var cardNoMatchResponse = (this.CardNoMatchResponse != null) ? await this.CardNoMatchResponse.BindToData(dc.Context, dcState).ConfigureAwait(false) : null;
var noAnswer = (this.NoAnswer != null) ? await this.NoAnswer.BindToData(dc.Context, dc.State).ConfigureAwait(false) : null;
var cardNoMatchResponse = (this.CardNoMatchResponse != null) ? await this.CardNoMatchResponse.BindToData(dc.Context, dc.State).ConfigureAwait(false) : null;
if (noAnswer != null)
{
@ -196,8 +191,8 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.QnA
var responseOptions = new QnADialogResponseOptions
{
ActiveLearningCardTitle = this.ActiveLearningCardTitle.GetValue(dcState),
CardNoMatchText = this.CardNoMatchText.GetValue(dcState),
ActiveLearningCardTitle = this.ActiveLearningCardTitle.GetValue(dc.State),
CardNoMatchText = this.CardNoMatchText.GetValue(dc.State),
NoAnswer = noAnswer,
CardNoMatchResponse = cardNoMatchResponse,
};

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

@ -133,8 +133,6 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.QnA.Recognizers
public override async Task<RecognizerResult> RecognizeAsync(DialogContext dialogContext, Activity activity, CancellationToken cancellationToken, Dictionary<string, string> telemetryProperties = null, Dictionary<string, double> telemetryMetrics = null)
{
var dcState = dialogContext.GetState();
// Identify matched intents
var recognizerResult = new RecognizerResult()
{
@ -149,13 +147,13 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.QnA.Recognizers
}
List<Metadata> filters = new List<Metadata>();
if (IncludeDialogNameInMetadata.GetValue(dcState))
if (IncludeDialogNameInMetadata.GetValue(dialogContext.State))
{
filters.Add(new Metadata() { Name = "dialogName", Value = dialogContext.ActiveDialog.Id });
}
// if there is $qna.metadata set add to filters
var externalMetadata = this.Metadata?.GetValue(dcState);
var externalMetadata = this.Metadata?.GetValue(dialogContext.State);
if (externalMetadata != null)
{
filters.AddRange(externalMetadata);
@ -167,12 +165,12 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.QnA.Recognizers
dialogContext.Context,
new QnAMakerOptions
{
Context = this.Context?.GetValue(dcState),
ScoreThreshold = this.Threshold.GetValue(dcState),
Context = this.Context?.GetValue(dialogContext.State),
ScoreThreshold = this.Threshold.GetValue(dialogContext.State),
StrictFilters = filters.ToArray(),
Top = this.Top.GetValue(dcState),
QnAId = this.QnAId.GetValue(dcState),
RankerType = this.RankerType.GetValue(dcState),
Top = this.Top.GetValue(dialogContext.State),
QnAId = this.QnAId.GetValue(dialogContext.State),
RankerType = this.RankerType.GetValue(dialogContext.State),
IsTest = this.IsTest
},
null).ConfigureAwait(false);
@ -226,11 +224,9 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.QnA.Recognizers
return Task.FromResult(qnaClient);
}
var dcState = dc.GetState();
var (epKey, error) = this.EndpointKey.TryGetValue(dcState);
var (hn, error2) = this.HostName.TryGetValue(dcState);
var (kbId, error3) = this.KnowledgeBaseId.TryGetValue(dcState);
var (epKey, error) = this.EndpointKey.TryGetValue(dc.State);
var (hn, error2) = this.HostName.TryGetValue(dc.State);
var (kbId, error3) = this.KnowledgeBaseId.TryGetValue(dc.State);
var endpoint = new QnAMakerEndpoint
{

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

@ -55,10 +55,9 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Selectors
_evaluate = evaluate;
}
public async Task<IReadOnlyList<OnCondition>> Select(ActionContext context, CancellationToken cancel = default)
public async Task<IReadOnlyList<OnCondition>> Select(ActionContext actionContext, CancellationToken cancel = default)
{
var dcState = context.GetState();
var (eval, _) = Condition.TryGetValue(dcState);
var (eval, _) = Condition.TryGetValue(actionContext.State);
ITriggerSelector selector;
if (eval)
{
@ -71,7 +70,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Selectors
IfFalse.Initialize(_conditionals, _evaluate);
}
return await selector.Select(context, cancel).ConfigureAwait(false);
return await selector.Select(actionContext, cancel).ConfigureAwait(false);
}
}
}

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

@ -37,7 +37,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Selectors
{
var conditional = _conditionals[i];
var expression = conditional.GetExpression();
var (value, error) = expression.TryEvaluate(context.GetState());
var (value, error) = expression.TryEvaluate(context.State);
var eval = error == null && (bool)value;
if (eval == true)
{

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

@ -39,7 +39,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Selectors
public virtual async Task<IReadOnlyList<OnCondition>> Select(ActionContext context, CancellationToken cancel)
{
var triggers = _tree.Matches(context.GetState());
var triggers = _tree.Matches(context.State);
var matches = new List<OnCondition>();
foreach (var trigger in triggers)
{

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

@ -61,7 +61,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Selectors
foreach (var conditional in _conditionals)
{
var expression = conditional.GetExpression();
var (value, error) = expression.TryEvaluate(context.GetState());
var (value, error) = expression.TryEvaluate(context.State);
var eval = error == null && (bool)value;
if (eval == true)
{

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

@ -36,7 +36,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Selectors
foreach (var conditional in _conditionals)
{
var expression = conditional.GetExpression();
var (value, error) = expression.TryEvaluate(context.GetState());
var (value, error) = expression.TryEvaluate(context.State);
var result = error == null && (bool)value;
if (result == true)
{

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

@ -104,25 +104,24 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Skills
public override async Task<DialogTurnResult> BeginDialogAsync(DialogContext dc, object options = null, CancellationToken cancellationToken = default)
{
var dcState = dc.GetState();
if (Disabled != null && Disabled.GetValue(dcState))
if (Disabled != null && Disabled.GetValue(dc.State))
{
return await dc.EndDialogAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
}
// Update the dialog options with the runtime settings.
DialogOptions.BotId = BotId.GetValue(dcState);
DialogOptions.SkillHostEndpoint = new Uri(SkillHostEndpoint.GetValue(dcState));
DialogOptions.BotId = BotId.GetValue(dc.State);
DialogOptions.SkillHostEndpoint = new Uri(SkillHostEndpoint.GetValue(dc.State));
DialogOptions.ConversationIdFactory = HostContext.Current.Get<SkillConversationIdFactoryBase>() ?? throw new NullReferenceException("Unable to locate SkillConversationIdFactoryBase in HostContext");
DialogOptions.SkillClient = HostContext.Current.Get<BotFrameworkClient>() ?? throw new NullReferenceException("Unable to locate BotFrameworkClient in HostContext");
DialogOptions.ConversationState = dc.Context.TurnState.Get<ConversationState>() ?? throw new NullReferenceException($"Unable to get an instance of {nameof(ConversationState)} from TurnState.");
// Set the skill to call
DialogOptions.Skill.Id = DialogOptions.Skill.AppId = SkillAppId.GetValue(dcState);
DialogOptions.Skill.SkillEndpoint = new Uri(SkillEndpoint.GetValue(dcState));
DialogOptions.Skill.Id = DialogOptions.Skill.AppId = SkillAppId.GetValue(dc.State);
DialogOptions.Skill.SkillEndpoint = new Uri(SkillEndpoint.GetValue(dc.State));
// Get the activity to send to the skill.
var activity = await Activity.BindToData(dc.Context, dcState).ConfigureAwait(false);
var activity = await Activity.BindToData(dc.Context, dc.State).ConfigureAwait(false);
// Call the base to invoke the skill
return await base.BeginDialogAsync(dc, new BeginSkillDialogOptions { Activity = activity }, cancellationToken).ConfigureAwait(false);
@ -133,10 +132,9 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Skills
if (dc.Context.Activity.Type == ActivityTypes.EndOfConversation)
{
// Capture the result of the dialog if the property is set
var dcState = dc.GetState();
if (ResultProperty != null)
{
dcState.SetValue(ResultProperty.GetValue(dcState), dc.Context.Activity.Value);
dc.State.SetValue(ResultProperty.GetValue(dc.State), dc.Context.Activity.Value);
}
}

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

@ -46,7 +46,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Conditions
public override Expression GetExpression()
{
// add constraints for activity type
return Expression.AndExpression(Expression.Parse($"{TurnPath.ACTIVITY}.type == '{this.Type}'"), base.GetExpression());
return Expression.AndExpression(Expression.Parse($"{TurnPath.Activity}.type == '{this.Type}'"), base.GetExpression());
}
}
}

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

@ -57,17 +57,17 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Conditions
var expressions = new List<Expression> { base.GetExpression() };
if (this.Property != null)
{
expressions.Add(Expression.Parse($"{TurnPath.DIALOGEVENT}.value.property == '{this.Property}'"));
expressions.Add(Expression.Parse($"{TurnPath.DialogEvent}.value.property == '{this.Property}'"));
}
if (this.Entity != null)
{
expressions.Add(Expression.Parse($"{TurnPath.DIALOGEVENT}.value.entity.name == '{this.Entity}'"));
expressions.Add(Expression.Parse($"{TurnPath.DialogEvent}.value.entity.name == '{this.Entity}'"));
}
if (this.Operation != null)
{
expressions.Add(Expression.Parse($"{TurnPath.DIALOGEVENT}.value.entity.operation == '{this.Operation}'"));
expressions.Add(Expression.Parse($"{TurnPath.DialogEvent}.value.entity.operation == '{this.Operation}'"));
}
return Expression.AndExpression(expressions.ToArray());

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

@ -50,12 +50,12 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Conditions
var expressions = new List<Expression> { base.GetExpression() };
if (this.Property != null)
{
expressions.Add(Expression.Parse($"{TurnPath.DIALOGEVENT}.value.property == '{this.Property}'"));
expressions.Add(Expression.Parse($"{TurnPath.DialogEvent}.value.property == '{this.Property}'"));
}
if (this.Entity != null)
{
expressions.Add(Expression.Parse($"{TurnPath.DIALOGEVENT}.value.entity.name == '{this.Entity}'"));
expressions.Add(Expression.Parse($"{TurnPath.DialogEvent}.value.entity.name == '{this.Entity}'"));
}
return Expression.AndExpression(expressions.ToArray());

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

@ -39,7 +39,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Conditions
// add constraints for the intents property if set
if (this.Intents?.Any() == true)
{
var constraints = this.Intents.Select(subIntent => Expression.Parse($"contains(jPath({TurnPath.RECOGNIZED}, '$.candidates[*].intent'), '{subIntent}')"));
var constraints = this.Intents.Select(subIntent => Expression.Parse($"contains(jPath({TurnPath.Recognized}, '$.candidates[*].intent'), '{subIntent}')"));
return Expression.AndExpression(base.GetExpression(), Expression.AndExpression(constraints.ToArray()));
}

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

@ -50,12 +50,12 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Conditions
var expressions = new List<Expression> { base.GetExpression() };
foreach (var property in this.Properties)
{
expressions.Add(Expression.Parse($"contains(foreach({TurnPath.DIALOGEVENT}.value, mapping, mapping.property), '{property}')"));
expressions.Add(Expression.Parse($"contains(foreach({TurnPath.DialogEvent}.value, mapping, mapping.property), '{property}')"));
}
foreach (var entity in this.Entities)
{
expressions.Add(Expression.Parse($"contains(foreach({TurnPath.DIALOGEVENT}.value, mapping, mapping.entity.name), '{entity}')"));
expressions.Add(Expression.Parse($"contains(foreach({TurnPath.DialogEvent}.value, mapping, mapping.entity.name), '{entity}')"));
}
return Expression.AndExpression(expressions.ToArray());

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

@ -42,7 +42,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Conditions
var expressions = new List<Expression> { base.GetExpression() };
if (this.Property != null)
{
expressions.Add(Expression.Parse($"{TurnPath.DIALOGEVENT}.value.property == '{this.Property}'"));
expressions.Add(Expression.Parse($"{TurnPath.DialogEvent}.value.property == '{this.Property}'"));
}
return Expression.AndExpression(expressions.ToArray());

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

@ -111,7 +111,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Conditions
if (this.fullConstraint == null)
{
var allExpressions = new List<Expression>();
if (this.Condition != null)
{
allExpressions.Add(this.Condition.ToExpression());
@ -141,11 +141,34 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Conditions
$"runOnce{Id}",
(expression, os) =>
{
var state = os as DialogStateManager;
var basePath = $"{AdaptiveDialog.ConditionTracker}.{Id}.";
var lastRun = state.GetValue<uint>(basePath + "lastRun");
var paths = state.GetValue<string[]>(basePath + "paths");
var changed = state.AnyPathChanged(lastRun, paths);
var changed = false;
if (os.TryGetValue(basePath + "lastRun", out object val))
{
uint lastRun = ObjectPath.MapValueTo<uint>(val);
if (os.TryGetValue(basePath + "paths", out val))
{
string[] paths = ObjectPath.MapValueTo<string[]>(val);
if (paths != null)
{
foreach (var path in paths)
{
if (os.TryGetValue($"dialog._tracker.paths.{path}", out val))
{
uint current = ObjectPath.MapValueTo<uint>(val);
if (current > lastRun)
{
changed = true;
break;
}
}
}
}
}
}
return (changed, null);
},
ReturnType.Boolean,
@ -164,7 +187,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Conditions
/// <returns>Computed priority.</returns>
public int CurrentPriority(ActionContext actionContext)
{
var (priority, error) = this.Priority.TryGetValue(actionContext.GetState());
var (priority, error) = this.Priority.TryGetValue(actionContext.State);
if (error != null)
{
priority = -1;
@ -205,9 +228,8 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Conditions
{
if (RunOnce)
{
var dcState = actionContext.GetState();
var count = dcState.GetValue<uint>(DialogPath.EventCounter);
dcState.SetValue($"{AdaptiveDialog.ConditionTracker}.{Id}.lastRun", count);
var count = actionContext.State.GetValue<uint>(DialogPath.EventCounter);
actionContext.State.SetValue($"{AdaptiveDialog.ConditionTracker}.{Id}.lastRun", count);
}
return await Task.FromResult(new List<ActionChangeList>()

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

@ -39,7 +39,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Conditions
public override Expression GetExpression()
{
return Expression.AndExpression(Expression.Parse($"{TurnPath.DIALOGEVENT}.name == '{this.Event}'"), base.GetExpression());
return Expression.AndExpression(Expression.Parse($"{TurnPath.DialogEvent}.name == '{this.Event}'"), base.GetExpression());
}
}
}

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

@ -39,7 +39,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Conditions
public override Expression GetExpression()
{
return Expression.AndExpression(Expression.Parse($"{TurnPath.DIALOGEVENT}.name == '{this.Event}'"), base.GetExpression());
return Expression.AndExpression(Expression.Parse($"{TurnPath.DialogEvent}.name == '{this.Event}'"), base.GetExpression());
}
}
}

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

@ -63,7 +63,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Conditions
throw new ArgumentNullException(nameof(this.Intent));
}
var intentExpression = Expression.Parse($"{TurnPath.RECOGNIZED}.intent == '{this.Intent.TrimStart('#')}'");
var intentExpression = Expression.Parse($"{TurnPath.Recognized}.intent == '{this.Intent.TrimStart('#')}'");
// build expression to be INTENT AND (@ENTITY1 != null AND @ENTITY2 != null)
if (this.Entities.Any())
@ -72,7 +72,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Conditions
intentExpression,
Expression.AndExpression(this.Entities.Select(entity =>
{
if (entity.StartsWith("@") || entity.StartsWith(TurnPath.RECOGNIZED, StringComparison.InvariantCultureIgnoreCase))
if (entity.StartsWith("@") || entity.StartsWith(TurnPath.Recognized, StringComparison.InvariantCultureIgnoreCase))
{
return Expression.Parse($"exists({entity})");
}
@ -86,8 +86,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Conditions
protected override ActionChangeList OnCreateChangeList(ActionContext actionContext, object dialogOptions = null)
{
var dcState = actionContext.GetState();
var recognizerResult = dcState.GetValue<RecognizerResult>($"{TurnPath.DIALOGEVENT}.value");
var recognizerResult = actionContext.State.GetValue<RecognizerResult>($"{TurnPath.DialogEvent}.value");
if (recognizerResult != null)
{
var (name, score) = recognizerResult.GetTopScoringIntent();

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

@ -29,7 +29,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Debugging
// try to avoid regenerating Identifier values within a breakpoint
if (CachedData == null)
{
CachedData = DialogContext.GetState().GetMemorySnapshot();
CachedData = DialogContext.State.GetMemorySnapshot();
}
return CachedData;
@ -44,6 +44,6 @@ namespace Microsoft.Bot.Builder.Dialogs.Debugging
public override string ToString() => Name;
object ICodePoint.Evaluate(string expression) => DialogContext.GetState().GetValue<object>(expression);
object ICodePoint.Evaluate(string expression) => DialogContext.State.GetValue<object>(expression);
}
}

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

@ -1,14 +0,0 @@
namespace Microsoft.Bot.Builder.Dialogs
{
public class ScopePath
{
public const string USER = "user";
public const string CONVERSATION = "conversation";
public const string DIALOG = "dialog";
public const string DIALOGCLASS = "dialogclass";
public const string THIS = "this";
public const string CLASS = "class";
public const string SETTINGS = "settings";
public const string TURN = "turn";
}
}

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

@ -7,6 +7,7 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs.Debugging;
using Microsoft.Bot.Builder.Dialogs.Memory;
using static Microsoft.Bot.Builder.Dialogs.Debugging.DebugSupport;
namespace Microsoft.Bot.Builder.Dialogs
@ -30,8 +31,9 @@ namespace Microsoft.Bot.Builder.Dialogs
Dialogs = dialogs ?? throw new ArgumentNullException(nameof(dialogs));
Context = turnContext ?? throw new ArgumentNullException(nameof(turnContext));
Stack = state.DialogStack;
State = new DialogStateManager(this);
ObjectPath.SetPathValue(turnContext.TurnState, TurnPath.ACTIVITY, Context.Activity);
ObjectPath.SetPathValue(turnContext.TurnState, TurnPath.Activity, Context.Activity);
}
/// <summary>
@ -126,6 +128,14 @@ namespace Microsoft.Bot.Builder.Dialogs
}
}
/// <summary>
/// Gets or sets the DialogStateManager which manages view of all memory scopes.
/// </summary>
/// <value>
/// DialogStateManager with unified memory view of all memory scopes.
/// </value>
public DialogStateManager State { get; set; }
/// <summary>
/// Starts a new dialog and pushes it onto the dialog stack.
/// </summary>
@ -561,7 +571,7 @@ namespace Microsoft.Bot.Builder.Dialogs
Stack.RemoveAt(0);
// set Turn.LastResult to result
ObjectPath.SetPathValue(this.Context.TurnState, TurnPath.LASTRESULT, result);
ObjectPath.SetPathValue(this.Context.TurnState, TurnPath.LastResult, result);
}
}
}

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

@ -7,8 +7,6 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AdaptiveExpressions.Memory;
using Microsoft.Bot.Builder.Dialogs.Declarative;
using Microsoft.Bot.Builder.Dialogs.Memory.Scopes;
using Newtonsoft.Json.Linq;
@ -19,7 +17,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Memory
/// MemoryScopes are named root level objects, which can exist either in the dialogcontext or off of turn state
/// PathResolvers allow for shortcut behavior for mapping things like $foo -> dialog.foo.
/// </summary>
public class DialogStateManager : IDictionary<string, object>, IMemory
public class DialogStateManager : IDictionary<string, object>
{
/// <summary>
/// Information for tracking when path was last modified.
@ -109,7 +107,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Memory
/// Version help caller to identify the updates and decide cache or not.
/// </summary>
/// <returns>Current version.</returns>
string IMemory.Version()
public string Version()
{
return version.ToString();
}

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

@ -3,7 +3,7 @@
using System.Collections.Generic;
using Microsoft.Bot.Builder.Dialogs.Memory.Scopes;
namespace Microsoft.Bot.Builder.Dialogs.Declarative
namespace Microsoft.Bot.Builder.Dialogs.Memory
{
public interface IComponentMemoryScopes
{

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

@ -1,9 +1,8 @@
// Licensed under the MIT License.
// Copyright (c) Microsoft Corporation. All rights reserved.
using System.Collections.Generic;
using Microsoft.Bot.Builder.Dialogs.Memory;
namespace Microsoft.Bot.Builder.Dialogs.Declarative
namespace Microsoft.Bot.Builder.Dialogs.Memory
{
/// <summary>
/// Interface for declaring path resolvers in the memory system.

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

@ -0,0 +1,64 @@
using System;
namespace Microsoft.Bot.Builder.Dialogs
{
public class ScopePath
{
/// <summary>
/// User memory scope root path.
/// </summary>
public const string User = "user";
/// <summary>
/// Conversation memory scope root path.
/// </summary>
public const string Conversation = "conversation";
/// <summary>
/// Dialog memory scope root path.
/// </summary>
public const string Dialog = "dialog";
/// <summary>
/// DialogClass memory scope root path.
/// </summary>
public const string DialogClass = "dialogclass";
/// <summary>
/// This memory scope root path.
/// </summary>
public const string This = "this";
/// <summary>
/// Class memory scope root path.
/// </summary>
public const string Class = "class";
/// <summary>
/// Settings memory scope root path.
/// </summary>
public const string Settings = "settings";
/// <summary>
/// Turn memory scope root path.
/// </summary>
public const string Turn = "turn";
[Obsolete]
public const string USER = "user";
[Obsolete]
public const string CONVERSATION = "conversation";
[Obsolete]
public const string DIALOG = "dialog";
[Obsolete]
public const string DIALOGCLASS = "dialogclass";
[Obsolete]
public const string THIS = "this";
[Obsolete]
public const string CLASS = "class";
[Obsolete]
public const string SETTINGS = "settings";
[Obsolete]
public const string TURN = "turn";
}
}

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

@ -11,7 +11,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Memory.Scopes
public class ClassMemoryScope : MemoryScope
{
public ClassMemoryScope()
: base(ScopePath.CLASS)
: base(ScopePath.Class)
{
this.IncludeInSnapshot = false;
}
@ -29,7 +29,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Memory.Scopes
var dialog = dc.FindDialog(dc.ActiveDialog.Id);
if (dialog != null)
{
return new ExpressionPropertyBinder(dc, dialog);
return new ReadOnlyObject(dialog);
}
}

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

@ -18,7 +18,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Memory.Scopes
/// Create new ConversationMemoryScope bound to ConversationState.
/// </summary>
public ConversationMemoryScope()
: base(ScopePath.CONVERSATION)
: base(ScopePath.Conversation)
{
}
}

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

@ -11,7 +11,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Memory.Scopes
public class DialogClassMemoryScope : MemoryScope
{
public DialogClassMemoryScope()
: base(ScopePath.DIALOGCLASS)
: base(ScopePath.DialogClass)
{
this.IncludeInSnapshot = false;
}
@ -29,12 +29,12 @@ namespace Microsoft.Bot.Builder.Dialogs.Memory.Scopes
var dialog = dc.FindDialog(dc.ActiveDialog.Id);
if (dialog is DialogContainer)
{
return new ExpressionPropertyBinder(dc, dialog);
return new ReadOnlyObject(dialog);
}
}
// Otherwise we always bind to parent, or if there is no parent the active dialog
return new ExpressionPropertyBinder(dc, dc.FindDialog(dc.Parent?.ActiveDialog?.Id ?? dc.ActiveDialog?.Id));
return new ReadOnlyObject(dc.FindDialog(dc.Parent?.ActiveDialog?.Id ?? dc.ActiveDialog?.Id));
}
public override void SetMemory(DialogContext dc, object memory)

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

@ -12,7 +12,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Memory.Scopes
public class DialogMemoryScope : MemoryScope
{
public DialogMemoryScope()
: base(ScopePath.DIALOG)
: base(ScopePath.Dialog)
{
}

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

@ -4,33 +4,28 @@ using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using AdaptiveExpressions.Properties;
namespace Microsoft.Bot.Builder.Dialogs.Memory.Scopes
{
/// <summary>
/// ExpressionPropertyBinder is a wrapper around any object to support expression binding.
/// ReadOnlyObject is a wrapper around any object to prevent setting of properties on the object.
/// </summary>
/// <remarks>
/// The ExpressionPropertyBinder provides read-only dictionary semantics for getting access to properties of an object.
/// If the value of a property is an IExpressionProperty, then the expression property will be evaluated using the DC.
/// Any complex objects that are returned from this are further wrapped in an ExpressionPropertyBinder, so that you can
/// Any complex objects that are returned from this are further wrapped in an ReadOnlyObject, so that you can
/// get ExpressionProperty binding for properties in a complex hierarchy of objects.
/// </remarks>
internal class ExpressionPropertyBinder : IDictionary<string, object>
internal class ReadOnlyObject : IDictionary<string, object>
{
private const string NOTSUPPORTED = "Changing dialog definitions at run time is not supported";
private readonly DialogContext dc;
private const string NOTSUPPORTED = "This object is readonly.";
private readonly object obj;
/// <summary>
/// Initializes a new instance of the <see cref="ExpressionPropertyBinder"/> class.
/// Initializes a new instance of the <see cref="ReadOnlyObject"/> class.
/// </summary>
/// <param name="dialogContext">dialog context for evalutation of expression properties.</param>
/// <param name="obj">object to wrap. Any expression properties on it will be evaluated using the dc.</param>
public ExpressionPropertyBinder(DialogContext dialogContext, object obj)
public ReadOnlyObject(object obj)
{
this.dc = dialogContext;
this.obj = obj;
}
@ -61,7 +56,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Memory.Scopes
public override bool Equals(object other)
{
if (other is ExpressionPropertyBinder esp)
if (other is ReadOnlyObject esp)
{
return this.obj.Equals(esp.obj);
}
@ -106,21 +101,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Memory.Scopes
public bool TryGetValue(string name, out object value)
{
if (ObjectPath.TryGetPathValue<object>(this.obj, name, out value))
{
if (value is IExpressionProperty ep)
{
value = ep.GetObject(dc.GetState());
if (!value.GetType().IsValueType && !(value is string))
{
value = new ExpressionPropertyBinder(this.dc, value);
}
}
return true;
}
return false;
return ObjectPath.TryGetPathValue<object>(this.obj, name, out value);
}
IEnumerator IEnumerable.GetEnumerator()
@ -133,7 +114,7 @@ namespace Microsoft.Bot.Builder.Dialogs.Memory.Scopes
object val;
if (TryGetValue(name, out val))
{
return val;
return new ReadOnlyObject(val);
}
return null;

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше