BOT框架 - 使用Cosmos DB进行状态管理

时间:2018-04-10 13:25:34

标签: c# botframework state-management

我已使用Cosmos DB在我的BOT框架中启用了日志记录和状态管理,如下面的链接所示

Manage State using Cosmos DB

我在Global.ascx中添加了以下代码

rotected void Application_Start()
{
    Conversation.UpdateContainer(
        builder =>
        {
            builder.RegisterModule(new AzureModule(Assembly.GetExecutingAssembly()));
            // Bot Storage: register state storage for your bot
            var uri = new Uri(ConfigurationManager.AppSettings["DocumentDBUri"]);
            var key = ConfigurationManager.AppSettings["DocumentDBKey"];
            var store = new DocumentDbBotDataStore(uri, key);
            builder.Register(c => store)
                .Keyed<IBotDataStore<BotData>>(AzureModule.Key_DataStore)
                .AsSelf()
                .SingleInstance();
        });

    GlobalConfiguration.Configure(WebApiConfig.Register);
}

Azure文档数据库:

{
"id": "emulator:private52mgl3acgcke:default-user",
"botId": "lg3443gthi57gd",
"channelId": "emulator",
"conversationId": "52mgl3acgcke",
"userId": "default-user",
"data": {
    "ResumptionContext": {
        "locale": "en-US",
        "isTrustedServiceUrl": false
    },
    "DialogState": "H4sIAAAAAAAEAO1b22/bVBhPWsdNso6Oq7gMFgQMSlt3SZpeRjeWpOoI62VaOhCqquzYPklNHTv4HHdkjzzBy4TEI4J/ASHxDkICib+CVxB/RPk+20nTNG2c0BQX6ilfk/hcvsvvfN/vnHihcCgU2oML/+I1OgTio1VNsUxmlrmUM+Fla7pKrcnEB9RimmncSEvJlJSSZiYTeVvntkVvGNTmFtEnE3dtWdeUO7S+Ye5QaJmUy+n5zCxR07MzNJ2J4Dw/hjuOLxUMTi2D6Exa1mSYyv3zILm52bn9kkZ0s8Ja+rnfbBC2M5kYmA1bW8NgRIRxouyIZYtUKYs8JBpnw4Lw01CxzjitSnlT16nCYSYm3aYGtTRFWtEYP9qaQ9YXlnHsAJo/0MGJT+8UwaVE1x4R9PFEkZsWLRgQE0OhufpGvUaLtmWZFcLpxLr8MYTiHi1Ti8JtRPjpzIKvGIIlJqCIgBDw4zlKTmIFiiUNfMgiJaY9otHSrjssePpnv/klsL7b3 "
},
"_rid": "JnhaAKnGzgEJAAAAAAAAAA==",
"_self": "dbs/JnhaAA==/colls/JnhaAKnGzgE=/docs/JnhaAKnGzgEJAAAAAAAAAA==/",
"_etag": "\"00002f19-0000-0000-0000-5a56565655000\"",
"_attachments": "attachments/",
"_ts": 1523330900

}

  using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
            {
                var botDataStore = scope.Resolve<IBotDataStore<BotData>>();
                var key = new AddressKey()
                {
                    BotId = message.Recipient.Id,
                    ChannelId = message.ChannelId,
                    UserId = message.From.Id,
                    ConversationId = message.Conversation.Id,
                    ServiceUrl = message.ServiceUrl
                };
                var userData = await botDataStore.LoadAsync(key, BotStoreType.BotConversationData, CancellationToken.None);

                userData.SetProperty("userId", UserID);

                userData.SetProperty("DOB", DOB);

                BotData botdata = new BotData();


                await botDataStore.SaveAsync(key, BotStoreType.BotUserData, userData, CancellationToken.None);

现在,我想在我的州(Ex,name,email和DOB)中为用户添加自定义用户数据,并将其用于完整对话 - 我无法找到任何最好的方法来处理它。

(context.UserData.SetValue - 有效,但我希望它的状态客户端,而不是在cosmos DB中更新它)

context.UserData.SetValue("username", "John Smith");

1 个答案:

答案 0 :(得分:1)

无关,但您实际上可以将代码的var key部分更改为var key = Address.FromActivity(message);

使用下面的代码我得到屏幕截图中的结果有一些差异,其中一个是因为我没有使用代码BotData botdata = new BotData();中的这一行而且我还添加了这一行await botDataStore.FlushAsync(key, CancellationToken.None);我在global.asax

中拥有与您完全相同的代码
        if (activity.Type == ActivityTypes.Message)
        {

            var message = activity as IMessageActivity;
            using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
            {
                var botDataStore = scope.Resolve<IBotDataStore<BotData>>();
                var key = Address.FromActivity(message);

                ConversationReference r = new ConversationReference();
                var userData = await botDataStore.LoadAsync(key, BotStoreType.BotUserData, CancellationToken.None);

                userData.SetProperty("userId", "123");

                userData.SetProperty("DOB", "some date");

                await botDataStore.SaveAsync(key, BotStoreType.BotUserData, userData, CancellationToken.None);
                await botDataStore.FlushAsync(key, CancellationToken.None);
            }
            await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());

        }

我在cosmosDB中得到了这个结果 enter image description here

希望这有助于你

编辑4/12/2018

解决您的后续问题。为了使这个代码已经运行,你只需要检查密钥上是否存在值修改我给你的代码片段如下:

if (userData.GetProperty<string>("userId") == null)
{    
    userData.SetProperty("userId", "123");
    userData.SetProperty("DOB", "some date");
    await botDataStore.SaveAsync(key, BotStoreType.BotUserData, userData, CancellationToken.None);
    await botDataStore.FlushAsync(key, CancellationToken.None);
}

由于您无权访问上下文对象,因此每次都需要运行其余的代码来检查状态。

要回答关于用户关闭和重新打开窗口的其他问题,应将其保存到cosmosDB中,这应该不是问题。