Я создал бота с помощью Microsoft Boframework C # V4 SDK, и он работает хорошо. Теперь я хочу сохранить сообщения беседы бота и пользователей в базе данных SQL Azure. Как я могу подключиться и записать эти сообщения в базу данных SQL Azure.
Я уже пробовал это с SDK V3. В SDK V3 я создал класс SqlActivityLogger, вызвал его из файла Global.asax и открыл там соединение Sql. И он успешно регистрирует сообщения разговоров в базе данных SQL Azure. Теперь, как я могу сделать то же самое в SDK V4, используя C #.
SqlActivityLogger.cs
using Microsoft.Bot.Builder.History;
using Microsoft.Bot.Connector;
using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Threading.Tasks;
namespace Robo
{
public class SqlActivityLogger : IActivityLogger
{
SqlConnection connection;
public SqlActivityLogger(SqlConnection conn)
{
this.connection = conn;
}
public async Task LogAsync(IActivity activity)
{
string fromId = activity.From.Id;
string toId = activity.Recipient.Id;
string message = activity.AsMessageActivity().Text;
// DateTime DateTimeNow = DateTime.Now;
string insertQuery = "INSERT INTO RobosensusLog(fromId, toId, message) VALUES (@fromId,@toId,@message)";
// Passing the fromId, toId, message to the the user chatlog table
SqlCommand command = new SqlCommand(insertQuery, connection);
command.Parameters.AddWithValue("@fromId", fromId);
command.Parameters.AddWithValue("@toId", toId);
command.Parameters.AddWithValue("@message", message);
// command.Parameters.AddWithValue("@datetime", DateTime.Now);
// Insert to Azure sql database
command.ExecuteNonQuery();
Debug.WriteLine("Insertion successful of message: " + activity.AsMessageActivity().Text);
}
}
}
Global.asax
using Autofac;
using Microsoft.Bot.Builder.Dialogs;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Routing;
namespace Robo
{
public class WebApiApplication : System.Web.HttpApplication
{
SqlConnection connection = null;
protected void Application_Start()
{
//Setting up sql string connection
SqlConnectionStringBuilder sqlbuilder = new SqlConnectionStringBuilder();
sqlbuilder.DataSource = "Your data source";
sqlbuilder.UserID = "userid";
sqlbuilder.Password = "password";
sqlbuilder.InitialCatalog = "your catalog";
connection = new SqlConnection(sqlbuilder.ConnectionString);
connection.Open();
Debug.WriteLine("Connection Success");
Conversation.UpdateContainer(builder =>
{
builder.RegisterType<SqlActivityLogger>().AsImplementedInterfaces().InstancePerDependency().WithParameter("conn", connection);
});
GlobalConfiguration.Configure(WebApiConfig.Register);
}
protected void Application_End()
{
connection.Close();
Debug.WriteLine("Connection to database closed");
}
}
}