Exemple #1
0
        static void Main(string[] args)
        {
            AssemblyDomain.Init();

            var hwFunc = FastMethodOperator
                         .RandomDomain()
                         .Param(typeof(string), "str1")
                         .Param <string>("str2")
                         .Body("return str1+str2;")
                         .Return <string>()
                         .Compile <Func <string, string, string> >();

            Console.WriteLine(hwFunc("Hello", " World!"));


            var a123   = NClass.UseDomain(typeof(Program).GetDomain());
            var domain = DomainManagement.Random;
            var type   = NDelegate.UseDomain(domain).GetType("public class A{ public A(){Name=\"1\"; }public string Name;}");
            var func   = NDelegate.UseDomain(domain).Func <string>("return (new A()).Name;");

            Console.WriteLine(type.FullName);
            Console.WriteLine(func());

            //type.RemoveReferences();
            type = NDelegate.UseDomain(domain).GetType("public class A{ public A(){Name=\"2\"; }public string Name;}");
            func = NDelegate.UseDomain(domain).Func <string>("return (new A()).Name;");
            Console.WriteLine(type.FullName);
            Console.WriteLine(func());

            domain = DomainManagement.Create("a");
            using (DomainManagement.Lock("a"))
            {
                Console.WriteLine(domain == (AssemblyDomain)AssemblyLoadContext.CurrentContextualReflectionContext);
            }
        }
        public void TestClass2()
        {
            NClass builder = NClass.RandomDomain();

            var mb = builder.GetMethodBuilder();

            mb.Public().Name("Apple").Type <int>().Body("return 0;");
            var pb = builder.GetPropertyBuilder();

            pb.Public()
            .Name("Banana")
            .Type <NClass>()
            .Setter("int a = value.ToString().Length;")
            .Getter("return default;");


            var script = builder
                         .CustomUsing()
                         .HiddenNamespace()
                         .Access(Natasha.Reverser.Model.AccessFlags.Public)
                         .Name("EnumUT1")
                         .Script;

            Assert.Equal($"using System;{Environment.NewLine}using Natasha.CSharp;{Environment.NewLine}public class EnumUT1{{{Environment.NewLine}public System.Int32 Apple(){{return 0;}}{Environment.NewLine}public Natasha.CSharp.NClass Banana{{{Environment.NewLine}get{{return default;}}{Environment.NewLine}set{{int a = value.ToString().Length;}}{Environment.NewLine}}}{Environment.NewLine}}}", script);
            Assert.Equal($"using System;{Environment.NewLine}using Natasha.CSharp;{Environment.NewLine}public class EnumUT1{{{Environment.NewLine}public System.Int32 Apple(){{return 0;}}{Environment.NewLine}public Natasha.CSharp.NClass Banana{{{Environment.NewLine}get{{return default;}}{Environment.NewLine}set{{int a = value.ToString().Length;}}{Environment.NewLine}}}{Environment.NewLine}}}", script);

            Assert.NotNull(builder.GetType());
        }
Exemple #3
0
        public void TestValue()
        {
            var runtime = new ReuseAnonymousRTD();

            runtime.UseReadonlyFields();
            runtime.AddValue("小明");
            runtime.AddValue("小明");
            runtime.AddValue("小明1");
            runtime.AddValue("name", "abc");
            runtime.AddValue("name2", "abc");

            var nClass = NClass.RandomDomain()
                         .Public()
                         .Inheritance <Test>()
                         .BodyAppendLine(runtime.FieldsScript)
                         .BodyAppendLine(runtime.MethodScript);
            var  type = nClass.GetType();
            Test test = (Test)Activator.CreateInstance(type);

            test.Age = 100;
            var action = runtime.GetInitMethod <Test>(nClass);

            action(test);
            string result  = nClass.DelegateHandler.Func <Test, string>($"return (({type.Name})arg).{runtime.GetFieldName("小明")};")(test);
            string result3 = nClass.DelegateHandler.Func <Test, string>($"return (({type.Name})arg).name;")(test);

            Assert.Equal("小明", result);
            Assert.Equal("abc", result3);
            Assert.Equal(100, test.Age);
        }
Exemple #4
0
 public static void Test()
 {
     for (int i = 0; i < count; i++)
     {
         var type = NClass.Create("test" + i.ToString())
                    .Namespace("Test")
                    .UseRandomName()
                    .PublicField <string>("Name")
                    .PublicField <string>("Name1")
                    .PublicField <string>("Name2")
                    .PublicField <string>("Name3")
                    .PublicField <string>("Name4")
                    .PublicField <string>("Name5")
                    .PublicField <string>("Age")
                    .PublicField <int[]>("Temp")
                    .Ctor(item => item.Body("Temp = new int[40960];"))
                    .GetType();
         //builder.Compiler.SyntaxInfos.SyntaxExceptions.Clear();
         //builder.Compiler.SyntaxInfos.TreeCodeMapping.Clear();
         //builder.Compiler.SyntaxInfos.TreeUsingMapping.Clear();
         //builder = null;
         if (type == default)
         {
             throw new Exception("Bad Builder!");
         }
         func[i] = type;
     }
 }
Exemple #5
0
        public static void TestMemoery()
        {
            Console.WriteLine("Memory1");
            List <Type> list    = new List <Type>();
            var         domain1 = DomainManagment.Create("TempDomain1");

            for (int i = 0; i < 500; i += 1)
            {
                Console.WriteLine("new");
                NClass nStruct = new NClass();
                nStruct
                .Namespace("Core301")
                .OopName($"Test{i}")

                .Ctor(builder => builder
                      .MemberAccess(AccessTypes.Public)
                      .Param <string>("name")
                      .Body("Name=name;"))
                .PublicField <string>("Name")
                .PublicField <string>("Name1")
                .PublicField <string>("Name2")
                .PublicField <string>("Name3")
                .PublicField <string>("Name4");
                list.Add(nStruct.GetType());
            }
            DomainManagment.Get("TempDomain1").Dispose();
        }
