예제 #1
0
        public void Test1()
        {
            string script = @"public record Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
}";
            AssemblyCSharpBuilder builder = new AssemblyCSharpBuilder();

            builder.Domain = DomainManagement.Random;
            builder.Add(script);
            var type = builder.GetType();

            Assert.NotNull(type);
        }
예제 #2
0
        public void RunClassName1()
        {
            //ScriptCompiler.Init();
            string text = @"using System;
using System.Collections;
using System.Linq;
using System.Text;
 
namespace HelloWorld
{
    public class TestIndex1
    {
        public string Name;
        public int Age{get;set;}
    }
    public class TestIndex2
    {
        public string Name;
        public int Age{get;set;}
    }

    public class TestIndex3
    {
        public string Name;
        public int Age{get;set;}
    }
}

namespace HelloWorld{
    public struct TestStruct1{}
    public struct TestStruct2{}
    public class TestIndex4
    {
        public string Name;
        public int Age{get;set;}
    }
}

";
            //根据脚本创建动态类
            AssemblyCSharpBuilder oop = new AssemblyCSharpBuilder();

            oop.Compiler.Domain = DomainManagement.Random;
            oop.Add(text);
            Type type = oop.GetTypeFromShortName("TestIndex3");

            Assert.Equal("TestIndex3", type.Name);
        }
예제 #3
0
        static void Main(string[] args)
        {
            NatashaInitializer.Initialize();
            string text = @"namespace HelloWorld
            {
                public class Test
                {
                    public Test(){
                        Name=""111"";
                    }

                    public string Name;
                    public int Age{get;set;}
                }
            }";
            //根据脚本创建动态类
            AssemblyCSharpBuilder oop = new AssemblyCSharpBuilder("test");

            oop.Domain = DomainManagement.Random;
            //oop.Domain.AddReferencesFromDllFile(typeof(object).Assembly.Location);
            oop.Add(text);
            Type type = oop.GetTypeFromShortName("Test");

            Console.WriteLine(type.Name);

            var action = NDelegate.UseDomain(oop.Domain).Action("");
            var a      = action.Method;

            Console.WriteLine(action.Method.Module.Assembly);
            Console.WriteLine(DomainManagement.IsDeleted(action.GetDomain().Name));

            //var nClass = NClass
            //    .RandomDomain();
            //nClass.DelegateHandler.
            //type = NClass
            //    .RandomDomain().Namespace("")
            //    .Name("Test")
            //    .Ctor(item => item
            //        .Public()
            //        .Body("Name = null;")
            //    )
            //    .PublicField<string>("Name")
            //    .GetType();
            //type.Assembly
            //CSharpScript.EvaluateAsync

            Console.ReadKey();
        }
예제 #4
0
        public string Post(string csharpCode,
                           [FromServices] ApplicationPartManager manager,
                           [FromServices] DynamicChangeTokenProvider tokenProvider)
        {
            string code = HttpUtility.UrlDecode(csharpCode);
            string name = ScriptHelper.GetClassName(code);
            AssemblyCSharpBuilder builder = new AssemblyCSharpBuilder("TestAAA");

            builder.Compiler.Domain = DomainManagement.Create(name);
            builder.Add(code);
            var assembly = new AssemblyPart(builder.GetAssembly());

            AssemblyCache.Enqueue(assembly);
            manager.ApplicationParts.Add(assembly);
            tokenProvider.NotifyChanges();
            return("succeed!");
        }
예제 #5
0
        public string Post(string csharpCode,
                           [FromServices] ApplicationPartManager manager,
                           [FromServices] DynamicChangeTokenProvider tokenProvider)
        {
            string code = HttpUtility.UrlDecode(csharpCode);
            string name = ScriptHelper.GetClassName(code);
            AssemblyCSharpBuilder builder = new AssemblyCSharpBuilder("TestAAA");

            builder.Compiler.Domain = DomainManagement.Create(name);
            builder.Add(code);
            var assembly     = builder.GetAssembly();
            var assemblyPart = new AssemblyPart(assembly);

            AssemblyCache.Enqueue(assemblyPart);
            //manager.ApplicationParts.Add(assemblyPart);
            IControllerFactoryProvider a;

            var controllerType = assembly.GetTypes().First(item => item.Name == "TestController");

            //AutoFacBuilder.RegisterType(controllerType).AsSelf();
            //var result = _icoContext.Resolve<IApplicationFeatureProvider>();
            manager.ApplicationParts.Add(new AssemblyPart(assembly));
            manager.FeatureProviders.Add(new ControllerFeatureProvider());
            var feature = new ControllerFeature();

            manager.PopulateFeature(feature);

            AutoFacBuilder.RegisterTypes(feature.Controllers.Select(ti => ti.AsType()).ToArray()).PropertiesAutowired();
            tokenProvider.NotifyChanges();

            //AutoFac.RegisterType(assembly.GetTypes().First(item=>item.Name=="TestController")).SingleInstance();
            //icoContext.Resolve(assembly.GetTypes().First(item => item.Name == "TestController"));

            //AutoFacBuilder.RegisterAssemblyModules(assembly);
            //StaticAssemblyProvider

            ////AutoFacBuilder.IfNotRegistered(controllerType);
            //AutoFacBuilder.RegisterType(controllerType).AsSelf().PropertiesAutowired();
            //services.AddControllers().AddControllersAsServices();
            //AutoFacBuilder.RegisterType(controllerType).AsSelf().InstancePerLifetimeScope();
            //_icoContext.ResolveOptional(controllerType);
            //_icoContext.Resolve(controllerType);
            //_icoContext.TryResolve(controllerType, out var provider);

            return(controllerType.ToString());
        }
