Azure Bot State Data Store in Azure Cosmos db

In previous post here explained how bot manage state data in memory cache.Now I have extended this example here to store state data in azure cosmos db.

Few changes in code are required.Just add few  c#  lines  in StateDialog.cs

//Set conversion data
dialogContext.UserData.SetValue("patientname", patiantName.Text);

//Set conversion  data
dialogContext.ConversationData.SetValue("address", patiantAddress.Text);

//Set PrivateConversationData  data
dialogContext.PrivateConversationData.SetValue("patientMedicalHistory", medicalHistory.Text);

  1. Add nuget package ref of Microsoft.Bot.Builder.Azure in project
  2. Create Azure cosmos db instance here

Then click on create Cosmos Db and fill some details ….

Fire Create button and it will create cosmos db instance for you ..

Write down URI and key strings as shown in above pic and save somewhere so we need to update these key as a DocumentDbAuthKey and URI  as DocumentDbServiceEndpoint in web.config.

<add key=”DocumentDbServiceEndpoint” value=”” />
<add key=”DocumentDbAuthKey” value=”cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx” />

3.Change the Global.asax.cs  

Add the below code there to connect the azure cosmos db :

protected void Application_Start()
   Uri docDbServiceEndpoint = new Uri(ConfigurationManager.AppSettings["DocumentDbServiceEndpoint"]);
   string docDbEmulatorKey = ConfigurationManager.AppSettings["DocumentDbAuthKey"];
   var builder = new ContainerBuilder();
   builder.RegisterModule(new AzureModule(Assembly.GetExecutingAssembly()));
   var store = new DocumentDbBotDataStore(docDbServiceEndpoint, docDbEmulatorKey);
   builder.Register(c => store).Keyed<IBotDataStore<BotData>>(AzureModule.Key_DataStore)

4.Build the solution and run bot in emulator and reply to bot messages ..

Emulator messages

5.Here we are saving patient name as a user data ,address info as public conversation info and Medical history as private conversation info. Lets check all these information stored in cosmos db..

Public state data(address) stored in cosmos document:

Private state data(Patient Medical History) stored in cosmos document:



User state data(Patient name) stored in cosmos document:

User bot state


Find working code here  Download

Just replace cosmos db key and Uri and code should work……….

Good luck!!

Leave a Reply

Your email address will not be published. Required fields are marked *