C# Interactive Compiler Development

Introduction

This article explains the complete life cycle of making a custom interactive C# compiler much like the existing CSC.exe. It is hard to imagine such a custom C# interactive compiler kind of mechanism but this innovation could be constructed by employing the C# APIs of the open source project, referred to as Mono. The development life cycle of this mechanism is relatively sophisticated and we can extend its features to be operable on the Linux operating system also because the Mono APIs are implemented there. Hence, we shall illustrate the development process in a comprehensive way, along with the live demonstration of this C# interactive compiler.

Interactive Compiler

We have been primarily relying on the Visual Studio IDE to compile C# programming code where csc.exe typically handles the compilation related tasks. The .Net Framework suports a range of compilers for various programming languages to debug an application and generate an executable. But those 2 language compilation utilities interpret the entire application code file rather than a single code segment. This process is sometimes time-consuming and creating unnecessary overhead on the file system, even if in case of executing a very short code statement. We occasionally, need to execute 1 or 2 lines of code. For example, a calculating Math function and LINQ statements. So, the C# Interactive kind of mechanism is suitable that reflects immediate results and spares developers from the hectic Visual Studio compilation process such project creation and other configuration.

Mono especially, has been sponsoring a couple of interoperable projects that are not limited to a specific platform. It allows developers to use their development API and evolve it to build cross-platform support applications where the Linux operating system and other wide range of platform developer can also execute and run .NET applications. The C# interactive compiler mechanism is constructed on top of the Mono.CSharp library utilizing C# APIs. These APIs provide a C# compiler service that can be used to evaluate expressions and statements. Hence, the C# interactive shell allows dynamically evaluating C# programming code statements, as well as can be utilized for testing mini code fragments or writing scripts.

Essential


The C# interactive compiler code is typically developed using the C# language under the .Net 4.0 frameworks and classes that are responsible for providing custom compiler-related functionality, are referenced from Microsoft.CSharp.dll and Mono.ceil.dll.

Prototype

The C# interactive compiler operates through the command line, typically provides a command-prompt like mechanism where we enter C# code statements, much like console commands are entered and it will reflect interpreted the result. We don't need to suffix a semicolon in the code at the command line, as in C# code semantics, just write the code statement and press Enter.

development tool

This command line utility, however is able to compile a single-line or multiline C# code. We shall show how it works later in step-by-step format. Although such a mechanism can build in GUI form also, this is relatively easy to operate rather than the command line.

Getting Started

As we have noticed from the project prototypes, it would be a command line utility. Hence, create a Console based application as CsharpInterpreter.

Classes Blueprints

The C# Compiler design project is not limited to an entry class, rather its functionality is scattered in dozen of classes, some of them are static and abstract. It is not possible to explain each class implementation in detail. Hence, we are presenting the employed classes as diagram blueprints, by which one can easily get an idea of the project inner workings. Some classes are marked as abstract to make their reference into other classes, that again are inherited in other classes.

Classes Blueprints

Entry Point