예제 #6
0
        public static void Deconstruct(
            this string script,
            out Assembly Assembly,
            out NatashaException Exception)
        {
            AssemblyCSharpBuilder assembly = new AssemblyCSharpBuilder();

            assembly.Add(script);
            Assembly = assembly.GetAssembly();
            if (assembly.Exceptions != null)
            {
                Exception = assembly.Exceptions[0];
            }
            else
            {
                Exception = null;
            }
        }
예제 #7
0
파일: DictNormalTest.cs 프로젝트: wwwK/Leo
        public void TestCall4()
        {
            //ScriptComplier.Init();
            string text = @"using System;
using System.Collections;
using System.Linq;
using System.Text;
 
namespace HelloWorld
{
    public class Test
    {
        public Test(){
            Name=""111"";
            Pp = 10;
            Rp=""aa"";
        }
        private long Pp;
        private readonly string Rp;
        public string Name;
        public int Age{get;set;}
    }
}";
            //根据脚本创建动态类
            var oop = new AssemblyCSharpBuilder();

            oop.Add(text);
            Type type = oop.GetTypeFromShortName("Test");
            //创建动态类实例代理
            var instance = PrecisionDictOperator.CreateFromType(type);
            var obj      = Activator.CreateInstance(type);

            instance.SetObjInstance(obj);
            instance["Pp"] = 30L;
            instance["Rp"] = "ab";
            //Get动态调用
            Assert.Equal("111", (string)instance["Name"]);
            Assert.Equal("ab", (string)instance["Rp"]);
            Assert.Equal(30, (long)instance["Pp"]);
            //调用动态委托赋值
            instance.Set("Name", "222");

            Assert.Equal("222", (string)instance["Name"]);
        }
예제 #8
0
        public void Test6()
        {
            string assemblyName           = "tsda";
            AssemblyCSharpBuilder builder = new AssemblyCSharpBuilder(assemblyName);

            builder.Compiler.Domain = DomainManagement.Create("a");
            builder.Add("public class TSDA{}");
            var assembly = builder.GetAssembly();

            assembly.RemoveReferences();
            Assert.NotNull(assembly);
            builder = new AssemblyCSharpBuilder();
            builder.Compiler.Domain = DomainManagement.Create("a");
            builder.Add("public class TSDA{}");
            var assembly1 = builder.GetAssembly();

            Assert.NotEqual(assembly, assembly1);
            var func = NDelegate.CreateDomain("a").Func <string>("return typeof(TSDA).Assembly.FullName;");

            Assert.Equal(assembly1.FullName, func());
        }
예제 #9
0
        public void RunClassName0()
        {
            //ScriptCompiler.Init();
            string text = @"
namespace HelloWorld
{public class Test{public Test(){
            Name=""111"";
        }public string Name;
        public int Age{get;set;}
    }
}";
            //根据脚本创建动态类
            AssemblyCSharpBuilder oop = new AssemblyCSharpBuilder();

            oop.LogCompilerError();
            oop.LogSyntaxError();
            oop.Compiler.Domain = DomainManagement.Random;
            oop.Add(text);
            Type type = oop.GetTypeFromShortName("Test");

            Assert.Equal("Test", type.Name);
        }
예제 #10
0
파일: DictStaticTest.cs 프로젝트: wwwK/Leo
        public void TestCall1()
        {
            //ScriptComplier.Init();
            string text = @"using System;
using System.Collections;
using System.Linq;
using System.Text;
 
namespace HelloWorld
{
    public static class StaticTest2
    {
        static StaticTest2(){
            Name=""111"";
        }

        public static string Name;
        public static int Age{get;set;}
    }
}";
            //根据脚本创建动态类
            var oop = new AssemblyCSharpBuilder();

            oop.Add(text);
            var type = oop.GetTypeFromShortName("StaticTest2");
            //创建动态类实例代理
            var instance = PrecisionDictOperator.CreateFromType(type);

            //Get动态调用
            Assert.Equal("111", (string)instance["Name"]);
            //调用动态委托赋值
            instance["Name"] = "222";

            Assert.Equal("222", (string)instance["Name"]);
            Assert.Equal("222", instance.Get <string>("Name"));
        }