Exemple #6
0
        public static void TestMemoery2()
        {
            Console.WriteLine("Memory2");
            var domain1 = DomainManagment.Create("TempDomain2");

            for (int i = 0; i < 10; i += 1)
            {
                Thread.Sleep(5000);
                Console.WriteLine("new");
                NClass nStruct = new NClass();
                nStruct
                .Namespace("Core30")
                .OopName($"Test{i}")

                .Ctor(builder => builder
                      .MemberAccess(AccessTypes.Public)
                      .Param <string>("name")
                      .Body("Name=name;"))
                .PublicField <string>("Name")
                .PublicField <string>("Name1")
                .PublicField <string>("Name2")
                .PublicField <string>("Name3")
                .PublicField <string>("Name4");
                var type = nStruct.GetType();
            }
            DomainManagment.Get("TempDomain2").Dispose();
            DomainManagment.Get("TempDomain2").Unload();
        }
Exemple #7
0
        public void TestDelegate()
        {
            Func <string, int> ageFunc = item => item.Length;
            var runtime = new ReuseAnonymousRTD();

            runtime.AddValue(ageFunc);
            runtime.AddValue(ageFunc);
            runtime.AddValue("name", "abc");
            runtime.AddValue("name2", "abc");

            var nClass = NClass.RandomDomain()
                         .Public()
                         .Inheritance <Test>()
                         .BodyAppendLine(runtime.FieldsScript)
                         .BodyAppendLine(runtime.MethodScript);
            var  type = nClass.GetType();
            Test test = (Test)Activator.CreateInstance(type);

            test.Age = 100;
            var action = runtime.GetInitMethod <Test>(nClass);

            action(test);

            var    result  = nClass.DelegateHandler.Func <Test, string, int>($"return (({type.Name})arg1).{runtime.GetFieldName(ageFunc)}(arg2);")(test, "Hello");
            string result3 = nClass.DelegateHandler.Func <Test, string>($"return (({type.Name})arg).name;")(test);

            Assert.Equal("abc", result3);
            Assert.Equal(5, result);
            Assert.Equal(100, test.Age);
        }
Exemple #8
0
        public void TestValue()
        {
            var runtime = new AnonymousRTD();

            runtime.UseStaticReadonlyFields();
            runtime.AddValue("小明");
            runtime.AddValue("小明1");
            runtime.AddValue("小明");
            runtime.AddValue("name", "abc");
            runtime.AddValue("name2", "abc");

            var nClass = NClass.RandomDomain()
                         .Public()
                         .BodyAppendLine(runtime.FieldsScript)
                         .BodyAppendLine(runtime.MethodScript);
            var type   = nClass.GetType();
            var action = runtime.GetInitMethod(nClass);

            action();
            string result0 = nClass.DelegateHandler.Func <string>($"return {type.Name}._anonymous_1;")();
            string result1 = nClass.DelegateHandler.Func <string>($"return {type.Name}._anonymous_2;")();
            string result2 = nClass.DelegateHandler.Func <string>($"return {type.Name}._anonymous_3;")();
            string result3 = nClass.DelegateHandler.Func <string>($"return {type.Name}.name;")();
            string result4 = nClass.DelegateHandler.Func <string>($"return {type.Name}.name2;")();

            Assert.Equal("小明1", result1);
            Assert.Equal("小明", result0);
            Assert.Equal("小明", result2);
            Assert.Equal("abc", result3);
            Assert.Equal("abc", result4);
        }
