Threadsafe Sql logging in Linq2Sql

This is a very handy thing to do on the backend on your data model Projects…

First create your DBContext through a wrapper.

    public static MyDataContext2 DBContext([CallerMemberName] string memberName = "")
    {
      var db = new MyDataContext2 {CommandTimeout = 2000};
      db.Connection.Open();
      //db.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
#if LOGTSQL
      db.Connection.Disposed += Connection_Disposed;
      _tw.WriteLineAsync("Starting time: " + DateTime.Now.ToString() + " " + memberName);
      _tw.WriteLineAsync("__________________________________________________");
      db.Log = _tw;
#endif
      return db;
    }

Then ensure you have a synchronized TextWriter for your entire debugging/execution session:

#if LOGTSQL
    private static TextWriter GetThreadSafeTextWriter()
    {
      var tmpPath = Environment.ExpandEnvironmentVariables("%TEMP%");
      var myTmpPath = Path.Combine(tmpPath, "_MyApp");
      if (!Directory.Exists(myTmpPath))
      {
        Directory.CreateDirectory(myTmpPath);
      }

      var fName = Path.Combine(myTmpPath, "LOGSQL_" + DateTime.Now.ToString("yyy-MM-dd_HHmmss") + ".txt");
      var ret = TextWriter.Synchronized(new StreamWriter(fName, true));

      return ret;
    }
    private static TextWriter _tw = GetThreadSafeTextWriter();
    private static void Connection_Disposed(object sender, EventArgs e)
    {
      _tw.FlushAsync();
    }
#endif

HowTo read the Windows EventLog with a Linq query.

Tags

This query extracts all the “Login” and “Logout” events for the given period. Nice if you want to see the usage of your computer.

var el = new EventLog(“System”);
var entries = (

from entry in el.Entries.Cast<EventLogEntry>()
where (entry.InstanceId == 7001 || entry.InstanceId == 7002) &&
entry.Source == “Microsoft-Windows-Winlogon” &&
entry.TimeWritten > start && entry.TimeWritten < end
orderby entry.TimeWritten
group entry by entry.TimeWritten.Date into g
select new { TheDate = g.Key, DayEntries = g }).ToList();