Archive for July, 2008

LINQ to SQL log to debug window, file, memory or multiple writers

The Log property on a LINQ to SQL data context takes a TextWriter and streams out details of the SQL statements and parameters that are being generated and sent to the server.

Normally in examples you will see Console.Out being assigned to it which is fine for small demos and sandboxes but sooner or later you’ll want access to it in Windows or web applications. Here are some examples of how to redirect TextWriter output such as the DataContext log to other destinations.

Github has the latest version of ActionTextWriter etc.

To the output/debug window

The output/debug window mechanism actually uses a listener mechanism and so doesn’t actually directly expose a TextWriter interface however we can simply wrap up Debug.Write in something that does and use that instead:

class DebugTextWriter : System.IO.TextWriter {
   public override void Write(char[] buffer, int index, int count) {
       System.Diagnostics.Debug.Write(new String(buffer, index, count));
   }

   public override void Write(string value) {
       System.Diagnostics.Debug.Write(value);
   }

   public override Encoding Encoding {
       get { return System.Text.Encoding.Default; }
   }
}

To use it then simply:

myDataContext.Log = new DebugTextWriter();

To a file

#if DEBUG
   db.Log = new System.IO.StreamWriter("linq-to-sql.log") { AutoFlush = true };
#endif

If you wish to not overwrite the existing log file then change the constructor to include the parameter true after the filename. Bear in mind this log file can get very large and slow down your application with all that extra writing to disk and could well reveal information you’d rather wasn’t persisted there so the DEBUG conditional is recommended.

To memory

#if DEBUG
   var sw = new System.IO.StringWriter();
   db.Log = sw;
#endif

You will be able to examine sw or call ToString() on it to see the contents. Again this is not recommended for production as it will cause a lot of memory consumption as the StringWriter gets larger and larger.

To multiple writers

Here is a small useful class that lets you send the results intended for a TextWriter off into multiple writers.

class MulticastTextWriter : TextWriter {
    private readonly IList<TextWriter> textWriters;

    public MulticastTextWriter()
        : this(new List<TextWriter>()) {
    }

    public MulticastTextWriter(IList<TextWriter> textWriters) {
        this.textWriters = textWriters;
    }

    public void Add(TextWriter textWriter) {
        lock (textWriters)
            textWriters.Add(textWriter);
    }

    public bool Remove(TextWriter textWriter) {
        lock (textWriters)
            return textWriters.Remove(textWriter);
    }

    public override void Write(char[] buffer, int index, int count) {
        lock (textWriters)
            foreach (TextWriter textWriter in textWriters)
                textWriter.Write(buffer, index, count);
    }

    public override Encoding Encoding {
        get { return System.Text.Encoding.Default; }
    }
}