Exemple #9
0
        public Action GetInitMethod(NClass nClass)
        {
            var action = nClass.DelegateHandler.Action <ConcurrentDictionary <string, object> >($@"
{nClass.NameScript}.SetObject(obj);
");

            return(() => { action(NameValueMapping); });
        }
Exemple #10
0
        public Action <TInstance> GetInitMethod <TInstance>(NClass nClass)
        {
            var initMethod = nClass.DelegateHandler.Action <TInstance, ConcurrentDictionary <string, object> >($@"
var realInstance  = ({nClass.NameScript})arg1;
realInstance.SetObject(arg2);
");

            return((instance) => { initMethod(instance, NameValueMapping); });
        }
Exemple #11
0
        public void Test5()
        {
            var type = NClass
                       .RandomDomain()
                       .Name("TRecord")
                       .HiddenNamespace()
                       .SkipInit()
                       .Public()
                       .RecordProperty <string>("P1")
                       .RecordProperty <int>("P2")
                       .GetType();

            Assert.NotNull(type);
        }
Exemple #12
0
        public void TestClass()
        {
            NClass builder = NClass.RandomDomain();
            var    script  = builder
                             .CustomUsing()
                             .HiddenNamespace()
                             .Access(Natasha.Reverser.Model.AccessFlags.Public)
                             .Name("EnumUT1")
                             .Field(item => { item.Public().Name("Apple").Type <int>(); })
                             .Field(item => { item.Public().Name("Orange").Type <string>(); })
                             .Property(item => { item.Public().Name("Banana").Type <NClass>(); })
                             .Script;

            Assert.Equal($"using System;{Environment.NewLine}using Natasha.CSharp;{Environment.NewLine}public class EnumUT1{{{Environment.NewLine}public System.Int32 Apple;{Environment.NewLine}public System.String Orange;{Environment.NewLine}public Natasha.CSharp.NClass Banana{{{Environment.NewLine}get;{Environment.NewLine}set;{Environment.NewLine}}}{Environment.NewLine}}}", script);
            Assert.NotNull(builder.GetType());
        }
Exemple #13
0
        public void Test1()
        {
            NClass builder = new NClass();

            builder
            .Public()
            .Static()
            .Using <OopBuildTest>()
            .Namespace("TestNamespace")
            .DefinedName("TestExceptionUt1")
            .Body(@"public static void 1 Test(){}")
            .PublicStaticField <string>("Name")
            .PrivateStaticField <int>("_age")
            .Builder();
            var type = builder.GetType();

            Assert.Null(type);
            Assert.Equal(CompileError.Syntax, builder.Compiler.CompileException.ErrorFlag);
        }
Exemple #14
0
        public void CreateScript(string script = default)
        {
            //GetValue = FastMethodOperator
            //    .RandomDomain()
            //    .Param<Test>("parameter")
            //    .Return<string>()
            //    .Body("return parameter.A;")
            //    .Compile<Func<string>>(this);
            var domain   = DomainManagement.Default;
            var subClass = NClass
                           .UseDomain(domain)
                           .Inheritance <Test>()
                           .Body($"public override string Get(){{ {script} }}")
                           .GetType();

            var methodInfo = subClass.GetMethod("Get");

            this.GetValue = (Func <string>)(methodInfo.CreateDelegate(typeof(Func <string>), this));
        }
Exemple #15
0
        public void Test1()
        {
            NClass classBuilder = new NClass();

            classBuilder.AssemblyBuilder.Syntax.ErrorBehavior = ExceptionBehavior.None;
            classBuilder
            .Public()
            .Static()
            .Using <ClassExceptionTest>()
            .Namespace("TestNamespace")
            .DefinedName("TestExceptionUt1")
            .Body(@"public static void 1 Test(){}")
            .PublicStaticField <string>("Name")
            .PrivateStaticField <int>("_age")
            .BuilderScript();
            var type = classBuilder.GetType();

            Assert.Null(type);
            Assert.Equal(ExceptionKind.Syntax, classBuilder.Exception.ErrorFlag);
        }
Exemple #16
0
        public void TestClass1()
        {
            NClass builder = NClass.Random();
            var    script  = builder
                             .CurstomeUsing()
                             .HiddenNamespace()
                             .Access(Natasha.Reverser.Model.AccessTypes.Public)
                             .DefinedName("EnumUT1")
                             .Method(item => { item.Public().DefinedName("Apple").DefinedType <int>().Body("return 0;"); })
                             .Property(item => { item
                                                 .Public()
                                                 .DefinedName("Banana")
                                                 .DefinedType <NClass>()
                                                 .Setter("int a = value.ToString().Length;")
                                                 .Getter("return default;"); })
                             .Script;

            Assert.Equal($"using System;{Environment.NewLine}using Natasha.CSharp;{Environment.NewLine}public class EnumUT1{{{Environment.NewLine}public System.Int32 Apple(){{return 0;}}{Environment.NewLine}public Natasha.CSharp.NClass Banana{{{Environment.NewLine}get{{return default;}}{Environment.NewLine}set{{int a = value.ToString().Length;}}{Environment.NewLine}}}{Environment.NewLine}}}", script);
            Assert.NotNull(builder.GetType());
        }
Exemple #17
0
        static void Main(string[] args)
        {
            NatashaComponentRegister.RegistDomain <NatashaAssemblyDomain>();
            NatashaComponentRegister.RegistCompiler <NatashaCSharpCompiler>();
            NatashaComponentRegister.RegistSyntax <NatashaCSharpSyntax>();

            //var hwFunc = FastMethodOperator
            //    .RandomDomain()
            //    .Param(typeof(string), "str1")
            //    .Param<string>("str2")
            //    .Body("return str1+str2;")
            //    .Return<string>()
            //    .Compile<Func<string, string, string>>();
            //Console.WriteLine(hwFunc("Hello", " World!"));


            var a123   = NClass.UseDomain(typeof(Program).GetDomain());
            var domain = DomainManagement.Random;
            var type   = NDelegate.UseDomain(domain, item => item.AssemblyName = "a").GetType($"[assembly: AssemblyKeyFileAttribute(\"c:\\\\vs2019\\\\natasha.snk\")]" + "[assembly: AssemblyVersion(\"1.3.3.3\")]public class A{ public A(){Name=\"1\"; }public string Name;}");
            var func   = NDelegate.UseDomain(domain).Func <string>("return (new A()).Name;");

            Console.WriteLine(type.FullName);
            Console.WriteLine(func());

            //type.RemoveReferences();
            type = NDelegate.UseDomain(domain, item => item.AssemblyName = "a").GetType($"[assembly: AssemblyKeyFileAttribute(\"c:\\\\vs2019\\\\natasha.snk\")]" + "[assembly: AssemblyVersion(\"2.3.3.4\")]public class A{ public A(){Name=\"2\"; }public string Name;}");
            func = NDelegate.UseDomain(domain).Func <string>("return (new A()).Name;");
            Console.WriteLine(type.FullName);
            Console.WriteLine(func());

            domain = DomainManagement.Create("a");
            using (DomainManagement.Lock("a"))
            {
                Console.WriteLine(domain == (NatashaAssemblyDomain)AssemblyLoadContext.CurrentContextualReflectionContext);
            }

            Console.ReadKey();
        }
Exemple #18
0
        public void TestDelegate()
        {
            Func <string, int> func  = item => item.Length;
            Func <string, int> func1 = item => item.Length + 1;
            var runtime = new AnonymousRTD();

            runtime.UseStaticFields();
            var key = runtime.AddValue(func);

            runtime.AddValue(func1);
            runtime.AddValue(func);
            runtime.AddValue("name", "abc");
            runtime.AddValue("name2", "abc");

            var nClass = NClass.RandomDomain()
                         .Public()
                         .BodyAppendLine(runtime.FieldsScript)
                         .BodyAppendLine(runtime.MethodScript);
            var type = nClass.GetType();

            var action = runtime.GetInitMethod(nClass);

            action();


            int    result0 = nClass.DelegateHandler.Func <string, int>($"return {type.Name}.{key}(arg);")("hello");
            int    result1 = nClass.DelegateHandler.Func <string, int>($"return {type.Name}._anonymous_2(arg);")("hello");
            int    result2 = nClass.DelegateHandler.Func <string, int>($"return {type.Name}._anonymous_3(arg);")("hello");
            string result3 = nClass.DelegateHandler.Func <string>($"return {type.Name}.name;")();
            string result4 = nClass.DelegateHandler.Func <string>($"return {type.Name}.name2;")();

            Assert.Equal(6, result1);
            Assert.Equal(5, result0);
            Assert.Equal(5, result2);
            Assert.Equal("abc", result3);
            Assert.Equal("abc", result4);
        }
Exemple #19
0
        static void Main(string[] args)
        {
            var a123 = NClass.Use(typeof(Program).GetDomain());

            var domain = DomainManagment.Random;
            var type   = NDelegate.Use(domain).GetType("public class A{ public A(){Name=\"1\"; }public string Name;}");

            Console.WriteLine(type.FullName);
            var func = NDelegate.Use(domain).Func <string>("return (new A()).Name;");

            Console.WriteLine(func());

            type.RemoveReferences();
            type = NDelegate.Use(domain).GetType("public class A{ public A(){Name=\"2\"; }public string Name;}");
            func = NDelegate.Use(domain).Func <string>("return (new A()).Name;");
            Console.WriteLine(type.FullName);
            Console.WriteLine(func());

            domain = DomainManagment.Create("a");
            using (DomainManagment.Lock("a"))
            {
                Console.WriteLine(domain == (AssemblyDomain)AssemblyLoadContext.CurrentContextualReflectionContext);
            }
        }
        public IEnumerable <object> ToList <TReturn>(Expression <Func <TEntity, TReturn> > expression)
        {
            var code = expression.GetHashCode();

            if (SelectHandler == null)
            {
                SelectHandler = SqlHandler.Select <TEntity>();
            }
            var type = typeof(TReturn);

            if (!JoinExpressionMapping.Contains(code))
            {
                var           nclass = NClass.DefaultDomain().Public();
                StringBuilder script = new StringBuilder();
                // 获取构造函数参数
                var arguments = ((NewExpression)expression.Body).Arguments;
                //获取匿名类成员
                var members             = ((NewExpression)expression.Body).Members;
                var joinTypeFlagMapping = new Dictionary <Type, JoinTypeFlag>();
                for (int i = 0; i < arguments.Count; i++)
                {
                    // 方法类型参数
                    if (arguments[i].NodeType == ExpressionType.Call)
                    {
                        var methodExpression    = (MethodCallExpression)arguments[i];
                        var methodDeclaringType = methodExpression.Method.DeclaringType;
                        if (methodDeclaringType.IsGenericType && methodDeclaringType.GetGenericTypeDefinition().Name.Contains("Join"))
                        {
                            var joinType = methodDeclaringType.GetGenericArguments()[0];
                            if (methodExpression.Arguments[0].NodeType == ExpressionType.Quote)
                            {
                                var quoteExpression = (UnaryExpression)methodExpression.Arguments[0];
                                if (quoteExpression.Operand.NodeType == ExpressionType.Lambda)
                                {
                                    var lambdaExpression = (LambdaExpression)quoteExpression.Operand;
                                    if (lambdaExpression.Body.NodeType == ExpressionType.MemberAccess)
                                    {
                                        var memberExpression = (MemberExpression)lambdaExpression.Body;
                                        nclass.Property(item => item
                                                        .Public()
                                                        .Type(((PropertyInfo)memberExpression.Member).PropertyType)
                                                        .Name(memberExpression.Member.Name));

                                        var definitionType = methodDeclaringType.GetGenericTypeDefinition();
                                        if (definitionType == typeof(InnerJoin <>))
                                        {
                                            joinTypeFlagMapping[joinType] = JoinTypeFlag.Inner;
                                            script.Append(InnerJoin.GetJoinScript(joinType));
                                        }
                                        else if (definitionType == typeof(LeftJoin <>))
                                        {
                                            joinTypeFlagMapping[joinType] = JoinTypeFlag.Left;
                                            script.Append(LeftJoin.GetJoinScript(joinType));
                                        }
                                        else if (definitionType == typeof(RightJoin <>))
                                        {
                                            joinTypeFlagMapping[joinType] = JoinTypeFlag.Right;
                                            script.Append(RightJoin.GetJoinScript(joinType));
                                        }
                                        script.Append($".\"{memberExpression.Member.Name}\" AS \"{members[i].Name}\",");
                                    }
                                }
                            }
                        }
                    }
                    else if (arguments[i].NodeType == ExpressionType.MemberAccess)
                    {
                        var memberExpression = (MemberExpression)arguments[i];
                        nclass.Property(item => item
                                        .Public()
                                        .Type(((PropertyInfo)memberExpression.Member).PropertyType)
                                        .Name(memberExpression.Member.Name));
                        script.Append($"a.\"{memberExpression.Member.Name}\",");
                    }
                    //JoinObjectCache<ISelect<T>, TReturn>.GetObjects = NDelegate.RandomDomain().Func<ISelect<T>, object>(builder.ToString());
                }
                if (script.Length > 1)
                {
                    script.Length -= 1;
                    var joinScript = script.ToString();
                    JoinExpressionMapping = JoinExpressionMapping.Add(code);

                    var tempClass = nclass.GetType();
                    ProxyCaller <TEntity, TReturn> .Add(code, NDelegate
                                                        .DefaultDomain(item => item.LogSyntaxError())
                                                        .Func <ISelect <TEntity>, IEnumerable <object> >($"return arg.ToList<{tempClass.GetDevelopName()}>(\"{joinScript.Replace("\"","\\\"")}\");"));

                    var builder = new StringBuilder();
                    foreach (var item in joinTypeFlagMapping)
                    {
                        var    joinFieldCache = OrmNavigate <TEntity> .JoinScriptMapping[item.Key];
                        string joinAlias      = string.Empty;
                        switch (item.Value)
                        {
                        case JoinTypeFlag.Left:
                            joinAlias = LeftJoin.GetJoinScript(item.Key);
                            builder.Append($"obj.LeftJoin(\"");
                            break;

                        case JoinTypeFlag.Inner:
                            joinAlias = InnerJoin.GetJoinScript(item.Key);
                            builder.Append($"obj.InnerJoin(\"");
                            break;

                        case JoinTypeFlag.Right:
                            joinAlias = RightJoin.GetJoinScript(item.Key);
                            builder.Append($"obj.RightJoin(\"");
                            break;

                        default:
                            break;
                        }
                        var joinFieldScript = $"\"{item.Key.Name}\" AS {joinAlias} ON a.\"{joinFieldCache.src}\" = {joinAlias}.\"{joinFieldCache.dst}\"";
                        builder.Append(joinFieldScript.Replace("\"", "\\\""));
                        builder.AppendLine("\");");
                    }

                    //$"\"{typeof(TJoinEntity).Name}\" AS {InnerJoinHelper<TJoinEntity>.JoinAliasName} ON a.\"{srcFieldName}\" = {InnerJoinHelper<TJoinEntity>.JoinAliasName}.\"{destFieldName}\"")
                    JoinFiller <TEntity, TReturn> .Add(code, NDelegate
                                                       .DefaultDomain()
                                                       .Action <ISelect <TEntity> >(builder.ToString()));
                }
            }

            JoinFiller <TEntity, TReturn> .HandlerSelect(code, SelectHandler);

            return(ProxyCaller <TEntity, TReturn> .ToList(code, SelectHandler));
        }
