using Microsoft.Data.SqlClient; using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Diagnostics; using System.Diagnostics.Tracing; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp4 { // it the ability to create events. public class SqlClientListener : EventListener { public SqlClientListener() { using (StreamWriter wr = new StreamWriter("log.txt", true)) { wr.WriteLine("-----"); } } protected override void OnEventSourceCreated(EventSource eventSource) { // Only enable events from SqlClientEventSource. if (eventSource.Name.StartsWith("Microsoft.Data.SqlClient")) { // Use EventKeyWord 2 to capture basic application flow events. // See the above table for all available keywords. EnableEvents(eventSource, EventLevel.Verbose, (EventKeywords)2); } } // This callback runs whenever an event is written by SqlClientEventSource. // Event data is accessed through the EventWrittenEventArgs parameter. protected override void OnEventWritten(EventWrittenEventArgs eventData) { // Print event data. Debug.WriteLine(eventData.Payload[0]); using (StreamWriter wr = new StreamWriter("log.txt", true)) { wr.WriteLine(eventData.Payload[0]); } } } public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { using (new SqlClientListener()) using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["Azure_DB"].ConnectionString)) { txtResult.Text = "Connecting..."; //con.OpenAsync().Wait(); con.Open(); using (var cmd = con.CreateCommand()) { cmd.CommandText = @"SELECT SUSER_SNAME() AS CurrentLogin"; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { string login = Convert.ToString(reader["CurrentLogin"]); txtResult.Text += Environment.NewLine + "You have successfully logged on as: " + login; } } } con.Close(); txtResult.Text += Environment.NewLine + "Connection closed"; } } } }