The making of this project is embarking from the entry point Program class that is responsible from displaying a command shell and other messages. The backbone class of this project is an interactive class that contains the significant implementation of the custom compilation process and obviously, called from the entry point class.

  1. using System;  
  2. using System.Diagnostics;  
  3. using System.Reflection;  
  4. using System.Windows.Forms;     
  5.   
  6. namespace CsharpInterpreter  
  7. {  
  8.     class Program  
  9.     {  
  10.         static void Main(string[] args)  
  11.         {  
  12.             if (args.Length > 0 && args[0].Equals("--verbose", StringComparison.InvariantCultureIgnoreCase))  
  13.             {  
  14.                 Interactive.Context.VerboseTrace = true;  
  15.             }  
  16.             Trace.Listeners.Add(new ConsoleTraceListener());  
  17.               
  18.             Program.WriteWelcomeMessage();  
  19.             while (Interactive.Context.Continue)  
  20.             {  
  21.                 
  22.                 Console.Write("#:->");  
  23.                  
  24.                 string text = Console.ReadLine();  
  25.                 if (text == null)  
  26.                 {  
  27.                     return;  
  28.                 }  
  29.                 try  
  30.                 {  
  31.                     string text2 = Interactive.Interpret(text);  
  32.                       
  33.                     if (text2 != null)  
  34.                     {  
  35.                         Console.WriteLine(text2);  
  36.                           
  37.                     }  
  38.                     
  39.                 }  
  40.                 catch (TargetInvocationException ex)  
  41.                 {  
  42.                     Program.WriteExceptionMessage(ex.InnerException);  
  43.                 }  
  44.                 catch (Exception ex2)  
  45.                 {  
  46.                     Program.WriteExceptionMessage(ex2);  
  47.                 }  
  48.             }  
  49.         }  
  50.         private static void WriteWelcomeMessage()  
  51.         {  
  52.             Version version = Assembly.GetExecutingAssembly().GetName().Version;  
  53.             Console.WriteLine("---------------------------------------");  
  54.             Console.WriteLine("Tool Developed by Ajay Yadav\n");  
  55.             Console.WriteLine("Copyright (c) Cyberbrilliance, 2014.");  
  56.             Console.WriteLine("\n");  
  57.             Console.WriteLine("Help -- For Help");  
  58.             Console.WriteLine("clear-- For Clear Screen");  
  59.             Console.WriteLine("quit -- For quit");  
  60.             Console.WriteLine("---------------------------------------");  
  61.             Console.WriteLine();  
  62.         }  
  63.         private static void WriteExceptionMessage(Exception ex)  
  64.         {  
  65.             Console.WriteLine("Exception of type '" + ex.GetType().Name + "' was thrown: " + ex.Message);  
  66.             if (Interactive.Context.VerboseTrace)  
  67.             {  
  68.                 Console.WriteLine("StackTrace:");  
  69.                 Console.WriteLine(ex.StackTrace);  
  70.                 if (ex.InnerException != null)  
  71.                 {  
  72.                     Console.WriteLine("Inner Exception:");  
  73.                     Console.WriteLine(ex.InnerException.Message);  
  74.                     Console.WriteLine(ex.InnerException.StackTrace);  
  75.                 }  
  76.             }  
  77.           
  78.         }  
  79.     }  
  80. }  
The program entry point class also handles any unexpected occurrences of errors and maintains a proper log database for each activity. Since this is a command-line utility and a separate session is required after executing the main project file, we shall enter C# code statements to compile them inline. Hence it is mandatory to open a verbose mode through the command line as in the following:
  1. if (args.Length > 0 && args[0].Equals("--verbose", StringComparison.InvariantCultureIgnoreCase))  
  2. {  
  3.     Interactive.Context.VerboseTrace = true;  
  4. }  
Interpreter Class