Exemple #21
0
        private NClass ProcessInheritance(NType type)
        {
            NClass baseModel = null;

            if (type.Bases.Count > 0)
            {
                var directParent = type.Bases[0];
                baseModel = (NClass)this.FindType(directParent.Id);
            }

            if (type.AllMembers.Count > 0)
            {
                return(baseModel);
            }

            type.AllMembers.AddRange(type.Members);

            if (baseModel != null)
            {
                this.ProcessInheritance(baseModel);

                var newMembers = new List <INMemberReference>();
                foreach (var nMemberReference in baseModel.AllMembers)
                {
                    // Don't add constructor as inherited member
                    if (nMemberReference is NConstructor)
                    {
                        continue;
                    }

                    bool addInheritedMember = true;

                    foreach (var currentMember in type.AllMembers)
                    {
                        var method = currentMember as NMethod;

                        // Don't add method that are overriden
                        if (method != null && method.Overrides != null && nMemberReference is NMethod)
                        {
                            if (method.Overrides.Id == nMemberReference.Id)
                            {
                                addInheritedMember = false;
                                break;
                            }
                        }
                    }

                    if (addInheritedMember)
                    {
                        if (nMemberReference is NMethod)
                        {
                            type.HasMethods = true;
                        }
                        else if (nMemberReference is NProperty)
                        {
                            type.HasProperties = true;
                        }
                        else if (nMemberReference is NEvent)
                        {
                            type.HasEvents = true;
                        }

                        newMembers.Add(nMemberReference);
                    }
                }

                type.AllMembers.AddRange(newMembers);
            }

            // Order elements
            type.AllMembers.Sort((from, to) => string.CompareOrdinal(@from.Name, to.Name));

            // Recalculate a PageId based on the number of overriding methods.
            var counters  = new Dictionary <string, int>();
            var overrides = new Dictionary <string, int>();

            foreach (var member in type.AllMembers.OfType <NMethod>())
            {
                string id = PageIdFunction(member);

                // Count overrides
                if (!overrides.ContainsKey(member.Name))
                {
                    overrides.Add(member.Name, 0);
                }
                else
                {
                    overrides[member.Name]++;
                }

                // Change only Id that are overlapping
                if (!counters.ContainsKey(id))
                {
                    counters.Add(id, 0);
                }
                else
                {
                    counters[id]++;
                    id = id + "_" + counters[id];
                }

                member.PageId = id;
            }

            // Tag methods that are overriden
            foreach (var method in type.AllMembers.OfType <NMethod>())
            {
                if (overrides.ContainsKey(method.Name) && overrides[method.Name] > 0)
                {
                    method.HasOverrides = true;
                }
            }

            foreach (var nsubClass in type.Members.OfType <NType>())
            {
                ProcessInheritance(nsubClass);
            }

            return(baseModel);
        }
