using System;
using System.Reflection;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace VSOnline.Framework
{
/**//// <summary>
/// 代碼執行類
/// </summary>
public class CodeRun
{
/**//// <summary>
/// Framework版本,可選擇v2.0, v3.0, v3.5
/// </summary>
private string CompilerVersion { get; set; }
/**//// <summary>
/// 構造函數
/// </summary>
/// <param name="compilerVersion">Framework版本,可選擇v2.0, v3.0, v3.5</param>
public CodeRun(string compilerVersion)
{
CompilerVersion = compilerVersion;
}
/**//// <summary>
/// 構造函數,默認為3.5版本
/// </summary>
public CodeRun()
{
CompilerVersion = "v3.5";
}
/**//// <summary>
/// 動態編譯並執行代碼
/// </summary>
/// <param name="code">代碼</param>
/// <returns>返回輸出內容</returns>
public List<string> Run(string code, string id, params string[] assemblIEs)
{
Consoler.Outputs.Add(id, new Consoler());
CompilerParameters compilerParams = new CompilerParameters();
//編譯器選項設置
compilerParams.CompilerOptions = "/target:library /optimize";
//compilerParams.CompilerOptions += @" /lib:""C:\Program Files\Reference AssemblIEs\Microsoft\Framework\v3.5\""";
//編譯時在內存輸出
compilerParams.GenerateInMemory = true;
//生成調試信息
compilerParams.IncludeDebugInformation = false;
//添加相關的引用
foreach (string assembly in assemblIEs)
{
compilerParams.ReferencedAssemblIEs.Add(assembly);
}
compilerParams.ReferencedAssemblIEs.Add("mscorlib.dll");
compilerParams.ReferencedAssemblIEs.Add("System.dll");
if (this.CompilerVersion == "v3.5")
{
compilerParams.ReferencedAssemblIEs.Add("System.Core.dll");
}
string path = "";
try
{
path = HttpContext.Current.Server.MapPath("/bin/");
}
catch { }
compilerParams.ReferencedAssemblIEs.Add(path + "VSOnline.Framework.dll");
CSharpCodeProvider compiler = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", CompilerVersion } });
//編譯
code = code.Replace("Console.WriteLine", string.Format("VSOnline.Framework.Consoler.Outputs[\"{0}\"].WriteLine", id));
code = code.Replace("Console.Write", string.Format("VSOnline.Framework.Consoler.Outputs[\"{0}\"].Write", id));
CompilerResults results = compiler.CompileAssemblyFromSource(compilerParams, code);
//錯誤
if (results.Errors.HasErrors)
{
foreach (CompilerError error in results.Errors)
{
Consoler.Outputs[id].Output.Add(error.ErrorText + "\n");
}
return ReturnOutput(id);
}
//創建程序集
Assembly asm = results.CompiledAssembly;
//獲取編譯後的類型
object mainClass = asm.CreateInstance("Program");
Type mainClassType = mainClass.GetType();
//輸出結果
mainClassType.GetMethod("Main").Invoke(mainClass, null);
return ReturnOutput(id);
}
private List<string> ReturnOutput(string id)
{
string[] output = new string[Consoler.Outputs[id].Output.Count];
Consoler.Outputs[id].Output.CopyTo(output, 0);
Consoler.Outputs.Remove(id);
return output.ToList();
}
}
}