oleg-shilo / cs-script.core

.NET Core port of CS-Script
MIT License
100 stars 18 forks source link

[Question] Migrating from .Net Framework - Compiling wholesome files #18

Closed X39 closed 3 years ago

X39 commented 3 years ago

Summary

Hello there, i am currently migrating from .net framework to .net core and am facing issues during this process.

Prior i used CSScriptLibrary.CSScript.LoadCode to load a file as a whole and get the assembly returned, receiving the method later using a "default" method name.

The benefit has been that i had more control about what the methods can access easily, thanks to additional using instructions, and could place the code into a certain namespace, easing the navigation further.

The issue i now face is that this approach presents me with a You cannot declare namespace in script code error message.

The relevant code in question is as follows:

.Net Framework code

assembly = CSScriptLibrary.CSScript.LoadCode(code, assemblyPath, DEBUG_BUILD);

.Net Core code

CSScriptLib.CSScript.Evaluator.DebugBuild = DEBUG_BUILD;
assembly = CSScriptLib.CSScript.Evaluator.CompileCode(code, new CSScriptLib.CompileInfo
{
    AssemblyFile = assemblyPath
});

The outer shell for code is the follows:

const string preText = @"using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace X39.Trader.Data
{
    public class CSScriptClass
    {
        public static bool CSScriptMethod(
            X39.Trader.Api.Client client,
            X39.Trader.Data.Job job)
        {
";
const string postText = @"
        }
    }
}";

// class Condition { ... public string Code { get; set; } ... }
Condition condition = ...;
var code = String.Concat(preText, condition.Code, postText);

Is it possible to get the same behavior?

Thanks for your time, X39

oleg-shilo commented 3 years ago

yes it is possible. Try to use CSScript.CodeDomEvaluator it allows using namespaces.

The problem with Roslyn compiler is that it takes the script code and treats it as a class declaration. Whereas CodeDom treats it as a C# file.

X39 commented 3 years ago

Solved it already by pretty much updated all script files. Was substantially less work then i expected at first, thanks to some basic regex magic i did.

Thanks anyways :)