Exemple #22
0
        static void Main(string[] args)
        {
            NErrorLog.Enabled   = false;
            NSucceedLog.Enabled = false;
            NWarningLog.Enabled = false;
            Stopwatch watch = new Stopwatch();
            double    tempTotleTime;

            #region Natasha Preheating
            var preTime = Process.GetCurrentProcess().TotalProcessorTime;
            watch.Start();
            tempType = NClass.Create("tes1t")
                       .Namespace("Test")
                       .UseRandomName()
                       .PublicField <string>("Name")
                       .PublicField <string>("Age")
                       .PublicField <int[]>("Temp")
                       .Ctor(item => item.Body("Temp = new int[40960];"))
                       .GetType();
            watch.Stop();
            tempTotleTime = GetCpu(Process.GetCurrentProcess().TotalProcessorTime, preTime);
            if (watch.Elapsed.Seconds > 0)
            {
                tempTotleTime = tempTotleTime / watch.Elapsed.Seconds;
            }
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine("Natasha预热:");
            Console.WriteLine("-----------------------------------------------------------------------------------------");
            Console.WriteLine($"|\tCPU:{tempTotleTime.ToString("f2")}%\t|\t内存:{Process.GetCurrentProcess().PrivateMemorySize64 / 1024 / 1024}M\t|\t执行耗时:{watch.Elapsed}\t|");
            Console.WriteLine("-----------------------------------------------------------------------------------------");
            #endregion

            Thread.Sleep(1000);

            #region Run Compiler
            preTime = Process.GetCurrentProcess().TotalProcessorTime;
            watch.Restart();
            Test();
            watch.Stop();
            tempTotleTime = GetCpu(Process.GetCurrentProcess().TotalProcessorTime, preTime);
            if (watch.Elapsed.Seconds > 0)
            {
                tempTotleTime = tempTotleTime / watch.Elapsed.Seconds;
            }
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine($"{count}个独立域编译后:");
            Console.WriteLine("-----------------------------------------------------------------------------------------");
            Console.WriteLine($"|\tCPU:{tempTotleTime.ToString("f2")}%\t|\t内存:{Process.GetCurrentProcess().PrivateMemorySize64 / 1024 / 1024}M\t|\t执行耗时:{watch.Elapsed}\t|");
            Console.WriteLine("-----------------------------------------------------------------------------------------");
            #endregion

            Thread.Sleep(1000);

            #region Release Handler
            preTime = Process.GetCurrentProcess().TotalProcessorTime;
            watch.Restart();
            Release();
            watch.Stop();
            tempTotleTime = GetCpu(Process.GetCurrentProcess().TotalProcessorTime, preTime);
            if (watch.Elapsed.Seconds > 0)
            {
                tempTotleTime = tempTotleTime / watch.Elapsed.Seconds;
            }
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("释放中:");
            Console.WriteLine("-----------------------------------------------------------------------------------------");
            Console.WriteLine($"|\tCPU:{tempTotleTime.ToString("f2")}%\t|\t内存:{Process.GetCurrentProcess().PrivateMemorySize64 / 1024 / 1024}M\t|\t执行耗时:{watch.Elapsed}\t|");
            Console.WriteLine("-----------------------------------------------------------------------------------------");
            #endregion

            Thread.Sleep(1000);
            #region Run GC
            preTime = Process.GetCurrentProcess().TotalProcessorTime;
            watch.Restart();
            RunGc();
            watch.Stop();
            tempTotleTime = GetCpu(Process.GetCurrentProcess().TotalProcessorTime, preTime);
            if (watch.Elapsed.Seconds > 0)
            {
                tempTotleTime = tempTotleTime / watch.Elapsed.Seconds;
            }
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine();
            Console.WriteLine("回收后:");
            Console.WriteLine("-----------------------------------------------------------------------------------------");
            Console.WriteLine($"|\tCPU:{tempTotleTime.ToString("f2")}%\t|\t内存:{Process.GetCurrentProcess().PrivateMemorySize64 / 1024 / 1024}M\t|\t执行耗时:{watch.Elapsed}\t|");
            Console.WriteLine("-----------------------------------------------------------------------------------------");
            #endregion

            Thread.Sleep(1000);

            #region Check Alive
            preTime = Process.GetCurrentProcess().TotalProcessorTime;
            watch.Restart();
            var alive = CheckAlive();
            DomainManagement.Clear();
            watch.Stop();
            tempTotleTime = GetCpu(Process.GetCurrentProcess().TotalProcessorTime, preTime);
            if (watch.Elapsed.Seconds > 0)
            {
                tempTotleTime = tempTotleTime / watch.Elapsed.Seconds;
            }
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine();
            Console.WriteLine($"存活检测: {alive}");
            Console.WriteLine("-----------------------------------------------------------------------------------------");
            Console.WriteLine($"|\tCPU:{tempTotleTime.ToString("f2")}%\t|\t内存:{Process.GetCurrentProcess().PrivateMemorySize64 / 1024 / 1024}M\t|\t执行耗时:{watch.Elapsed}\t|");
            Console.WriteLine("-----------------------------------------------------------------------------------------");
            #endregion

            //for (int i = 0; i < 10; i++)
            //{
            //    Thread.Sleep(3000);
            //    preTime = Process.GetCurrentProcess().TotalProcessorTime;
            //    Console.WriteLine($"第{i}次静默检测:");
            //    Console.WriteLine("-----------------------------------------------------------------------------------------");
            //    Console.WriteLine($"|\tCPU:{tempTotleTime.ToString("f2")}%\t|\t内存:{Process.GetCurrentProcess().PrivateMemorySize64 / 1024 / 1024}M\t|\t执行耗时:{watch.Elapsed}\t|");
            //    Console.WriteLine("-----------------------------------------------------------------------------------------");
            //}

            Console.ReadKey();
        }