The prime role of this class is to provide the C# custom provider from the CodeDom class and invoke the entered C# inline or multiline programming statements. This class is basically a custom grammar for this project that checks what kind of statements are entered by the user such as using, expression and generic statements.
  1. public static class Interactive  
  2. {  
  3.     private static readonly CodeDomProvider Compiler;  
  4.     public static exeContext Context;  
  5.     static Interactive()  
  6.     {  
  7.         Interactive.Compiler = CodeDomProvider.CreateProvider("C#");  
  8.         Interactive.Context = new exeContext();  
  9.     }  
  10.     public static void Reset()  
  11.     {  
  12.         Interactive.Context = new exeContext();  
  13.     }  
  14.     public static string Interpret(string sourceCode)  
  15.     {  
  16.         return sourceCode.CompileCodeSnippet().Invoke();  
  17.     }  
  18.     private static compiledCode CompileCodeSnippet(this string code)  
  19.     {  
  20.         if (Interactive.Context.MultiLine)  
  21.         {  
  22.             exeContext expr_11 = Interactive.Context;  
  23.             expr_11.MultiLineStatement += code;  
  24.             code = Interactive.Context.MultiLineStatement;  
  25.         }  
  26.         return code.Statement() || code.TypeMember();  
  27.     }  
  28.     private static compiledCode Statement(this string code)  
  29.     {  
  30.         return code.ExpressionStatement() || code.UsingStatement() || code.GenericStatement();  
  31.     }  
  32.     private static compiledCode UsingStatement(this string code)  
  33.     {  
  34.         compiledCode result = null;  
  35.         if (code.TrimStart(new char[0]).StartsWith("using "))  
  36.         {  
  37.             string text = code.TrimEnd(new char[0]);  
  38.             if (!text.EndsWith(";"))  
  39.             {  
  40.                 text += ";";  
  41.             }  
  42.             string usingStatement = text;  
  43.             string source = Interactive.Program(nullnullnullnull, usingStatement);  
  44.             custStatement statement = new custStatement(code, source.CompileFromSource());  
  45.             if (!statement.HasErrors)  
  46.             {  
  47.                 Interactive.Context.UsingStatements.Add(text);  
  48.                 result = statement;  
  49.             }  
  50.         }  
  51.         return result;  
  52.     }  
  53.     private static compiledCode GenericStatement(this string code)  
  54.     {  
  55.         compiledCode result = null;  
  56.         string statement = code + ";";  
  57.         string source = Interactive.Program(null, statement, nullnullnull);  
  58.         custStatement statement2 = new custStatement(code, source.CompileFromSource());  
  59.         if (!statement2.HasErrors)  
  60.         {  
  61.             Interactive.Context.CallStack.Add(code + ";");  
  62.             result = statement2;  
  63.         }  
  64.         else  
  65.         {  
  66.                           if (!Interactive.Context.MultiLine && (statement2.Errors[0].ErrorNumber == "CS1513" || statement2.Errors[0].ErrorNumber == "CS1528"))  
  67.             {  
  68.                  Interactive.Context.MultiLine = true;  
  69.                  exeContext expr_A2 = Interactive.Context;  
  70.                  expr_A2.MultiLineStatement += code;  
  71.              }  
  72.         }  
  73.         return result;  
  74.     }  
  75.     private static compiledCode ExpressionStatement(this string expr)  
  76.     {  
  77.         string returnStatement = custProBuilds.ReturnStatement(expr);  
  78.         custExpression expression = new custExpression(expr, Interactive.Program(nullnull, returnStatement, nullnull).CompileFromSource());  
  79.         if (!expression.HasErrors && !expr.Trim().Equals("clear", StringComparison.OrdinalIgnoreCase))  
  80.         {  
  81.             string text = "__" + Guid.NewGuid().ToString().Replace("-""");  
  82.             Interactive.Context.CallStack.Add(string.Concat(new string[]  
  83.             {  
  84.                 "var ",  
  85.                 text,  
  86.                 " = ",  
  87.                 expr,  
  88.                 ";"  
  89.             }));  
  90.         }  
  91.         return expression;  
  92.     }  
  93.   
  94.     public static string Program(string typeDeclaration = nullstring statement = nullstring returnStatement = nullstring memberDeclaration = nullstring usingStatement = null)  
  95.     {  
  96.      
  97.         return custProBuilds.Build(Interactive.Context, typeDeclaration, statement, returnStatement, memberDeclaration, usingStatement);  
  98.     }  
  99.     private static compiledCode TypeMember(this string source)  
  100.     {  
  101.         return source.TypeDeclaration() || source.MemberDeclaration() || source.FieldDeclaration();  
  102.     }  
  103.     private static compiledCode MemberDeclaration(this string code)  
  104.     {  
  105.         custMemDecl memberDeclaration = new custMemDecl(code, Interactive.Program(nullnullnull, code, null).CompileFromSource());  
  106.         if (!memberDeclaration.HasErrors)  
  107.         {  
  108.             Interactive.Context.MemberDeclarations.Add(code);  
  109.         }  
  110.         return memberDeclaration;  
  111.     }  
  112.     private static compiledCode TypeDeclaration(this string source)  
  113.     {  
  114.         string source2 = Interactive.Program(source, nullnullnullnull);  
  115.         custTypeDecl typeDeclaration = new custTypeDecl(source, source2.CompileFromSource());  
  116.         if (!typeDeclaration.HasErrors)  
  117.         {  
  118.             Interactive.Context.TypeDeclarations.Add(source);  
  119.         }  
  120.         return typeDeclaration;  
  121.     }  
  122.     private static compiledCode FieldDeclaration(this string code)  
  123.     {  
  124.         string text = code + ";";  
  125.         string memberDeclaration = text;  

  126.         custMemDecl memberDeclaration2 = new custMemDecl(code, Interactive.Program(nullnullnull, memberDeclaration, null).CompileFromSource());  
  127.         if (!memberDeclaration2.HasErrors)  
  128.         {  
  129.             Interactive.Context.MemberDeclarations.Add(text);  
  130.         }  
  131.         return memberDeclaration2;  
  132.     }  
  133.     private static string Invoke(this compiledCode compiledCode)  
  134.     {  
  135.         if (Interactive.Context.MultiLine && !compiledCode.HasErrors)  
  136.         {  
  137.             Interactive.Context.MultiLine = false;  
  138.             Interactive.Context.MultiLineStatement = "";  
  139.         }  
  140.         if (!Interactive.Context.MultiLine && compiledCode.HasErrors)  
  141.         {  
  142.             Interactive.TraceErrorMessage(compiledCode);  
  143.         }  
  144.             
  145.         if (!Interactive.Context.MultiLine && !compiledCode.HasErrors && (compiledCode is custExpression || compiledCode is custStatement))  
  146.         {  
  147.             Interactive.Context.MultiLine = false;  
  148.             Interactive.Context.MultiLineStatement = "";  
  149.             object result = Interactive.InvokeCompiledResult(compiledCode.Results);  
  150.             if (compiledCode is custExpression)  
  151.             {  
  152.                 return result.FormatOutput();  
  153.             }  
  154.         }  
  155.         return null;  
  156.     }  
  157.     private static void TraceErrorMessage(compiledCode compiledCode)  
  158.     {  
  159.         Trace.TraceError(compiledCode.Errors[0].ErrorText);  
  160.         if (Interactive.Context.VerboseTrace)  
  161.         {  
  162.             Trace.TraceError(compiledCode.Errors[0].ErrorNumber);  
  163.         }  
  164.     }  
  165.     private static object InvokeCompiledResult(CompilerResults results)  
  166.     {  
  167.         Assembly compiledAssembly = results.CompiledAssembly;  
  168.         Type type = compiledAssembly.GetType("Wrapper");  
  169.         object obj = Activator.CreateInstance(type, null);  
  170.         MethodInfo method = type.GetMethod("Eval");  
  171.         return method.Invoke(obj, null);  
  172.     }  
  173.     private static CompilerResults CompileFromSource(this string source)  
  174.     {  
  175.         CompilerParameters compilerParameters = new CompilerParameters  
  176.         {  
  177.             GenerateExecutable = false,  
  178.             GenerateInMemory = true  
  179.         };  
  180.         compilerParameters.ReferencedAssemblies.Add("System.Core.dll");  
  181.         compilerParameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);  
  182.         compilerParameters.ReferencedAssemblies.Add("System.Xml.dll");  
  183.         compilerParameters.ReferencedAssemblies.Add("System.Xml.Linq.dll");  
  184.         compilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");  
  185.         foreach (string current in exeContext.Assemblies)  
  186.         {  
  187.             compilerParameters.ReferencedAssemblies.Add(current);  
  188.         }  
  189.         return Interactive.Compiler.CompileAssemblyFromSource(compilerParameters, new string[]  
  190.         {  
  191.             source  
  192.         });  
  193.     }  
  194. }  
