Udostępnij za pośrednictwem


DataContext.Log and Windows Phone

 

Among the many features that are compatible between Linq To SQL on desktop Windows and on Windows Phone is the support for capturing all of the generated SQL as it is being sent to the database. This can be a great way to both gain an understanding of how L2S works, as well as optimize query complexity. One of the challenges with using this feature is actually collecting the data. Extracting the log out of isostore can be problematic. Typically I like to visualize the output of my queries in the Debug Output Window. However the problem there is that there is no TextWriter in the platform that can write there. 

The solution is to simply wrap Debug.WriteLine() in your own TextWriter implementation.

I am sure this has been done many times before, but here is my implementation:

 namespace PhoneHelper
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Text;

    public class DebugStreamWriter : TextWriter
    {
        private const int DefaultBufferSize = 256;
        private StringBuilder _buffer;

        public DebugStreamWriter()
        {
            BufferSize = 256;
            _buffer = new StringBuilder(BufferSize);
        }

        public int BufferSize
        {
            get;
            private set;
        }

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

        #region StreamWriter Overrides
        public override void Write(char value)
        {
            _buffer.Append(value);
            if (_buffer.Length >= BufferSize)
                Flush();
        }

        public override void WriteLine(string value)
        {
            Flush();

            using(var reader = new StringReader(value))
            {
                string line; 
                while( null != (line = reader.ReadLine()))
                    Debug.WriteLine(line);
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
                Flush();
        }

        public override void Flush()
        {
            if (_buffer.Length > 0)
            {
                Debug.WriteLine(_buffer);
                _buffer.Clear();
            }
        }
        #endregion
    }
}

And the output:

image