// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Drawing; using System.Reflection; using System.Windows.Forms; using Microsoft.CSharp; namespace E { public interface ISnippet { string Run(); } public partial class MainForm : Form { public MainForm() { InitializeComponent(); } protected void CompileClick(object sender, EventArgs e) { ISnippet o = CompileAndLoad(LinesText.Text, MethodsText.Text, ClassesText.Text); if(o != null) { OutputText.Text = o.Run(); } } private int count = 0; private const string TEMPLATE = @" using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace E {{ {3} public class {0} : ISnippet {{ {2} public string Run() {{ TextWriter save = Console.Out; StringWriter sw = new StringWriter(); Console.SetOut(sw); {1} Console.SetOut(save); return sw.ToString(); }} }} }} "; private ISnippet CompileAndLoad(string lines, string methods, string classes) { count++; string clznam = "DynClass" + count; string src = string.Format(TEMPLATE, clznam, lines, methods, classes); CodeDomProvider comp = new CSharpCodeProvider(); CompilerParameters param = new CompilerParameters(); param.GenerateInMemory = true; param.ReferencedAssemblies.Add("System.Core.dll"); param.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); CompilerResults res = comp.CompileAssemblyFromSource(param, src); if(res.Errors.HasErrors) { OutputText.Text = src; foreach(CompilerError line in res.Errors) { OutputText.Text += (line + "\r\n"); } return null; } else { Assembly asm = res.CompiledAssembly; return (ISnippet)asm.CreateInstance("E." + clznam); } } } }