The implementation of each semantic resides in separate methods that reference passes to the build method later. As we know, each C# code definition is located in external DLL files that are typically imported into a code file with using statements. Some of the namespaces are automatically imported into the class file. Hence, this project also provides the definition for some default namespace in the CompilerFromSource() method. It doesn't mean that whatever we enter on the command line shell is interpreted perfectly, this mechanism also echos the error message, in case the code grammar is not recognized.

Loading Context Class

The Context class is used to load the external or default namespace (DLL) in the C# interactive interface so that the user is spared from importing, even some common namespace frequently. It also gathers the information about the verbose mode, Single/Multiline statements, using statements and later, the reference in the CompilerFromSource() method of the interpreted class.
  1. public class exeContext  
  2. {  
  3.     public static List<string> Assemblies = new List<string>();  
  4.     public IList<string> CallStack = new List<string>();  
  5.     public IList<string> TypeDeclarations = new List<string>();  
  6.     public List<string> MemberDeclarations = new List<string>();  
  7.     public List<string> UsingStatements = new List<string>();  
  8.     public bool MultiLine  
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     public string MultiLineStatement  
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     public bool VerboseTrace  
  19.     {  
  20.         get;  
  21.         set;  
  22.     }  
  23.     public bool Continue  
  24.     {  
  25.         get;  
  26.         set;  
  27.     }  
  28.     public exeContext()  
  29.     {  
  30.         this.Continue = true;  
  31.         this.MultiLineStatement = "";  
  32.     }  
  33.     public static void LoadAssembly(string name)  
  34.     {  
  35.         FileInfo fileInfo = new FileInfo(name);  
  36.         FileInfo fileInfo2 = new FileInfo(Assembly.GetExecutingAssembly().Location);  
  37.         if (fileInfo.DirectoryName != fileInfo2.DirectoryName)  
  38.         {  
  39.             if (fileInfo2.DirectoryName != null)  
  40.             {  
  41.                 if (!File.Exists(Path.Combine(fileInfo2.DirectoryName, fileInfo.Name)))  
  42.                 {  
  43.                     fileInfo.CopyTo(Path.Combine(fileInfo2.DirectoryName, fileInfo.Name), true);  
  44.                 }  
  45.                 exeContext.Assemblies.Add(fileInfo.Name);  
  46.                 return;  
  47.             }  
  48.         }  
  49.         else  
  50.         {  
  51.             exeContext.Assemblies.Add(name);  
  52.         }  
  53.     }  
  54. }  
