add Delete function to BotState for parity with JavaScript

This commit is contained in:
John Taylor 2018-12-04 15:37:54 -08:00
Родитель 5b707fe2b7
Коммит 17b7722f92
2 изменённых файлов: 59 добавлений и 0 удалений

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

@ -119,6 +119,29 @@ namespace Microsoft.Bot.Builder
return Task.CompletedTask;
}
/// <summary>
/// Delete any state currently stored in this state scope.
/// </summary>
/// <param name="turnContext">The context object for this turn.</param>
/// <param name="cancellationToken">cancellation token.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task DeleteAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
{
if (turnContext == null)
{
throw new ArgumentNullException(nameof(turnContext));
}
var cachedState = turnContext.TurnState.Get<CachedBotState>(_contextServiceKey);
if (cachedState != null)
{
turnContext.TurnState.Remove(_contextServiceKey);
}
var storageKey = GetStorageKey(turnContext);
await _storage.DeleteAsync(new[] { storageKey }, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// When overridden in a derived class, gets the key to use when reading and writing state to and from storage.
/// </summary>

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

@ -725,6 +725,42 @@ namespace Microsoft.Bot.Builder.Tests
Assert.AreEqual("default-value", value2);
}
[TestMethod]
public async Task BotStateDelete()
{
var turnContext = TestUtilities.CreateEmptyContext();
turnContext.Activity.Conversation = new ConversationAccount { Id = "1234" };
var storage = new MemoryStorage(new Dictionary<string, JObject>());
// Turn 0
var botState1 = new ConversationState(storage);
(await botState1
.CreateProperty<TestPocoState>("test-name")
.GetAsync(turnContext, () => new TestPocoState())).Value = "test-value";
await botState1.SaveChangesAsync(turnContext);
// Turn 1
var botState2 = new ConversationState(storage);
var value1 = (await botState2
.CreateProperty<TestPocoState>("test-name")
.GetAsync(turnContext, () => new TestPocoState { Value = "default-value" })).Value;
Assert.AreEqual("test-value", value1);
// Turn 2
var botState3 = new ConversationState(storage);
await botState3.DeleteAsync(turnContext);
// Turn 3
var botState4 = new ConversationState(storage);
var value2 = (await botState4
.CreateProperty<TestPocoState>("test-name")
.GetAsync(turnContext, () => new TestPocoState { Value = "default-value" })).Value;
Assert.AreEqual("default-value", value2);
}
public class TestBotState : BotState
{
public TestBotState(IStorage storage)