Project

Profile

Help

RE: Trouble When I use Console.SetOut and Console.SetError » Program.cs

Daniel Langdon, 2013-10-28 19:48

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace SaxonOutputBug
{
class Program
{
static void Main(string[] args)
{
// Cache the default Console TextWriter so we can use it again later.
TextWriter defaultWriter = Console.Out;

// Create a RecordingTextWriter and set it to be used for Console.Out and Console.Error
RecordingTextWriter writer = new RecordingTextWriter();
Console.SetOut(writer);
Console.SetError(writer);

// Perform some operations that will write to the Console, which has been set to the RecordingTextWriter.
performOperation();

// Now that everything is done, set Console.Out back to the default value and display the result:
Console.SetOut(defaultWriter);
Console.WriteLine("The RecordingTextWriter object recorded the following string:\n" + writer.Record.ToString());
}

private static void performOperation()
{
// Will record to the RecordingTextWriter class
Console.WriteLine("I'm writing on the default Console. Next, I want to see what Saxon writes on the default Console.");

// Next, create some Saxon classes and make them dump errors on the Console.
try
{
Saxon.Api.Processor processor = new Saxon.Api.Processor();
XmlDocument invalidXsltDocument = new XmlDocument();
invalidXsltDocument.LoadXml(@"<xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform""><xsl:template match=""invalidFunctionCall()""></xsl:template></xsl:stylesheet>");
Saxon.Api.XdmNode xsltInput = processor.NewDocumentBuilder().Build(invalidXsltDocument);
Saxon.Api.XsltCompiler xsltCompiler = processor.NewXsltCompiler();
Saxon.Api.XsltExecutable xsltExecutable = xsltCompiler.Compile(xsltInput);
}
catch (Exception ex)
{
Console.Error.WriteLine("Oh no! There was an error!");
Console.Error.WriteLine(ex.ToString());
}
}
}

public class RecordingTextWriter : TextWriter
{
public StringBuilder Record { get; private set; }

public RecordingTextWriter()
{
Record = new StringBuilder();
}

// Override Write and WriteLine so that the values recorded go to the Record StringBuilder.
public override void Write(string value)
{
Record.Append(value);
}
public override void WriteLine(string value)
{
Record.AppendLine(value);
}
public override void WriteLine()
{
Record.AppendLine();
}

public override Encoding Encoding
{
get { throw new NotImplementedException(); }
}
}
}
    (1-1/1)