Custom Build Class

The custProBuilds class mainly has the two methods Build() and ReturnStatment(). These methods usually generate code dynamically and are called from the interactive class. C# code typically requires the semicolon as a terminated statement, but here we can either use on not because such handling is done by the ReturnStatment() method automatically. The run time C# code entered on the command shell gathers from the interactive class and passes to Build() to generate the code that is later compiled.
  1. public static class custProBuilds  
  2. {  
  3.     public const string UsingStatements = "\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing System.Linq;\r\nusing System.Xml;\r\nusing System.Xml.Linq;\r\nusing CsharpInterpreter;\r\nSystem.Windows.Forms;\r\n";  
  4.     private const string ClassPrefix = "public class Wrapper { \r\n";  
  5.     private const string InteropDeclarations = "public void LoadAssembly(string name) \r\n  { \r\nexeContext.LoadAssembly(name); \r\n  }\r\n\r\n  public bool Verbose \r\n  {\r\nget { return Interactive.Context.VerboseTrace; }\r\n set { Interactive.Context.VerboseTrace = value; }\r\n  }\r\n\r\npublic OutputString Exit \r\n  {\r\n get { Interactive.Context.Continue = false; return new OutputString(\"Bye\"); }\r\n  }\r\n  public OutputString exit \r\n  {\r\n    get { return Exit; }\r\n  }\r\n\r\n  public OutputString Quit \r\n  {\r\n    get { return Exit; }\r\n  }\r\n\r\n  public OutputString quit \r\n  {\r\n    get { return Exit; }\r\n  }\r\n\r\n\r\n  public OutputString Help \r\n  {\r\n    get { return new OutputString(@\"Usings\t\t\tDisplay the current using statements\n    Help\t\t\tDisplay help\n    Clear\t\t\tClear the console window\n    Quit\t\t\tExit\"); }\r\n  }\r\n\r\n  public OutputString __Program \r\n  {\r\n    get { return new OutputString(Interactive.Program()); }\r\n  }\r\n\r\n  public OutputString Usings \r\n  {\r\n    get { return new OutputString(custProBuilds.UsingStatements); }\r\n  }\r\n\r\n  public outString Clear \r\n  {\r\n    get { Console.Clear(); return new outString(\"\"); }\r\n  }\r\n\r\n  public outString clear \r\n  {\r\n    get { return Clear; }\r\n  }\r\n\r\n";  
  6.     private const string FuncPrefix = "  public object Eval() { \r\n";  
  7.     private const string ReturnStmnt = "    return ";  
  8.     private const string FuncSuffix = " \r\n  }\r\n}";  
  9.     private static exeContext context;  
  10.     private static readonly string DefaultReturnStatement = custProBuilds.ReturnStatement("\"\"");  
  11.     public static string ReturnStatement(string expression)  
  12.     {  
  13.         return "    return " + expression + ";";  
  14.     }  
  15.     public static string Build(exeContext executionContext, string typeDeclaration, string statement, string returnStatement, string memberDeclaration, string usingStatement)  
  16.     {  
  17.         custProBuilds.context = executionContext;  
  18.         return string.Concat(new string[]  
  19.             {  
  20.                 "\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Text;\r\nusing System.Linq;\r\nusing System.Xml;\r\nusing System.Xml.Linq;\r\nusing CsharpInterpreter;\r\n",  
  21.                 custProBuilds.CustomUsingStatements(),  
  22.                 usingStatement,  
  23.                 custProBuilds.TypeDeclarations(),  
  24.                 typeDeclaration,  
  25.                 "public class Wrapper { \r\n",  
  26.                 custProBuilds.MemberDeclarations(),  
  27.                 memberDeclaration,  
  28.                 "  public void LoadAssembly(string name) \r\n  { \r\nexeContext.LoadAssembly(name); \r\n  }\r\n\r\n  public bool Verbose \r\n  {\r\n    get { return Interactive.Context.VerboseTrace; }\r\n    set { Interactive.Context.VerboseTrace = value; }\r\n  }\r\n\r\n  public outString Exit \r\n  {\r\n    get { Interactive.Context.Continue = false; return new outString(\"Bye\"); }\r\n  }\r\n  public outString exit \r\n  {\r\n    get { return Exit; }\r\n  }\r\n\r\n  public outString Quit \r\n  {\r\n    get { return Exit; }\r\n  }\r\n\r\n  public outString quit \r\n  {\r\n    get { return Exit; }\r\n  }\r\n\r\n\r\n  public outString Help \r\n  {\r\n    get { return new outString(@\"\n    Usings\t\t\tDisplay the current using statements\n    Help\t\t\tDisplay help\n    Clear\t\t\tClear the console window\n    Quit\t\t\tExit\"); }\r\n  }\r\n\r\n  public outString __Program \r\n  {\r\n    get { return new outString(Interactive.Program()); }\r\n  }\r\n\r\n  public outString Usings \r\n  {\r\n    get { return new outString(custProBuilds.UsingStatements); }\r\n  }\r\n\r\n  public outString Clear \r\n  {\r\n    get { Console.Clear(); return new outString(\"\"); }\r\n  }\r\n\r\n  public outString clear \r\n  {\r\n    get { return Clear; }\r\n  }\r\n\r\n  public object Eval() { \r\n",  
  29.                 custProBuilds.CallStack(),  
  30.                 statement,  
  31.                 returnStatement ?? custProBuilds.DefaultReturnStatement,  
  32.                 " \r\n  }\r\n}"  
  33.             });  
  34.     }  
  35.     private static string CallStack()  
  36.     {  
  37.         return custProBuilds.CreateInlineSectionFrom(custProBuilds.context.CallStack);  
  38.     }  
  39.     private static string MemberDeclarations()  
  40.     {  
  41.         return custProBuilds.CreateInlineSectionFrom(custProBuilds.context.MemberDeclarations);  
  42.     }  
  43.     private static string TypeDeclarations()  
  44.     {  
  45.         return custProBuilds.CreateSectionFrom(custProBuilds.context.TypeDeclarations);  
  46.     }  
  47.     private static string CustomUsingStatements()  
  48.     {  
  49.         return custProBuilds.CreateSectionFrom(custProBuilds.context.UsingStatements);  
  50.     }  
  51.     private static string CreateInlineSectionFrom(IEnumerable<string> linesOfCode)  
  52.     {  
  53.         StringBuilder stringBuilder = new StringBuilder();  
  54.         foreach (string current in linesOfCode)  
  55.         {  
  56.             stringBuilder.Append("    ");  
  57.             stringBuilder.Append(current);  
  58.             stringBuilder.Append("\r\n");  
  59.         }  
  60.         return stringBuilder.ToString();  
  61.     }  
  62.     private static string CreateSectionFrom(IEnumerable<string> linesOfCode)  
  63.     {  
  64.         StringBuilder stringBuilder = new StringBuilder();  
  65.         foreach (string current in linesOfCode)  
  66.         {  
  67.             stringBuilder.Append(current);  
  68.             stringBuilder.Append("\r\n");  
  69.         }  
  70.         return stringBuilder.ToString();  
  71.     }  
  72. }  
