- Java锁的逻辑(结合对象头和ObjectMonitor)
- 还在用饼状图?来瞧瞧这些炫酷的百分比可视化新图形(附代码实现)⛵
- 自动注册实体类到EntityFrameworkCore上下文,并适配ABP及ABPVNext
- 基于Sklearn机器学习代码实战
之前已经实现过 Blazor 在线编译了,现在我们 实现一个简单的在浏览器运行的编辑器,并且让他可以编译我们的C#代码, 。
技术栈:
Roslyn 用于编译 c# 代码 。
[monaco]( microsoft/monaco-editor: A browser based code editor (github.com) ) 用于提供语法高亮和代码的智能提示 。
问:在浏览器编译有什么用?我可以在电脑编译还可以调试,为什么要在浏览器中去编译代码?
答:对比某些场景,比如一些Blazor组件库,提供一个简单的编辑框,在编辑框中可以编辑组件代码,并且实时看到组件动态渲染效果,这样是不是会提高一些开发效率?或者说在某些学生,可能刚刚入门,还没有开发设备,想着熟悉c#,使用在线编辑是不是更简单?
问:WebAssembly不是打包几十MB吗?那岂不是下载很久?
答: 可以参考这个博客 如何将WebAssembly优化到1MB ,Blazor WebAssembly的优化方案。最小可以到1MB,其实并不会很大 。
问:是否有示例项目?
答: Blazor 在线编辑器 这是一个可以在浏览器动态编译Blazor的编辑器, 。
实现我们创建一个空的 Blazor WebAssembly 的项目 ,并且命名为 WebEditor 如图所示 。
然后删除 Pages\Index.razor , _Imports.razor , App.razor , MainLayout.razor 文件 。
项目添加包引用,将以下代码copy到项目文件中添加引用 。
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.4.0" />
创建 Compile.cs ,用于编写编译工具,添加以下代码,在这里我们使用 Roslyn 编译我们的C#代码,并且执行,这里还会提供 Execute 方法供 js 调用 。
public class Compile
{
/// <summary>
/// 定义需要加载的程序集,相当于项目引用第三方程序集
/// </summary>
static List<string> ReferenceAssembly = new(){
"/_framework/System.dll",
"/_framework/System.Buffers.dll",
"/_framework/System.Collections.dll",
"/_framework/System.Core.dll",
"/_framework/System.Linq.Expressions.dll",
"/_framework/System.Linq.Parallel.dll",
"/_framework/mscorlib.dll",
"/_framework/System.Linq.dll",
"/_framework/System.Console.dll",
"/_framework/System.Private.CoreLib.dll",
"/_framework/System.Runtime.dll"
};
private static IEnumerable<MetadataReference>? _references;
private static CSharpCompilation _previousCompilation;
private static object[] _submissionStates = { null, null };
private static int _submissionIndex = 0;
/// <summary>
/// 注入的HttpClient
/// </summary>
private static HttpClient Http;
/// <summary>
/// 初始化Compile
/// </summary>
/// <param name="http"></param>
/// <returns></returns>
public static void Init(HttpClient http)
{
Http = http;
}
[JSInvokable("Execute")]
public static async Task<string> Execute(string code)
{
return await RunSubmission(code);
}
private static bool TryCompile(string source, out Assembly? assembly, out IEnumerable<Diagnostic> errorDiagnostics)
{
assembly = null;
var scriptCompilation = CSharpCompilation.CreateScriptCompilation(
Path.GetRandomFileName(),
CSharpSyntaxTree.ParseText(source, CSharpParseOptions.Default.WithKind(SourceCodeKind.Script)
.WithLanguageVersion(LanguageVersion.Preview)), _references,
// 默认引用的程序集
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, usings: new[]
{
"System",
"System.Collections.Generic",
"System.Console",
"System.Diagnostics",
"System.Dynamic",
"System.Linq",
"System.Linq.Expressions",
"System.Text",
"System.Threading.Tasks"
}, concurrentBuild: false), // 需要注意,目前由于WebAssembly不支持多线程,这里不能使用并发编译
_previousCompilation
);
errorDiagnostics = scriptCompilation.GetDiagnostics().Where(x => x.Severity == DiagnosticSeverity.Error);
if (errorDiagnostics.Any())
{
return false;
}
using var peStream = new MemoryStream();
var emitResult = scriptCompilation.Emit(peStream);
if (emitResult.Success)
{
_submissionIndex++;
_previousCompilation = scriptCompilation;
assembly = Assembly.Load(peStream.ToArray());
return true;
}
return false;
}
/// <summary>
/// 执行Code
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
private static async Task<string> RunSubmission(string code)
{
var diagnostic = string.Empty;
try
{
if (_references == null)
{
// 定义零时集合
var references = new List<MetadataReference>(ReferenceAssembly.Count);
foreach (var reference in ReferenceAssembly)
{
await using var stream = await Http.GetStreamAsync(reference);
references.Add(MetadataReference.CreateFromStream(stream));
}
_references = references;
}
if (TryCompile(code, out var script, out var errorDiagnostics))
{
var entryPoint = _previousCompilation.GetEntryPoint(CancellationToken.None);
var type = script.GetType($"{entryPoint.ContainingNamespace.MetadataName}.{entryPoint.ContainingType.MetadataName}");
var entryPointMethod = type.GetMethod(entryPoint.MetadataName);
var submission = (Func<object[], Task>)entryPointMethod.CreateDelegate(typeof(Func<object[], Task>));
// 如果不进行添加会出现超出索引
if (_submissionIndex >= _submissionStates.Length)
{
Array.Resize(ref _submissionStates, Math.Max(_submissionIndex, _submissionStates.Length * 2));
}
// 执行代码
_ = await ((Task<object>)submission(_submissionStates));
}
diagnostic = string.Join(Environment.NewLine, errorDiagnostics);
}
catch (Exception ex)
{
diagnostic += Environment.NewLine + ex;
}
return diagnostic;
}
}
修改 Program.cs 文件,在这里我们注入了 HttpClient ,并且传递到了 Compile.Init 中; 。
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
var app = builder.Build();
// 获取HttpClient传递到初始化编译
Compile.Init(app.Services.GetRequiredService<HttpClient>());
await app.RunAsync();
创建 wwwroot/index.html 我们将使用monaco创建我们的编辑框,通过引用cdn加载monaco的js 。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>WebEditor</title>
<base href="/" />
<link href="web-editor.css" rel="stylesheet" />
</head>
<body>
<div>
<div class="web-editor" id="monaco">
</div>
<div class="web-editor console" id="console">
</div>
<div class="clear" id="clear">
清空调试
</div>
<div class="run" id="run">
运行
</div>
</div>
<!-- 设置autostart="false" 将不会自动加载web Assembly程序集 -->
<script src="_framework/blazor.webassembly.js"></script>
<script>
var require = { paths: { 'vs': 'https://cdn.masastack.com/npm/monaco-editor/0.34.1/min/vs' } };
</script>
<script src="https://cdn.masastack.com/npm/monaco-editor/0.34.1/min/vs/loader.js"></script>
<script src="https://cdn.masastack.com/npm/monaco-editor/0.34.1/min/vs/editor/editor.main.nls.js"></script>
<script src="https://cdn.masastack.com/npm/monaco-editor/0.34.1/min/vs/editor/editor.main.js"></script>
<script>
// 等待dom加载完成
window.addEventListener('load', function () {
// 创建Monaco对象存储在window中
window.webeditor = monaco.editor.create(document.getElementById('monaco'), {
value: `Console.WriteLine("欢迎使用Token在线编辑器");`, // 设置初始值
language: 'csharp', // 设置monaco 语法提示
automaticLayout: true, // 跟随父容器大小
theme: "vs-dark" // 主题
});
document.getElementById("run").onclick = () => {
// 调用封装的方法将编辑器的代码传入
execute(window.webeditor.getValue());
};
// 清空调试区
document.getElementById('clear').onclick = () => {
document.getElementById("console").innerText = '';
}
async function execute(code) {
// 使用js互操调用WebEditor程序集下的Execute静态方法,并且发送参数
code = await DotNet.invokeMethodAsync('WebEditor', 'Execute', code);
document.getElementById("console").innerText += code;
}
})
</script>
</body>
</html>
创建 web-editor.css 样式文件 。
/*通用样式*/
.web-editor {
height: 98vh; /*可见高度*/
width: 50%;/*区块宽度*/
float: left;
}
/*运行按钮*/
.run {
position: fixed; /*悬浮*/
height: 23px;
width: 34px;
right: 8px; /*靠右上角*/
cursor: pointer; /*显示手指*/
background: #3d5fab; /*背景颜色*/
border-radius: 6px;
user-select: none; /*禁止选择*/
}
/*清除按钮*/
.clear {
position: fixed;
height: 23px;
width: 69px;
right: 45px;
cursor: pointer;
background: #fd0707;
border-radius: 6px;
user-select: none;
}
.console {
background-color: dimgray;
color: aliceblue;
}
执行我们的项目,效果如图:
示例地址: GitHub 。
来着token的分享 。
最后此篇关于实现一个简单的在浏览器运行Dotnet编辑器的文章就讲到这里了,如果你想了解更多关于实现一个简单的在浏览器运行Dotnet编辑器的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
我正在努力实现以下目标, 假设我有字符串: ( z ) ( A ( z ) ( A ( z ) ( A ( z ) ( A ( z ) ( A ) ) ) ) ) 我想编写一个正则
给定: 1 2 3 4 5 6
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
大家好,我卡颂。 Svelte问世很久了,一直想写一篇好懂的原理分析文章,拖了这么久终于写了。 本文会围绕一张流程图和两个Demo讲解,正确的食用方式是用电脑打开本文,跟着流程图、Demo一
身份证为15位或者18位,15位的全为数字,18位的前17位为数字,最后一位为数字或者大写字母”X“。 与之匹配的正则表达式: ?
我们先来最简单的,网页的登录窗口; 不过开始之前,大家先下载jquery的插件 本人习惯用了vs2008来做网页了,先添加一个空白页 这是最简单的的做法。。。先在body里面插入 <
1、MySQL自带的压力测试工具 Mysqlslap mysqlslap是mysql自带的基准测试工具,该工具查询数据,语法简单,灵活容易使用.该工具可以模拟多个客户端同时并发的向服务器发出
前言 今天大姚给大家分享一款.NET开源(MIT License)、免费、简单、实用的数据库文档(字典)生成工具,该工具支持CHM、Word、Excel、PDF、Html、XML、Markdown等
Go语言语法类似于C语言,因此熟悉C语言及其派生语言( C++、 C#、Objective-C 等)的人都会迅速熟悉这门语言。 C语言的有些语法会让代码可读性降低甚至发生歧义。Go语言在C语言的
我正在使用快速将 mkv 转换为 mp4 ffmpeg 命令 ffmpeg -i test.mkv -vcodec copy -acodec copy new.mp4 但不适用于任何 mkv 文件,当
我想计算我的工作簿中的工作表数量,然后从总数中减去特定的工作表。我错过了什么?这给了我一个对象错误: wsCount = ThisWorkbook.Sheets.Count - ThisWorkboo
我有一个 perl 文件,用于查看文件夹中是否存在 ini。如果是,它会从中读取,如果不是,它会根据我为它制作的模板创建一个。 我在 ini 部分使用 Config::Simple。 我的问题是,如果
尝试让一个 ViewController 通过标准 Cocoa 通知与另一个 ViewController 进行通信。 编写了一个简单的测试用例。在我最初的 VC 中,我将以下内容添加到 viewDi
我正在绘制高程剖面图,显示沿路径的高程增益/损失,类似于下面的: Sample Elevation Profile with hand-placed labels http://img38.image
嗨,所以我需要做的是最终让 regStart 和 regPage 根据点击事件交替可见性,我不太担心编写 JavaScript 函数,但我根本无法让我的 regPage 首先隐藏。这是我的代码。请简单
我有一个非常简单的程序来测量一个函数花费了多少时间。 #include #include #include struct Foo { void addSample(uint64_t s)
我需要为 JavaScript 制作简单的 C# BitConverter。我做了一个简单的BitConverter class BitConverter{ constructor(){} GetBy
已关闭。这个问题是 not reproducible or was caused by typos 。目前不接受答案。 这个问题是由拼写错误或无法再重现的问题引起的。虽然类似的问题可能是 on-top
我是 Simple.Data 的新手。但我很难找到如何进行“分组依据”。 我想要的是非常基本的。 表格看起来像: +________+ | cards | +________+ | id |
我现在正在开发一个 JS UDF,它看起来遵循编码。 通常情况下,由于循环计数为 2,Alert Msg 会出现两次。我想要的是即使循环计数为 3,Alert Msg 也只会出现一次。任何想法都
我是一名优秀的程序员,十分优秀!