public static Type GetTypeFromShortName(this AssemblyCSharpBuilder builder, string typeName)
    {
        Assembly assembly = builder.GetAssembly();

        try
        {
            return(assembly.GetTypes().First(item => item.Name == typeName));
        }
        catch (Exception ex)
        {
            NatashaException exception = new($"无法在程序集 {builder.AssemblyName} 中找到该类型 {typeName}!错误信息:{ex.Message}");
            exception.ErrorKind = NatashaExceptionKind.Type;
            throw exception;
        }
    }
Example #2
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!");
        }
Example #3
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());
        }
Example #4
0
        public static void Deconstruct(
            this string script,
            out Assembly Assembly,
            out CompilationException Exception)
        {
            AssemblyCSharpBuilder assembly = new AssemblyCSharpBuilder();

            assembly.Syntax.Add(script);
            Assembly = assembly.GetAssembly();
            if (assembly.Exceptions != null)
            {
                Exception = assembly.Exceptions[0];
            }
            else
            {
                Exception = null;
            }
        }
Example #5
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());
        }
Example #6
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();
            //}
        }
Example #7
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();
            //}
        }