예제 #11
0
        public async Task Execute(string code, NScriptOptions scriptOptions)
        {
            if (code.Contains("static void Main(") || code.Contains("static async Task Main("))
            {
                // Program
            }
            else
            {
                // Statement
                if (code.Contains("await "))
                {
                    //async
                    code = $@"public static async Task MainAsync()
  {{
    {code}
  }}";
                }
                else
                {
                    // sync
                    code = $@"public static void Main(string[] args)
  {{
    {code}
  }}";
                }
            }

            if (!code.Contains("static void Main(") && code.Contains("static async Task Main("))
            {
                if (code.Contains("static async Task Main()"))
                {
                    code = $@"{code}
public static void Main() => MainAsync().Wait();
";
                }
                else
                {
                    code = $@"{code}
public static void Main() => MainAsync(null).Wait();
";
                }
            }

            if (!code.Contains("class Program"))
            {
                code = $@"public class Program
{{
  {code}
}}";
            }

            scriptOptions.UsingList.Add("NatashaPad");

            code = $"{scriptOptions.UsingList.Select(ns => $"using {ns};").StringJoin(Environment.NewLine)}{Environment.NewLine}{code}";

            using var domain = DomainManagement.Random;
            var assBuilder = new AssemblyCSharpBuilder();

            assBuilder.Add(code, scriptOptions.UsingList);

            // add reference
            if (scriptOptions.ReferenceResolvers != null && scriptOptions.ReferenceResolvers.Count > 0)
            {
                var references = await scriptOptions.ReferenceResolvers
                                 .Select(r => r.Resolve())
                                 .WhenAll()
                                 .ContinueWith(r => r.Result.SelectMany(_ => _).ToArray());

                // add reference
                foreach (var reference in references)
                {
                    // TODO: handle none filePath reference
                    if (!string.IsNullOrEmpty(reference?.FilePath))
                    {
                        domain.LoadPluginFromStream(reference.FilePath);
                    }
                }
            }
            assBuilder.Compiler.Domain             = domain;
            assBuilder.Compiler.AssemblyOutputKind = AssemblyBuildKind.File;

            var assembly = assBuilder.GetAssembly();

            using (var capture = await ConsoleOutput.Capture())
            {
                var entryPoint = assembly.GetType("Program")?.GetMethod("Main", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                if (null != entryPoint)
                {
                    entryPoint.Invoke(null, entryPoint.GetParameters().Select(p => p.ParameterType.GetDefaultValue()).ToArray());
                }
                else
                {
                    throw new ArgumentException("can not find entry point");
                }
                if (!string.IsNullOrEmpty(capture.StandardOutput))
                {
                    DumpOutHelper.OutputAction?.Invoke(capture.StandardOutput);
                }
            }

            //using (var executor = new DotNetExecutor(assembly.Location, _outputHelper))
            //{
            //    await executor.ExecuteAsync();
            //}
        }
예제 #12
0
        public async Task Execute(string code, NScriptOptions scriptOptions)
        {
            if (code.Contains("static void Main(") || code.Contains("static async Task Main("))
            {
                // Program
            }
            else
            {
                // Statement
                if (code.Contains("await "))
                {
                    //async
                    code = $@"public static async Task MainAsync()
  {{
    {code}
  }}";
                }
                else
                {
                    // sync
                    code = $@"public static void Main(string[] args)
  {{
    {code}
  }}";
                }
            }

            if (!code.Contains("static void Main(") && code.Contains("static async Task Main("))
            {
                if (code.Contains("static async Task Main()"))
                {
                    code = $@"{code}
public static void Main() => MainAsync().Wait();
";
                }
                else
                {
                    code = $@"{code}
public static void Main() => MainAsync(null).Wait();
";
                }
            }

            if (!code.Contains("class Program"))
            {
                code = $@"public class Program
{{
  {code}
}}";
            }

            if (scriptOptions.UsingList.Count > 0)
            {
                code = $"{scriptOptions.UsingList.Select(ns => $"using {ns};").StringJoin(Environment.NewLine)}{Environment.NewLine}{code}";
            }

            DomainManagement.RegisterDefault <AssemblyDomain>();
            var assBuilder = new AssemblyCSharpBuilder(GuidIdGenerator.Instance.NewId());

            assBuilder.Add(code, scriptOptions.UsingList);

            // TODO: add references

            assBuilder.CompilerOption(compiler =>
            {
                compiler.AssemblyOutputKind = AssemblyBuildKind.File;
            });

            var assembly        = assBuilder.GetAssembly();
            var targetFramework = assembly.GetCustomAttribute <TargetFrameworkAttribute>();

            var entryPoint = assembly.GetType("Program")?.GetMethod("Main", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);

            if (null != entryPoint)
            {
                entryPoint.Invoke(null, entryPoint.GetParameters().Select(p => p.ParameterType.GetDefaultValue()).ToArray());
            }
            else
            {
                throw new ArgumentException("can not find entry point");
            }

            //using (var executor = new DotNetExecutor(assembly.Location, _outputHelper))
            //{
            //    await executor.ExecuteAsync();
            //}
        }