/// <summary> /// Creates a file containing the source code and /// the console output of the /// specified example. /// </summary> /// <param name="codeExampleInfo"> /// The info about the code example under study. /// </param> /// <remarks> /// <para> /// The is created in the same directory containing the source /// code file, and its path is obtained by adding <c>".txt"</c> to /// the file path. /// </para> /// </remarks> private static void CreateExampleSourceAndOutputFile( CodeExampleInfo codeExampleInfo) { string path = codeExampleInfo.SourceCodePath; List <string> lines = new List <string>(); string sourceCode = null; using (StreamReader reader = new StreamReader(path)) { sourceCode = reader.ReadToEnd(); } sourceCode = codeExampleInfo.Language.RemoveICodeExampleReferences(sourceCode); string line; StringReader sourceCodeReader = new StringReader(sourceCode); while ((line = sourceCodeReader.ReadLine()) != null) { lines.Add(line); } string commentSymbol = codeExampleInfo.Language.CommentSymbol; StringReader stringReader = new StringReader(codeExampleInfo.Output); using (StreamWriter writer = new StreamWriter(path + ".txt", false, new UTF8Encoding(false))) { for (int i = 0; i < lines.Count; i++) { writer.WriteLine(lines[i]); } writer.WriteLine(); writer.WriteLine(commentSymbol + "Executing method Main() produces the following output:"); writer.WriteLine(commentSymbol); while (true) { line = stringReader.ReadLine(); if (line != null) { writer.WriteLine(commentSymbol + line); } else { break; } } } }
/// <summary> /// Executes the specified example. /// </summary> /// <param name="codeExampleInfo"> /// The info about the code example to be executed. /// </param> private static void Execute( CodeExampleInfo codeExampleInfo) { var obj = Activator.CreateInstance(codeExampleInfo.Type); StringWriter stringWriter = new StringWriter(); var defaultOut = Console.Out; Console.SetOut(stringWriter); try { codeExampleInfo.Type.GetMethod("Main").Invoke(obj, null); codeExampleInfo.ExitCode = 0; } catch (Exception e) { codeExampleInfo.Error = e.InnerException.Message; codeExampleInfo.ExitCode = -1; } codeExampleInfo.Output = stringWriter.ToString(); Console.SetOut(defaultOut); }