Alok Rajasukumaran
Alok Rajasukumaran

Reputation: 381

Accessing Conversation data from Message Controller c#

I have been using the context.setvalue(); and context.TryGetvalue(); to store and receive data to different storages in Bot Framework.

I want to know how we can access this values from MessageController.cs

Already tried creating a New object, it don't work for me.

Upvotes: 3

Views: 3357

Answers (2)

D4RKCIDE
D4RKCIDE

Reputation: 3426

I found this post when searching for another answer I posted. I wanted anyone that comes here in the future to know the correct way to do this.

StateClient stateClient = activity.GetStateClient(); gets the Default state client only which is deprecated as of March 31st 2018. It has been replaced by an in-memory state store. If you have implemented your own state client (i.e. cosmosDB, Azure table storage, SQL, etc etc) the proper way to access state in the messages controller is something along the lines of this:

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);

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

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

Upvotes: 7

rposbo
rposbo

Reputation: 327

To get the conversation data you either need a reference to the context or get a state client from the activity.

Inside the Dialog you can use the context: http://robinosborne.co.uk/2016/08/08/persisting-data-within-a-conversation-with-botframeworks-dialogs/

Outside of a Dialog you can use the activity to get a state client:

StateClient stateClient = activity.GetStateClient();
BotData userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);
if (userData.GetProperty<bool>("SentGreeting"))
        // do something

https://docs.botframework.com/en-us/csharp/builder/sdkreference/stateapi.html

Hope that helps!

Upvotes: 5

Related Questions