我正在尝试为 SQL Server 数据库项目创建一个 VS2010 扩展(托管 VSPackage)。
我想做的是从 Transact SQL 编辑器窗口捕获“查询执行”事件:
然后捕获 SQL 文本并在执行之前对其进行修改。到目前为止,我的代码处理打开文档时连接 Transact SQL 编辑器窗口(使用IVsRunningDocTableEvents
界面):
public int OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowFrame pFrame)
{
try
{
var marshalingWindowFrame = pFrame as WindowFrame.MarshalingWindowFrame;
if (marshalingWindowFrame != null)
{
var sqlScriptEditorControl =
marshalingWindowFrame.ViewHelper as
SqlScriptEditorControl;
if (sqlScriptEditorControl != null)
{
if (!sqlScriptEditorControl.IsConnected)
{
ReadConnectionInfoAndConnectEditor(sqlScriptEditorControl, docCookie);
}
}
}
}
catch (Exception exception)
{
Debug.WriteLine(exception);
}
return VSConstants.S_OK;
}
private void ReadConnectionInfoAndConnectEditor(SqlScriptEditorControl sqlScriptEditorControl, uint docCookie)
{
string documentName = GetDocumentMoniker(docCookie);
var document = _dte.Documents.OfType<Document>().FirstOrDefault(x => x != null && x.FullName == documentName);
if (document != null)
{
var p = document.ProjectItem.ContainingProject;
var hierarchy = ProjectToHierarchy(p);
var buildPropertyStorage = hierarchy as IVsBuildPropertyStorage;
if (buildPropertyStorage != null)
{
string sandboxTargetConnectionString;
buildPropertyStorage.GetPropertyValue("SandboxTargetConnectionString", "Debug", (uint)_PersistStorageType.PST_USER_FILE, out sandboxTargetConnectionString);
string sandboxTargetDatabase;
buildPropertyStorage.GetPropertyValue("SandboxTargetDatabase", "Debug", (uint)_PersistStorageType.PST_USER_FILE, out sandboxTargetDatabase);
var connectionStringBuilder = new SqlConnectionStringBuilder
{
ConnectionString = sandboxTargetConnectionString,
InitialCatalog = sandboxTargetDatabase,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
};
var uiConnectionInfo = new UIConnectionInfo
{
ServerName = connectionStringBuilder.DataSource,
ServerType = Microsoft.SqlServer.Management.UI.ConnectionDlg.SqlServerType.ServerType
};
var sqlConnection = new SqlConnection
{
ConnectionString = connectionStringBuilder.ConnectionString
};
sqlConnection.Open();
sqlScriptEditorControl.SetConnection(uiConnectionInfo, sqlConnection);
}
}
}
在这种情况下,我如何订阅“查询执行”事件?