Exemple #23
0
        static void Main(string[] args)
        {
            var nc = new NClass("class");

            nc.Items.CreateProperty("name", "value");
        }
Exemple #24
0
        static void Main(string[] args)
        {
            DomainManagement.RegisterDefault <AssemblyDomain>();
            //var @operator = FastMethodOperator.DefaultDomain();
            //var actionDelegate = @operator
            //    .Param(typeof(string), "parameter")
            //    .Body("Console.WriteLine(parameter);")
            //    .Compile();

            //actionDelegate.DynamicInvoke("HelloWorld!");
            //var action = (Action<string>)actionDelegate;
            //action("HelloWorld!");
            //actionDelegate.DisposeDomain();

            //起个类
            NClass nClass = NClass.DefaultDomain();

            nClass
            .Namespace("MyNamespace")
            .Public()
            .Name("MyClass")
            .Ctor(ctor => ctor.Public().Body("MyField=\"Hello\";"))
            .Property(prop => prop
                      .Type(typeof(string))
                      .Name("MyProperty")
                      .Public()
                      .OnlyGetter("return \"World!\";")
                      );


            //添加方法
            MethodBuilder mb = new MethodBuilder();

            mb
            .Public()
            .Override()
            .Name("ToString")
            .Body("return MyField+\" \"+MyProperty;")
            .Return(typeof(string));
            nClass.Method(mb);


            //添加字段
            FieldBuilder fb = nClass.GetFieldBuilder();

            fb.Public()
            .Name("MyField")
            .Type <string>();


            //动态调用动态创建的类
            var action = NDelegate
                         .RandomDomain()
                         .Action("Console.WriteLine((new MyClass()).ToString());", nClass.GetType());

            action();
            action.DisposeDomain();
            //Console.WriteLine(typeof(List<int>[]).GetRuntimeName());
            //Console.WriteLine(typeof(List<int>[,]).GetRuntimeName());
            //Console.WriteLine(typeof(int[,]).GetRuntimeName());
            //Console.WriteLine(typeof(int[][]).GetRuntimeName());
            //Console.WriteLine(typeof(int[][,,,]).GetRuntimeName());
            Console.ReadKey();
        }
Exemple #25
0
 public List<NClass> getJNationalClasses()
 {
     List<NClass> list = new List<NClass>();
     new NClass();
     SqlConnection connection = new SqlConnection(this.Connect());
     string cmdText = "SELECT xID,type,description FROM national_classes";
     SqlCommand command = new SqlCommand(cmdText, connection);
     connection.Open();
     SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
     while (reader.Read())
     {
         NClass item = new NClass {
             xID = Convert.ToInt64(reader["xID"]).ToString(),
             xtype = reader["type"].ToString(),
             xdescription = reader["description"].ToString()
         };
         list.Add(item);
     }
     reader.Close();
     return list;
 }
