【发布时间】:2019-04-08 08:35:12
【问题描述】:
我使用 Microsoft Boframework C# V4 SDK 创建了一个机器人,它运行良好。现在,我想将机器人和用户的对话消息存储在 Azure SQL 数据库中。如何在 Azure SQL 数据库中连接和记录这些对话消息。
我已经用 SDK V3 尝试过这个。在 SDK V3 中,我创建了一个 SqlActivityLogger 类并从 Global.asax 文件中调用它,并在那里打开了一个 Sql Connection。它正在成功地将对话消息记录到 Azure SQL 数据库中。现在如何使用 C# 在 SDK V4 中做同样的事情。
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);
}
}
}
全球.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");
}
}
}
【问题讨论】:
-
你能分享一下你到目前为止的尝试吗?
-
我提供了更多细节,请看一下。
标签: c# logging botframework