一个简单的C#在线IDE示例
做一个简单的C#在线IDE主要解决两个问题:
一是如何将网页上文本框的代码编译并执行;
二是如何将程序运行结果在网页上输出.
第一个问题不难, dotNET已经有现成的C#编译类CSharpCodeProvider(或是其它语言的),再使用CompilerParameters类做为编译参数,就可以很容易的实现.
第二个问题, 举最简单情况, 就是将Console.Write方法输出的内容在网页上显示出来.这其实也很好办,只要在编译之前, 在输出语句做一个替换, 将输出的内容存到另一个地方.等运行结束后, 再从那个地方取出来就是了.
代码实现如下:
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VSOnline.Framework
{
///
/// 自定义的输出类
///
public class Consoler
{
//存储所有输出
public static Dictionary Outputs { get; set; }
static Consoler()
{
Outputs = new Dictionary();
}
#region 输出操作
//当前输出
public List Output { get; private set; }
public Consoler()
{
Output = new List();
}
public void Write(object str)
{
Output.Add(str.ToString());
}
public void WriteLine(object str)
{
Output.Add(str.ToString() + "\n");
}
#endregion
}
}
using System.Reflection;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace VSOnline.Framework
{
///
/// 代码执行类
///
public class CodeRun
{
///
/// Framework版本,可选择v2.0, v3.0, v3.5
///
private string CompilerVersion { get; set; }
///
/// 构造函数
///
/// Framework版本,可选择v2.0, v3.0, v3.5
public CodeRun(string compilerVersion)
{
CompilerVersion = compilerVersion;
}
///
/// 构造函数,默认为3.5版本
///
public CodeRun()
{
CompilerVersion = "v3.5";
}
///
/// 动态编译并执行代码
///
/// 代码
/// 返回输出内容
public List 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() { { "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 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();
}
}
}
测试代码:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System;
using FastDev.Core;
using System.Linq;
namespace Test
{
[TestClass()]
public class CodeRunTest
{
[TestMethod()]
public void RunTest()
{
CodeRun target = new CodeRun();
//注意:以下是一个多行的 string
string code = @"
using System;
public class Program
{
public static void Main()
{
for(int index = 1;index <= 3;index++)
{
Console.Write(index);
}
}
} "; // 多行 string结束
List expected = new List() { "1", "2", "3" };
List actual;
actual = target.Run(code, "1");
Assert.AreEqual(true, expected.SerializeEqual(actual));
actual = target.Run(code, "2");
Assert.AreEqual(true, expected.SerializeEqual(actual));
}
[TestMethod()]
public void Run35Test()
{
CodeRun target = new CodeRun();
string code = @"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static string Name { get; set; }
public static void Main()
{
Name = ""3"";
Console.Write(Name);
}
} ";
List actual;
actual = target.Run(code, "1", "System.Core.dll");
Assert.AreEqual("3", actual[0]);
}
}
}
转载于:https://www.cnblogs.com/guangrou/archive/2008/06/02/1212197.html
一个简单的C#在线IDE示例相关推荐
- 从一个简单的Java单例示例谈谈并发
一个简单的单例示例 单例模式可能是大家经常接触和使用的一个设计模式,你可能会这么写 public class UnsafeLazyInitiallization { private static Un ...
- csv文件示例_自己动手? -一个简单的CSV解析器示例
csv文件示例 Download source code - 2.7 MB 下载源代码2.7 MB 目录 (Table of Contents) Introduction 介绍 The Dataset ...
- php用户注册功能设计,利用HTML+CSS设计一个简单的用户注册页面【示例】
本篇文章将要给新手小白们介绍如何使用HTML和css制作简单的注册页面.在开发网站过程中,如果网站内容要求是完善的信息站,那么肯定就离不开用户注册的这个功能.这个用户注册界面对于刚入门的前端新手来说, ...
- 使用ESP8266构建一个简单的温湿度在线监测装置
主要功能 在终端对环境温湿度进行采集,通过WIFI接入网络 能够显示实时参数变化(表格和曲线),具备一定的历史数据回溯功能 后期可加入一些联动控制或报警功能 项目目的 没有什么特别的实用性,就是随便玩 ...
- 端口扫描php,一个简单的php在线端口扫描器
作者:angel 前言 PHP是一种功能强大的Web开发语言.开发效率高,语法简单,为动态网站量身定做,加强面向对象(向C++靠拢,与JAVA搭了点边),可惜单线程(这是至命弱点,据说PHP是用C\C ...
- python简单代码hello-PySide教程:一个简单的点击按钮示例
在这篇文章里,我们将为你展示如何使用PySide使用信号.槽机制.基本来说,这是Qt提供给你的允许一个图形控件与其他图形控件或者python代码进行通讯的特性. 我们将要创建一个应用,你点击应用中的按 ...
- Angular中实现一个简单的toDoList(待办事项)示例代码
场景 Angular介绍.安装Angular Cli.创建Angular项目入门教程: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/detail ...
- PostgreSQL 的一个简单连接和查询操作——示例
表和数据: CREATE TABLE weather (city varchar(80),temp_lo int, -- low temperaturetemp_hi int, -- high tem ...
- 一个简单的汉字搜索匹配示例(支持拼音、首字母简写)
在社交应用中,很多场景下需要用到搜索,以微信的搜索通讯录为例.好友自己有昵称,我们可能给他/她备注一个昵称,在输入:拼间.首字母.原文时都应该能匹配到(匹配优先是备注然后才是原来的昵称).这里以'芈月 ...
最新文章
- 如何避免让微服务测试成为研发团队最大的瓶颈?
- chvg改变vg中LV的数量
- android 添加安装权限白名单
- OpenCV场景文本识别的实例(附完整代码)
- MSSQLSERVER服务不能启动
- debian文本配置网络备忘:/etc/network/interfaces
- CompletableFuture详解~anyOf
- linux视图版怎么输入命令,分享在Linux命令下操作MySQL视图实例代码
- Sublime Text 3的中文显示乱码问题
- 基于树莓派2代的DIY无线路由器
- How to install innotop and percona tookit on centos
- bzoj 1003: [ZJOI2006]物流运输
- “鱼渔合作”在IT运维中的启示
- set_union()和set_intersection()用法:原来并集和交集这样求!
- 最新Vue2.0+组件开源项目库集合
- 笔记本电脑键盘坏了,有密码应该如何打开?(生活小技巧)
- CB Insights:7个颠覆式创新框架
- IPv4地址的结构体与网络字节序
- 微信小程序客服功能,并在聊天页面获取用户头像昵称
- vuejs视图不能及时更新的问题 ,深入响应式原理