botframework-sdk icon indicating copy to clipboard operation
botframework-sdk copied to clipboard

[.Net SDK, FB Messenger] Bot State Service

Open varunsethnsit opened this issue 8 years ago • 13 comments

Bot Info

  • SDK Platform: .Net
  • SDK Version: Latest
  • Active Channels: Facebook
  • Deployment Environment: All

Issue Description

The bot we have built relies heavily on state storage service. As we came across the fact that the state storage service is deprecating and you have to build a custom one https://aka.ms/yr235k, we registered a new Azure Table Service via changes in Global.asax.cs file with the remaining usage(s) of state storage as it is.

Some snippet of our code: StateClient stateClient = activity.GetStateClient(); BotData botData = new BotData(eTag: "*"); botData = await stateClient.BotState.GetPrivateConversationDataAsync(activity.ChannelId, activity.Conversation.Id, activity.From.Id);

However, it turns out that the state storage service used is still an older one, i.e. the bot state storage. Moreover, there are warnings all over code that StateClient is deprecated, and the state storage API(s) are obsolete. Please help understand how to use the latest storage services that help us continue with our deployed bot post the deprecation of services too.

Also, please note, ours is a non dialog based development for the bot and use state storage to model the conversation flow.

Expected Behavior

To use the latest storage service (Azure Table storage service).

Actual Results

Still using the bot framework storage service.

varunsethnsit avatar Mar 10 '18 17:03 varunsethnsit

Unfortunately, how to use the new Bot State is not properly documented. It actually is very simple. For the places where context is available you can use context.UserData.GetValue<>("")... I found this blog post covers it well: https://desflanagan.wordpress.com/2018/02/03/bot-framework-state-data-in-azure-table-storage/

abhishekkant avatar Mar 11 '18 09:03 abhishekkant

@abhishekkant, thanks for the response. However, the method shared shared in the blog pertains to Dialogs. However, our bot conversation is modelled around StateClient not Bot framework dialogs. Is there any known mechanism to use the same underlying API(S) GetConversationData, SetConversationData (in case they are getting deprecated along with the State Storage Service(s)) without re-writing the logic to connect to the data stores and build variants of State API(s) offered by Bot Framework.

varunsethnsit avatar Mar 11 '18 14:03 varunsethnsit

activity.GetStateClient(); itself is deprecated and will always use the deprecated default state client, not any custom state you have implemented. Are you trying to access/set state data in the messages controller?

JasonSowers avatar Mar 12 '18 15:03 JasonSowers

@JasonSowers yes, we are using SetPrivateConversationData and other State related API's to store and retrieve data/values across messages.

varunsethnsit avatar Mar 12 '18 19:03 varunsethnsit

@varunsethnsit, See my snippet below, when in the messages controller without the context object this is how you would read/write to the state databags. Like I said, the GetStateClient will only use the the default state client. so this will not work if you have implemented your own state client.

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

                    var privateConversationData = await botDataStore.LoadAsync(key, BotStoreType.BotPrivateConversationData, CancellationToken.None);

                    //set data
                    privateConversationData.SetProperty("key 1", "value1");
                    privateConversationData.SetProperty("key 2", "value2");
                    //get data
                    privateConversationData.GetProperty<string>("key 1");
                    privateConversationData.GetProperty<string>("key 2");

                    await botDataStore.SaveAsync(key, BotStoreType.BotUserData, privateConversationData, CancellationToken.None);
                    await botDataStore.FlushAsync(key, CancellationToken.None);
                }

JasonSowers avatar Mar 12 '18 20:03 JasonSowers

@JasonSowers What about conflicts with ETag ?

If I write something to UserData with IBotDataStore while running the bot, I end up with a HTTP 412 Precondition Failed The bot tries to write its own UserData but as it has been changed in the meantime, it crashes.

I know that you can change the Etag policy to LastWriteWins but it means that writing with IBotDataStore will never work while the bot is running... (all changes will be overwritten)

Any way to have a reliable writing to the bot state without having conflicts and without having an IDialogContext ?

TimLariviere avatar Apr 09 '18 10:04 TimLariviere

@TimLariviere

this using block: using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity))

Should be disposed before calling await Conversation.SendAsync(activity, () => new ExcelBotDialog());

Dialogs use the state service internally. You are seeing precondition failed exceptions because you are manually manipulating state, then the dialog is also manipulating state within the same scope.

EricDahlvang avatar Apr 09 '18 20:04 EricDahlvang