Exemple #26
0
        public static Type InitType(Type type, FindTreeType kind = FindTreeType.Hash)
        {
            bool isStatic = (type.IsSealed && type.IsAbstract);
            Type callType = typeof(DictBase);


            StringBuilder body  = new StringBuilder();
            var           cache = NBuildInfo.GetInfos(type);

            var setByObjectCache     = new Dictionary <string, string>();
            var getByObjectCache     = new Dictionary <string, string>();
            var getByStrongTypeCache = new Dictionary <string, string>();

            foreach (var item in cache)
            {
                var    info   = item.Value;
                string caller = "Instance";
                if (info != null)
                {
                    if (info.IsStatic)
                    {
                        caller = type.GetDevelopName();
                    }


                    if (info.CanWrite)
                    {
                        setByObjectCache[info.MemberName] = $"{caller}.{info.MemberName} = ({info.MemberTypeName})value;";
                    }

                    if (info.CanRead)
                    {
                        getByObjectCache[info.MemberName]     = $"return {caller}.{info.MemberName};";
                        getByStrongTypeCache[info.MemberName] = $"return (T)(object)({caller}.{info.MemberName});";
                    }
                }
            }

            string setObjectBody     = default;
            string getObjectBody     = default;
            string getStrongTypeBody = default;

            switch (kind)
            {
            case FindTreeType.Fuzzy:
                setObjectBody     = BTFTemplate.GetFuzzyPointBTFScript(setByObjectCache, "name");
                getObjectBody     = BTFTemplate.GetFuzzyPointBTFScript(getByObjectCache, "name");
                getStrongTypeBody = BTFTemplate.GetFuzzyPointBTFScript(getByStrongTypeCache, "name");
                break;

            case FindTreeType.Hash:
                setObjectBody     = BTFTemplate.GetHashBTFScript(setByObjectCache, "name");
                getObjectBody     = BTFTemplate.GetHashBTFScript(getByObjectCache, "name");
                getStrongTypeBody = BTFTemplate.GetHashBTFScript(getByStrongTypeCache, "name");
                break;

            case FindTreeType.Precision:
                setObjectBody     = BTFTemplate.GetGroupPrecisionPointBTFScript(setByObjectCache, "name");
                getObjectBody     = BTFTemplate.GetGroupPrecisionPointBTFScript(getByObjectCache, "name");
                getStrongTypeBody = BTFTemplate.GetGroupPrecisionPointBTFScript(getByStrongTypeCache, "name");
                break;

            default:
                break;
            }


            body.AppendLine("public unsafe override void Set(string name,object value){");
            body.AppendLine(setObjectBody);
            body.Append('}');


            body.AppendLine("public unsafe override T Get<T>(string name){");
            body.AppendLine(getStrongTypeBody);
            body.Append("return default;}");


            body.AppendLine("public unsafe override object GetObject(string name){");
            body.AppendLine(getObjectBody);
            body.Append("return default;}");


            if (!isStatic)
            {
                callType = typeof(DictBase <>).With(type);
                body.Append($@"public override void New(){{ Instance = new {type.GetDevelopName()}();}}");
            }

            Type tempClass = NClass.UseDomain(type.GetDomain())
                             .Public()
                             .Using(type)
                             .Using("System")
                             .Using("NCaller")
                             .UseRandomName()
                             .Namespace("NCallerDynamic")
                             .Inheritance(callType)
                             .Body(body.ToString())
                             .GetType();


            return(tempClass);
        }
Exemple #27
0
        public DynamicSwitchBuilder(IDictionary <TKey, TValue> pairs, Func <TKey, string> keyToCase = null)
        {
            int count  = 0;
            var nClass = NClass.RandomDomain()
                         .Public()
                         .Inheritance <DynamicDictionaryBase <TKey, TValue> >()
                         .Unsafe();

#if NET5_0
            nClass.SkipInit();
#endif



            //构建快查字典 给BTF使用
            var getValueMethodScript    = new Dictionary <TKey, string>();
            var tryGetValueMethodScript = new Dictionary <TKey, string>();
            var setValueMethodSciprt    = new Dictionary <TKey, string>();
            foreach (var item in pairs)
            {
                count += 1;
                string field = _prefix + count;
                nClass.PrivateReadonlyField <TValue>(field);

                getValueMethodScript[item.Key]    = $"return {field};";
                tryGetValueMethodScript[item.Key] = $"value = {field};return true;";
                setValueMethodSciprt[item.Key]    = $"{field.ReadonlyScript()} = value;return;";
            }

            //根据快查字典生成快查代码
            //value GetValue(key)
            nClass.Method(method =>
            {
                method
                .Param <TKey>("key")
                .Override()
                .Return <TValue>()
                .Name("GetValue")
                .Public()
                .BodyAppend(ScriptKeyAction(getValueMethodScript, "key", keyToCase))
                .BodyAppend("return default;");
            });

            //bool TryGetValue(key,out value)
            nClass.Method(method =>
            {
                method
                .Param <TKey>("key")
                .Param <TValue>("value", "out ")
                .Override()
                .Return <bool>()
                .Name("TryGetValue")
                .Public()
                .BodyAppend(ScriptKeyAction(tryGetValueMethodScript, "key", keyToCase))
                .BodyAppend("value=default; return false;");
            });

            //Change(key,value)
            nClass.Method(method =>
            {
                method
                .Param <TKey>("key")
                .Param <TValue>("value")
                .Override()
                .Name("Change")
                .Public()
                .BodyAppend(ScriptKeyAction(setValueMethodSciprt, "key", keyToCase))
                .BodyAppend("throw new Exception(\"Can't find key!\");");
            });


            var ProxyType = nClass.GetType();

            Instance = nClass
                       .DelegateHandler
                       .Func <DynamicDictionaryBase <TKey, TValue> >($"return new {ProxyType.GetDevelopName()}();")();


            foreach (var item in pairs)
            {
                Instance.Change(item.Key, item.Value);
            }
        }
