Intercept writes to Debug windows and transform if it's XML?

sleelialpbase

New Member
I have an application that relies on some 3rd party components. These 3rd party components have a class with a \[code\]public TextWriter Log{ get; set; }\[/code\] that push XML (actually it's the class \[code\]Microsoft.SharePoint.Linq.DataContext\[/code\], but my question is wider than this class).I want to intercept this writes to push them in the debug window of Visual Studio.I have been able to do that by creating a custom \[code\]TextWriter\[/code\] that forward text to the debugger window. This works as expected.My problem is that the produced XML is quite difficult to read, as it's one-lined. So I want to intercept the writes to this text writer to format XML indented.To do this, I have tweak my writer like that :\[code\]public override void Write(byte[] buffer, int offset, int count){ string messageToWrite = System.Text.Encoding.Unicode.GetString(buffer, offset, count); try { // try to convert the one-lined XML to indented XML, for better readability messageToWrite = System.Xml.Linq.XElement.Parse(messageToWrite).ToString( System.Xml.Linq.SaveOptions.None ); } catch { } System.Diagnostics.Debug.Write(messageToWrite);}\[/code\]This code try to create an \[code\]XElement\[/code\] instance. If it succeed, it writes the content of the \[code\]XElement\[/code\]. It not, it fall back to a direct write of the content.This is working but with limitations :[*]If the text is not XML, it creates some FirstChanceException that are noisy in the debug window.[*]If the Xml content is larger than the buffer, it will also produces errors as the messageToWrite will contain partial XML content.Is there a better and more reliable way to intercept this Xml?
 
Back
Top