So if you wanted to output to a log and also to the debug window, you would use it like this (again recommended only for debugging):

   MulticastTextWriter mw = new MulticastTextWriter();
   mw.Add(new DebugTextWriter());
   mw.Add(new System.IO.StreamWriter("linq-to-sql.log") { AutoFlush = true };
   db.Log = mw;

Anything you want

To wrap things up here is a small TextWriter that lets you go off and do whatever you like with the string via the Action delegate.

class ActionTextWriter : TextWriter {
    private readonly Action<string> action;

    public ActionTextWriter(Action<string> action) {
        this.action = action;
    }

    public override void Write(char[] buffer, int index, int count) {
        Write(new string(buffer, index, count));
    }

    public override void Write(string value) {
        action.Invoke(value);
    }

    public override Encoding Encoding {
        get { return System.Text.Encoding.Default; }
    }
}

So if you wanted to output all log information to say a WinForms message box a tiny lambda expression gets you there:

   db.Log = new ActionTextWriter(s => MessageBox.Show(s));

Have fun!

[)amien

LINQ to SQL T4 template reloaded

A newer version of this LINQ to SQL template is available.

The topic of modifying the code generation phase of LINQ to SQL comes up quite often and the limited T4 template I published here last month was good at showing the potential but wasn’t a practical replacement for the code generation phase.

I am please to make available the next version, which now…

  • Runs from the DBML therefore keeping the designer in the loop
  • Generate all the attributes for columns and tables including UpdateCheck, IsDbGenerated etc.
  • Supports associations including those with a foreign key
  • Generates appropriate attributes and code for both serialization modes

In short it generates code that is now functionally equivalent to SQL Metal with the following caveats:

  • C# only – VB.NET can be added if there is some interest
  • Stored procedures – not yet supported
  • Table inheritance – incomplete
  • DBML changes require you open and re-save the T4 template so it regenerates the code
  • Unidirectional serialization requires you add System.Runtime.Serialization to your project references (thanks Roger!)

To use the template :

  • Extract the archive and add the two files to your project
  • Right-click on the L2ST4.tt file, choose Properties and set the Custom Tool to blank
  • Rename DataClasses1.tt to the same name as your DBML file (but keeping the .tt extension) and open it
  • Click save and watch a freshly generate C# DataContext pop out
  • Switch off the LINQ to SQL designer generated C# by either setting the Custom Tool on the DBML to blank or setting the Build Action on the generated C# to None.

L2ST4.tt contains a lightweight wrapper around the DBML which is processed using LINQ to XML making the template easier to work with and providing a central for naming rules etc.

This code should be treated as a sample and hasn’t received much testing yet so feel free to leave comments or feedback here.

Some places you could take this template:

  • Generate an interface for your data context to improve mocking
  • Alternative naming and defaults
  • Splitting output into multiple files
  • New languages
[)amien

MobileMe up and down at me.com

MobileMeMe.com was up, briefly, just long enough for me to grab my usual handle and get the confirmation message in fact.

I did get a brief glimpse of the UI complete with a Finder-like view of various folders once I clicked past a warning about Internet Explorer 7 not being supported. Seconds later things stopped responding and then the original placeholder was back.

It’s no secret Apple have been using the SproutCore framework in producing Me.com and that while SproutCore isn’t tied to Ruby on Rails it seems likely Apple went with Rails given the lack of interest in WebObjects and more and more Rails articles turning up on ADC.

If they’ve gone down that route I’m hoping we’re not in for a ride like the Rails powered Twitter one takes us on. Despite being relatively simple functionality it has been unable to cope with the demand and ability to scale which means downtime, slowness and features being switched off are regularly observed.

They are using WebObjects after all so expect some WebObjects and SproutCore integration love soon.

As an aside I’m in the US the week after next to meet my team and attend some training and will try and grab an iPhone 3G whilst there if not already sold out. Given that I’m only in Canada for 3 more months I don’t want to be trying to escape Roger’s expensive 3-year contract so soon.

[)amien

From the vaults of Twitter

I don’t normally republish my Tweets but are my highlights.

damienguard:
Methods returning "this" is a hack for fluency. Let’s get ".." added to the C# compiler to operate on previous object. a.This()..That()

lazycoder:
@damienguard I can’t decide if that’s genius or insanity. Should we add the "~" operator to refer back to the top of the inherit. chain? ;)

LostInTangent:
@damienguard I’ve started using Envy Code R for most of my applications (not just VS) and I have to say I’m loving it.

damienguard:
@LostInTangent: Envy Code R PR8 soon – Greek chars, improved hinting and some glyph revisions subscript/fractions & *96 redone.

damienguard:
Statically typed languages are not flexible enough to develop dynamically linked libraries.

damienguard:
Renaming your wifi router StupidRouter does not alas shame it into being more reliable.

damienguard:
@command_tab: Am I the only one who finds paying for pretty UI’s to leverage free software that took much more effort to develop offensive?

damienguard:
Just took delivery on my Alps-switched keyboard… feels good so far… but let’s see if co-workers complain about the noise.

Plip:
@damienguard I CAN’T HEAR MYSELF THINK FOR THAT INFERNAL CLICKING !

damienguard:
@lancefisher The alps keyboard was from DSI USA… but don’t order one, terrible 2-key limits prevent fast typing.

damienguard:
Apple should add hobbyist to its OS X line-up. Make kernel easier to switch, remove the h/w lockdown and no support.

damienguard:
Standard windows font smoothing’s real problem is lack of scales. Convert a ClearType rendering to greyscale in Photoshop…

[)amien