The Microsoft Bot framework provides the IBotDataStore interface as a mechanism for storing stateful data. When you create a new Bot in Visual Studio, your application is configured by default to store data in memory using the InMemoryDataStore class.

You can see this setup in the following line of the Application_Start() method of  Global.asax.cs :

var store = new InMemoryDataStore();

This is fine for testing, but memory is fragile and temporary; so, you will want a more persistent way to store stateful data in production. You can see this by running the app we created in this article.

If we run the bot described in that article, we can connect to it with the Bot Framework Emulator; then, stop and re-start the app and connect again, as shown in Fig. 1

Fig. 1

Notice that all the stateful information is reset after the app restarts, because the app memory is flushed.

We can modify the app so that it saves stateful data to something more persistent, like Azure Storage. To do this, we must first create a new Azure storage account.

In the Azure Portal, create a new Storage account (Fig. 2). If you have never created an Azure storage account, you can find instructions here.

Fig. 2

Once the account is created, open the "Access keys" blade, as shown in Fig. 3.

Fig. 3

Copy either of the connection strings and save it. You will need to add it to your application.

In the Bot application, open the web.config file and paste the following anywhere directly inside the tag.

  name="BotAzureStorage" connectionString="StorageConnectionString" /> 

where StorageConnectionString is the connection string you copied from the Azure portal.

Open the Global.asax.cs file and find the following line:

var store = new InMemoryDataStore();

Replace this line with the following code:

var azureStorageConnectionString 
  = System.Configuration.ConfigurationManager.ConnectionStrings["BotAzureStorage"].ConnectionString; 
var store = new TableBotDataStore(azureStorageConnectionString);

Now, compile and run the application.

Use the Bot Emulator to connect to it. Stateful information will now be saved to a Microsoft Azure Storage table named "botdata".

Notice that as you start and stop the app, the stateful data remains the same, as shown in Fig. 4.

Fig. 4

In this article, I showed you how to save stateful data to an Azure Storage table.

You can find this code in the SavingStateToAzureDemo folder of the Bot-Framework-Demos on my GitHub page.