Custom Output Class

The result of the dynamic code entered on the interactive command shell is compiled and its result is taken care of by the custOutput class. First this class recognizes the entire output stored in XML format, Array and later retrieved on the interactive shell through an enumerator. All the formatted output handling is done by the StringBuilder class here.
  1. public static class custOutput  
  2. {  
  3.     public static string FormatOutput(this object result)  
  4.     {  
  5.         if (result == null)  
  6.         {  
  7.             return "null";  
  8.         }  
  9.         if (result is string)  
  10.         {  
  11.             return custOutput.FormatOutput(result as string);  
  12.         }  
  13.         if (result is short || result is int || result is long || result is double || result is float || result is bool || result.GetType().Name.Contains("AnonymousType"))  
  14.         {  
  15.             return result.ToString();  
  16.         }  
  17.         if (result is IDictionary)  
  18.         {  
  19.             return custOutput.FormatOutput(result as IDictionary);  
  20.         }  
  21.         if (result is Array)  
  22.         {  
  23.             return custOutput.FormatOutput(result as Array);  
  24.         }  
  25.         if (result is IXPathNavigable)  
  26.         {  
  27.             IXPathNavigable iXPathNavigable = result as IXPathNavigable;  
  28.             XPathNavigator xPathNavigator = iXPathNavigable.CreateNavigator();  
  29.             return XDocument.Parse(xPathNavigator.OuterXml).ToString();  
  30.         }  
  31.         if (result is XDocument)  
  32.         {  
  33.             return result.ToString();  
  34.         }  
  35.         if (result is IEnumerable)  
  36.         {  
  37.             return custOutput.FormatOutput(result as IEnumerable);  
  38.         }  
  39.         MethodInfo method = result.GetType().GetMethod("ToString", Type.EmptyTypes);  
  40.         if (method != null && method.DeclaringType != typeof(object))  
  41.         {  
  42.             return result.ToString();  
  43.         }  
  44.         if (result.GetType() != typeof(object))  
  45.         {  
  46.             StringBuilder stringBuilder = new StringBuilder();  
  47.             Type type = result.GetType();  
  48.             stringBuilder.Append(type.Name);  
  49.             stringBuilder.Append(" {");  
  50.             int num = 0;  
  51.             PropertyInfo[] properties = type.GetProperties();  
  52.             for (int i = 0; i < properties.Length; i++)  
  53.             {  
  54.                 PropertyInfo propertyInfo = properties[i];  
  55.                 if (propertyInfo.MemberType == MemberTypes.Property)  
  56.                 {  
  57.                     stringBuilder.Append(" ");  
  58.                     stringBuilder.Append(propertyInfo.Name);  
  59.                     stringBuilder.Append(" = ");  
  60.                     stringBuilder.Append(propertyInfo.GetValue(result, null).FormatOutput());  
  61.                     if (num < type.GetProperties().Length - 1)  
  62.                     {  
  63.                         stringBuilder.Append(", ");  
  64.                     }  
  65.                 }  
  66.                 num++;  
  67.             }  
  68.             stringBuilder.Append(" }");  
  69.             return stringBuilder.ToString();  
  70.         }  
  71.         return result.ToString();  
  72.     }  
  73.     private static string FormatOutput(Array array)  
  74.     {  
  75.         StringBuilder stringBuilder = new StringBuilder("[");  
  76.         int num = 0;  
  77.         foreach (object current in array)  
  78.         {  
  79.             stringBuilder.Append(current.FormatOutput());  
  80.             if (num < array.Length - 1)  
  81.             {  
  82.                 stringBuilder.Append(",");  
  83.             }  
  84.             num++;  
  85.         }  
  86.         stringBuilder.Append("]");  
  87.         return stringBuilder.ToString();  
  88.     }  
  89.     private static string FormatOutput(string value)  
  90.     {  
  91.         return "\"" + value + "\"";  
  92.     }  
  93.     private static string FormatOutput(IEnumerable enumerable)  
  94.     {  
  95.         StringBuilder stringBuilder = new StringBuilder("[");  
  96.         IEnumerator enumerator = enumerable.GetEnumerator();  
  97.         int num = 0;  
  98.         while (enumerator.MoveNext())  
  99.         {  
  100.             stringBuilder.Append(enumerator.Current.FormatOutput());  
  101.             stringBuilder.Append(",");  
  102.             num++;  
  103.         }  
  104.         if (num > 0)  
  105.         {  
  106.             stringBuilder.Remove(stringBuilder.Length - 1, 1);  
  107.         }  
  108.         stringBuilder.Append("]");  
  109.         return stringBuilder.ToString();  
  110.     }  
  111.     private static string FormatOutput(IDictionary dictionary)  
  112.     {  
  113.         StringBuilder stringBuilder = new StringBuilder("[");  
  114.         IDictionaryEnumerator enumerator = dictionary.GetEnumerator();  
  115.         int num = 0;  
  116.         while (enumerator.MoveNext())  
  117.         {  
  118.             stringBuilder.Append("[");  
  119.             stringBuilder.Append(enumerator.Key.FormatOutput());  
  120.             stringBuilder.Append(", ");  
  121.             stringBuilder.Append(enumerator.Value.FormatOutput());  
  122.             stringBuilder.Append("]");  
  123.             stringBuilder.Append(",");  
  124.             num++;  
  125.         }  
  126.         if (num > 0)  
  127.         {  
  128.             stringBuilder.Remove(stringBuilder.Length - 1, 1);  
  129.         }  
  130.         stringBuilder.Append("]");  
  131.         return stringBuilder.ToString();  
  132.     }  
  133. }  
So, we have explained the main-2 coding segment up until now. The other class implementations in this scenario is subtle and their code could be found in the attachment. We can't discuss each here, due to the length of this paper. Once all the class's code is written properly and when we test it, the interactive compiler IDE is as in the following:

custom build class

In the previous figure, we can see an overview of results of the short C# code. We don't need to create a separate project, even to compile short codes. If we want to see the command help of this software then issue the Help command. To quit the application issue the quit command and for clearing the command window test, issue the clear command as in the following.

display status

Suppose we would like to do some Windows Forms related operations, like showing a message box. Then first use the namespace of the Windows Forms and issue the following code in the interactive shell pertaining to message boxes as shown in the following.

message box

Final Words

This article has given a taste of programming in a functional language, a dynamic language like Perl, Python or BASIC. It is hard to find a C# interactive kind of mechanism so far, but dreams can come true by employing the Mono project API. In this paper, I have illustrated the comprehensive development process of C# interactive programming where we can enter the C# code run time and get the results immediately, even without making or relying on a full-fledged Visual Studio project. We shall present other .NET DLR projects likes IronPython and IronRuby in the form of an interactive shell soon.


Similar Articles