53 lines
1.5 KiB
C#
53 lines
1.5 KiB
C#
using System.IO;
|
|
using System.Reflection;
|
|
|
|
using Autodesk.Revit.DB;
|
|
|
|
using Microsoft.CodeAnalysis;
|
|
using Microsoft.CodeAnalysis.CSharp;
|
|
|
|
namespace Szmedi.RvKits.LLMScript
|
|
{
|
|
public class CodeExecutor
|
|
{
|
|
public void Execute(string methodBody, Autodesk.Revit.DB.Document doc, UIDocument uidoc)
|
|
{
|
|
string code = $@"
|
|
using Autodesk.Revit.DB;
|
|
using Autodesk.Revit.UI;
|
|
using System;
|
|
|
|
public class ScriptRunner
|
|
{{
|
|
public void Run(Document doc, UIDocument uidoc)
|
|
{{
|
|
{methodBody}
|
|
}}
|
|
}}";
|
|
|
|
var syntaxTree = CSharpSyntaxTree.ParseText(code);
|
|
|
|
var compilation = CSharpCompilation.Create(
|
|
"DynamicScript")
|
|
.AddReferences(
|
|
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
|
|
MetadataReference.CreateFromFile(typeof(Document).Assembly.Location))
|
|
.AddSyntaxTrees(syntaxTree)
|
|
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
|
|
|
|
using var ms = new MemoryStream();
|
|
var result = compilation.Emit(ms);
|
|
|
|
if (!result.Success)
|
|
throw new Exception("Compilation failed");
|
|
|
|
ms.Seek(0, SeekOrigin.Begin);
|
|
var assembly = Assembly.Load(ms.ToArray());
|
|
|
|
var type = assembly.GetType("ScriptRunner");
|
|
var instance = Activator.CreateInstance(type);
|
|
type.GetMethod("Run").Invoke(instance, new object[] { doc, uidoc });
|
|
}
|
|
}
|
|
}
|