Search code examples
c#botframeworkbots

How to store user information to access in another dialog - Bot framework V3


I am facing a problem storing user profile in bot framework. With my bot I am using AAD authentication and storing the retrieved username in class

tokenstring = resultToken.AccessToken;
userName = resultToken.UserName;
Globalvariables.username = userName;

And try retrieving in another dialog something likeGlobalvariables.username but when two users accessing the bot simultaneously it is messing up completely. Is there an alternate way to do this?

I am using Bot framework v3 .

Below is another way I tried to get the information.

In Sign In dialog

StateClient stateClient = new StateClient(new MicrosoftAppCredentials(ConfigurationManager.AppSettings["MicrosoftAppId"], ConfigurationManager.AppSettings["MicrosoftAppPassword"]));
BotData userData = await stateClient.BotState.GetUserDataAsync(authContext.Activity.ChannelId, authContext.Activity.From.Id);
userData.SetProperty<string>("username", resultToken.UserName);

For retriving the stored user name in another Dialog

StateClient stateClient = new StateClient(new MicrosoftAppCredentials(ConfigurationManager.AppSettings["MicrosoftAppId"], ConfigurationManager.AppSettings["MicrosoftAppPassword"]));
BotData userData = await stateClient.BotState.GetUserDataAsync(context.Activity.ChannelId, context.Activity.From.Id);
context.UserData.SetValue("username", userData.GetProperty<string>("username"));  

But this seems depreciated and not working as expected .


Solution

  • As you have discovered, the StateClient methods are deprecated because they use the default state service which has been deprecated. However, the IDialogContext has IDataBag implementations that enable easy access for storing and retrieving information in .UserData, .PrivateConversationData and .ConversationData

    within SignIn dialog you should be able to store the Username via the IDialogContext like:

    context.UserData.SetValue("UserName", resultToken.UserName);
    

    Then access it within other dialogs:

    var userName = context.UserData.GetValueOrDefault("UserName", string.Empty);