Exemple #28
0
        public static Type InitType(Type type, AlgorithmKind kind = AlgorithmKind.Hash)
        {
            var isStatic = type.IsSealed && type.IsAbstract;
            var callType = typeof(DictBase);

            var body                       = new StringBuilder();
            var setByObjectCache           = new Dictionary <string, string>();
            var getByObjectCache           = new Dictionary <string, string>();
            var getByStrongTypeCache       = new Dictionary <string, string>();
            var getByLeoMembersCache       = new Dictionary <string, LeoMember>();
            var getByLeoMembersScriptCache = new Dictionary <string, string>();

            var getByReadOnlyStaticScriptBuilder  = new StringBuilder();
            var getByReadOnlySettingScriptBuilder = new StringBuilder();
            var getByInternalNamesScriptBuilder   = new StringBuilder();

            #region Field

            var fields = type.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            foreach (var field in fields)
            {
                if (field.IsSpecialName || field.Name.Contains("<"))
                {
                    continue;
                }

                var caller = "Instance";

                if (field.IsStatic)
                {
                    caller = type.GetDevelopName();
                }

                var fieldName = field.Name;
                var fieldType = field.FieldType.GetDevelopName();

                //set
                if (!field.IsLiteral)
                {
                    var fieldScript = $"{caller}.{fieldName}";

                    if (field.IsInitOnly)
                    {
                        fieldScript = fieldScript.ReadonlyScript();
                    }

                    setByObjectCache[fieldName] = $"{fieldScript} = ({fieldType})value;";
                }


                //get
                getByObjectCache[fieldName]     = $"return {caller}.{fieldName};";
                getByStrongTypeCache[fieldName] = $"return (T)(object)({caller}.{fieldName});";

                //member metadata
                getByLeoMembersCache[fieldName]       = field;
                getByLeoMembersScriptCache[fieldName] = $"return __metadata_LeoMember_{fieldName};";
                getByReadOnlyStaticScriptBuilder.AppendLine($@"private static readonly LeoMember __metadata_LeoMember_{fieldName};");
                getByInternalNamesScriptBuilder.Append($@"""{fieldName}"",");
                getByReadOnlySettingScriptBuilder.Append($"__metadata_LeoMember_{fieldName}".ReadonlyScript());
                getByReadOnlySettingScriptBuilder.Append($@" = leoMembersCache[""{fieldName}""];");
            }

            #endregion

            #region Property

            var props = type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            foreach (var property in props)
            {
                var method = property.CanRead ? property.GetGetMethod(true) : property.GetSetMethod(true);

                var caller = "Instance";

                if (method.IsStatic)
                {
                    caller = type.GetDevelopName();
                }

                var propertyName   = property.Name;
                var propertyType   = property.PropertyType.GetDevelopName();
                var propertyScript = $"{caller}.{propertyName}";

                //set
                if (property.CanWrite)
                {
                    setByObjectCache[propertyName] = $"{propertyScript} = ({propertyType})value;";
                }


                //get
                if (property.CanRead)
                {
                    getByObjectCache[propertyName]     = $"return {caller}.{propertyName};";
                    getByStrongTypeCache[propertyName] = $"return (T)(object)({caller}.{propertyName});";
                }

                //member metadata
                getByLeoMembersCache[propertyName]       = property;
                getByLeoMembersScriptCache[propertyName] = $"return __metadata_LeoMember_{propertyName};";
                getByReadOnlyStaticScriptBuilder.AppendLine($@"private static readonly LeoMember __metadata_LeoMember_{propertyName};");
                getByInternalNamesScriptBuilder.Append($@"""{propertyName}"",");
                getByReadOnlySettingScriptBuilder.Append($"__metadata_LeoMember_{propertyName}".ReadonlyScript());
                getByReadOnlySettingScriptBuilder.Append($@" = leoMembersCache[""{propertyName}""];");
            }

            #endregion

            string setObjectBody     = default;
            string getObjectBody     = default;
            string getStrongTypeBody = default;
            string getLeoMemberBody  = default;

            switch (kind)
            {
            case AlgorithmKind.Fuzzy:
                setObjectBody     = BTFTemplate.GetGroupFuzzyPointBTFScript(setByObjectCache, "name");
                getObjectBody     = BTFTemplate.GetGroupFuzzyPointBTFScript(getByObjectCache, "name");
                getStrongTypeBody = BTFTemplate.GetGroupFuzzyPointBTFScript(getByStrongTypeCache, "name");
                getLeoMemberBody  = BTFTemplate.GetGroupFuzzyPointBTFScript(getByLeoMembersScriptCache, "name");
                break;

            case AlgorithmKind.Hash:
                setObjectBody     = BTFTemplate.GetHashBTFScript(setByObjectCache, "name");
                getObjectBody     = BTFTemplate.GetHashBTFScript(getByObjectCache, "name");
                getStrongTypeBody = BTFTemplate.GetHashBTFScript(getByStrongTypeCache, "name");
                getLeoMemberBody  = BTFTemplate.GetHashBTFScript(getByLeoMembersScriptCache, "name");
                break;

            case AlgorithmKind.Precision:
                setObjectBody     = BTFTemplate.GetGroupPrecisionPointBTFScript(setByObjectCache, "name");
                getObjectBody     = BTFTemplate.GetGroupPrecisionPointBTFScript(getByObjectCache, "name");
                getStrongTypeBody = BTFTemplate.GetGroupPrecisionPointBTFScript(getByStrongTypeCache, "name");
                getLeoMemberBody  = BTFTemplate.GetGroupPrecisionPointBTFScript(getByLeoMembersScriptCache, "name");
                break;
            }


            //To add readonly metadata (LeoMember) properties.
            body.AppendLine(getByReadOnlyStaticScriptBuilder.ToString());


            body.AppendLine("public unsafe override void Set(string name,object value){");
            body.AppendLine(setObjectBody);
            body.Append('}');

#if NET5_0
            body.AppendLine("[SkipLocalsInit]");
#endif
            body.AppendLine("public unsafe override T Get<T>(string name){");
            body.AppendLine(getStrongTypeBody);
            body.Append("return default;}");

#if NET5_0
            body.AppendLine("[SkipLocalsInit]");
#endif
            body.AppendLine("public unsafe override object GetObject(string name){");
            body.AppendLine(getObjectBody);
            body.Append("return default;}");


            body.AppendLine("public unsafe override LeoMember GetMember(string name){");
            body.AppendLine(getLeoMemberBody);
            body.Append("return default;}");


            body.AppendLine("protected override HashSet<string> InternalMemberNames { get; } = new HashSet<string>(){");
            body.AppendLine(getByInternalNamesScriptBuilder.ToString());
            body.Append("};");


            body.AppendLine("public static void InitMetadataMapping(Dictionary<string, LeoMember> leoMembersCache){");
            body.AppendLine(getByReadOnlySettingScriptBuilder.ToString());
            body.Append('}');


            if (!isStatic)
            {
                callType = typeof(DictBase <>).With(type);
                body.Append($@"public override void New(){{ Instance = new {type.GetDevelopName()}();}}");
            }
            else
            {
                body.Append($@"public override void SetObjInstance(object obj){{ }}");
            }


            var tempClass = NClass.UseDomain(type.GetDomain())
                            .Public()
                            .Using(type)
                            .AllowPrivate(type.Assembly)
                            .Namespace("NMS.Leo.NCallerDynamic")
                            .Inheritance(callType)
                            .Body(body.ToString())
                            .GetType();

            InitMetadataMappingCaller(tempClass)(getByLeoMembersCache);

            return(tempClass);
        }