@EricDahlvang

So basically, it means I should never (in a dialog) manually manipulate state with IBotDataStore and instead use IDialogContext.UserData? IBotDataStore being usable only outside of a conversation.

TimLariviere avatar Apr 10 '18 06:04 TimLariviere

@TimLariviere Correct.

EricDahlvang avatar Apr 10 '18 18:04 EricDahlvang

@JasonSowers This makes sense - The part I'm struggling with is how to best handle updating a user data from some other service. My scenario is that I'm wanting the website that is hosting my webclient to send an event to my bot (via direct line) including my user's information. This is working, but the user info is not coming through to the real user because the Address.FromActivity(activity) has the context of my back channel event. Do I just have to fake out this out to include the UserId? I was thinking there would be a bit more straight forward way to load the state data based on a conversationId/userId.

Update - I can work around this by simply storing/retrieving data from the conversation data, which works in this case because its a single user conversation. This might be intentional to prevent anyone from updating user data, but I could see this being very useful for back channel updates.

ukphillips avatar Jun 13 '18 18:06 ukphillips

@ukphillips I'm not sure I follow, but that may be because I have never tried to implement what you are describing. Could you open a new issue with a minimum sample so we can take a look? I will be out for a couple weeks, but someone should be able to assist you with this.

JasonSowers avatar Jun 13 '18 23:06 JasonSowers

Sure, so let's say on the page that is hosting my bot, I want initiate my chat serverside to get a token (rather than using my secret for the webchat), and I also take the liberty since I have my conversationId and token to send over the associated useful information for that conversation:


            using (var tokenClient = new HttpClient())
            {
                tokenClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "REDACTED SECRET");
                var tokenResult = await tokenClient.PostAsync("https://directline.botframework.com/v3/directline/conversations", null);
                tokenResult.EnsureSuccessStatusCode();

                var tokenJson = await tokenResult.Content.ReadAsStringAsync();

                token = JObject.Parse(tokenJson)["token"].ToString();
                conversationId = JObject.Parse(tokenJson)["conversationId"].ToString();
            }
var client = new DirectLineClient(token);

            var result = await client.Conversations.PostActivityAsync(conversationId, new Microsoft.Bot.Connector.DirectLine.Activity()
            {
                Name = "SpecialEvent",
                From = new Microsoft.Bot.Connector.DirectLine.ChannelAccount()
                {
                    Id = "Hoster",
                    Name = "BotHoster"
                },
                Type = Microsoft.Bot.Connector.DirectLine.ActivityTypes.Event,
                Text = "Recieved UserInfo",
                Value = JsonConvert.SerializeObject(new {
			userDepartment: "Finance"
                 })
            });

so at this point before my webchat is even rendered I'm seeding the conversation with the stuff I need. In the bot though when I receive this seed event:

            {
                if (activity.Name == "SpecialEvent")
                {
                    using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity))
                    {
                        var botDataStore = scope.Resolve<IBotDataStore<BotData>>();
                        var key = Address.FromActivity(activity);
                        
                        var userData = await botDataStore.LoadAsync(key, BotStoreType.BotUserData, CancellationToken.None);
                        var convoData = await botDataStore.LoadAsync(key, BotStoreType.BotConversationData, CancellationToken.None);

                        var deptJson = activity.Value.ToString();
                        var userDept= JObject.Parse(deptJson)["userDepartment"].ToString();

                        //set data for the conversation
                        convoData.SetProperty("UserDept", userDept);
                        userData .SetProperty("UserDept", userDept);

                        await botDataStore.SaveAsync(key, BotStoreType.BotConversationData, convoData, CancellationToken.None);
                        await botDataStore.SaveAsync(key, BotStoreType.BotUserData, userData , CancellationToken.None);
                        await botDataStore.FlushAsync(key, CancellationToken.None);
                    }
                }
            }

so after this event is received when the web chat client starts up, I retrieve look up the userData, and it is null, but the conversation data has the department stored in it. I would guess when I go to load the BotUserData it scopes differently based on the store type and the key contents. Which makes sense, things in the conversation all participants would have access to etc. Since the event activity did not come from the user (From property), it seems like it's not storing it with the right key for later user retrieval.

ukphillips avatar Jun 15 '18 12:06 ukphillips

@ukphillips would you mind opening a new issue with this information for tracking purposes? I'm going to close this issue as the original issue was resolved.

JasonSowers avatar Jun 25 '18 15:06 JasonSowers