Example #1
0
        public void EvaluateDefinedClassVar()
        {
            ClassVarExpression expr = new ClassVarExpression("one");
            DynamicClass       cls  = new DynamicClass(null);
            DynamicObject      obj  = new DynamicObject(cls);

            cls.SetValue("one", 1);
            Context context = new Context(obj, null);

            Assert.AreEqual(1, expr.Evaluate(context));
        }
Example #2
0
        public static void DynamicDemo0()
        {
            dynamic d = new DynamicClass();

            d.X = 123;
            d.Y = "123";
            //d.Z = 123.456; 未包含Z的定义
            Console.WriteLine(d.Return(123));
            Console.WriteLine(d.Return("123"));
            Console.WriteLine(d.Return(123.456));
        }
        public static IDictionary <string, object> ToDictionary(this DynamicClass entity)
        {
            var dic = new Dictionary <string, object>();

            foreach (var key in entity.GetDynamicMemberNames())
            {
                dic.Add(key, entity.GetDynamicPropertyValue(key));
            }

            return(dic);
        }
Example #4
0
        public static object GetTypeDynamic(Type type)
        {
            var list = type
                       .GetProperties()
                       .ToList()
                       .ConvertAll(prop => new Field(prop.Name, prop.PropertyType));

            dynamic dynamicClass = new DynamicClass(list);

            return(dynamicClass);
        }
Example #5
0
        public void AssignValue()
        {
            AssignClassVarExpression cmd = new AssignClassVarExpression("one", new ConstantExpression(1));
            DynamicClass             cls = new DynamicClass(null);
            DynamicObject            obj = new DynamicObject(cls);
            Context context = new Context(obj, null);

            var result = cmd.Evaluate(context);

            Assert.AreEqual(1, result);
            Assert.AreEqual(1, cls.GetValue("one"));
        }
        public void GetOwnInstanceMethodNames()
        {
            DynamicClass dclass = new DynamicClass("Dog");
            IFunction    foo    = new DefinedFunction(null, null, null);

            dclass.SetInstanceMethod("foo", foo);

            var result = dclass.GetOwnInstanceMethodNames();

            Assert.IsNotNull(result);
            Assert.AreNotEqual(0, result.Count);
            Assert.IsTrue(result.Contains("foo"));
        }
        public void CreateInstance()
        {
            DynamicClass dclass = new DynamicClass("Dog");
            IFunction    foo    = new DefinedFunction(null, null, null);

            dclass.SetInstanceMethod("foo", foo);

            var result = dclass.CreateInstance();

            Assert.IsNotNull(result);
            Assert.AreSame(dclass, result.Class);
            Assert.AreSame(foo, result.GetMethod("foo"));
        }
        public void ApplyNewMethod()
        {
            Machine      machine = new Machine();
            DynamicClass @class  = new DynamicClass((DynamicClass)machine.RootContext.GetLocalValue("Class"), "Dog", (DynamicClass)machine.RootContext.GetLocalValue("Object"));

            var result = @class.GetMethod("new").Apply(@class, machine.RootContext, null);

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(DynamicObject));

            var obj = (DynamicObject)result;

            Assert.AreSame(@class, obj.Class);
        }
        public void ApplyNewMethodCallingInitialize()
        {
            Machine      machine    = new Machine();
            DynamicClass @class     = new DynamicClass((DynamicClass)machine.RootContext.GetLocalValue("Class"), "Dog", (DynamicClass)machine.RootContext.GetLocalValue("Object"));
            IFunction    initialize = new DefinedFunction(new AssignInstanceVarExpression("age", new ConstantExpression(10)), new string[0], null);

            @class.SetInstanceMethod("initialize", initialize);

            var result = @class.GetMethod("new").Apply(@class, @class.Constants, new object[] { });

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(DynamicObject));

            var obj = (DynamicObject)result;

            Assert.AreSame(@class, obj.Class);
            Assert.AreEqual(10, obj.GetValue("age"));
        }
Example #10
0
        public Machine()
        {
            this.requirepaths.Add(".");
            var basicobjectclass = new DynamicClass("BasicObject", null);
            var objectclass      = new DynamicClass("Object", basicobjectclass);
            var moduleclass      = new DynamicClass("Module", objectclass);
            var classclass       = new DynamicClass("Class", moduleclass);

            this.rootcontext.SetLocalValue("BasicObject", basicobjectclass);
            this.rootcontext.SetLocalValue("Object", objectclass);
            this.rootcontext.SetLocalValue("Module", moduleclass);
            this.rootcontext.SetLocalValue("Class", classclass);

            basicobjectclass.SetClass(classclass);
            objectclass.SetClass(classclass);
            moduleclass.SetClass(classclass);
            classclass.SetClass(classclass);

            basicobjectclass.SetInstanceMethod("class", new LambdaFunction(GetClass));
            basicobjectclass.SetInstanceMethod("methods", new LambdaFunction(GetMethods));
            basicobjectclass.SetInstanceMethod("singleton_methods", new LambdaFunction(GetSingletonMethods));

            moduleclass.SetInstanceMethod("superclass", new LambdaFunction(GetSuperClass));
            moduleclass.SetInstanceMethod("name", new LambdaFunction(GetName));

            classclass.SetInstanceMethod("new", new LambdaFunction(NewInstance));

            this.rootcontext.SetLocalValue("Fixnum", new FixnumClass(this));
            this.rootcontext.SetLocalValue("Float", new FloatClass(this));
            this.rootcontext.SetLocalValue("String", new StringClass(this));
            this.rootcontext.SetLocalValue("NilClass", new NilClass(this));
            this.rootcontext.SetLocalValue("FalseClass", new FalseClass(this));
            this.rootcontext.SetLocalValue("TrueClass", new TrueClass(this));
            this.rootcontext.SetLocalValue("Array", new ArrayClass(this));
            this.rootcontext.SetLocalValue("Hash", new HashClass(this));
            this.rootcontext.SetLocalValue("Range", new RangeClass(this));

            this.rootcontext.Self = objectclass.CreateInstance();

            this.rootcontext.Self.Class.SetInstanceMethod("puts", new PutsFunction(System.Console.Out));
            this.rootcontext.Self.Class.SetInstanceMethod("print", new PrintFunction(System.Console.Out));
            this.rootcontext.Self.Class.SetInstanceMethod("require", new RequireFunction(this));
        }
Example #11
0
        public override object Evaluate(Context context)
        {
            object value = null;

            if (context.Module != null)
            {
                if (context.Module.Constants.HasLocalValue(this.name))
                {
                    value = context.Module.Constants.GetLocalValue(this.name);
                }
            }
            else if (context.HasLocalValue(this.name))
            {
                value = context.GetLocalValue(this.name);
            }

            DynamicClass module;

            if (value == null || !(value is DynamicClass))
            {
                DynamicClass modclass   = (DynamicClass)context.RootContext.GetLocalValue("Module");
                var          superclass = (DynamicClass)context.RootContext.GetLocalValue("Object");
                module = new DynamicClass(modclass, this.name, superclass, context.Module);

                if (context.Module != null)
                {
                    context.Module.Constants.SetLocalValue(this.name, module);
                }
                else
                {
                    context.RootContext.SetLocalValue(this.name, module);
                }
            }
            else
            {
                module = (DynamicClass)value;
            }

            Context newcontext = new Context(module, context.RootContext);

            return(this.expression.Evaluate(newcontext));
        }
Example #12
0
        public void ExecuteAssignDotCommand()
        {
            Machine machine = new Machine();
            var     @class  = new DynamicClass("Dog");
            var     method  = new DefinedFunction((new Parser("@name = name")).ParseCommand(), new string[] { "name" }, machine.RootContext);

            @class.SetInstanceMethod("name=", method);
            var nero = @class.CreateInstance();

            machine.RootContext.SetLocalValue("nero", nero);
            var leftvalue            = (DotExpression)(new Parser("nero.name")).ParseExpression();
            var value                = new ConstantExpression("Nero");
            AssignDotExpressions cmd = new AssignDotExpressions(leftvalue, value);

            var result = cmd.Evaluate(machine.RootContext);

            Assert.IsNotNull(result);
            Assert.AreEqual("Nero", result);
            Assert.AreEqual("Nero", nero.GetValue("name"));
        }
Example #13
0
        public void CanAccessDynamicObject()
        {
            var test   = new DynamicClass();
            var engine = new Engine();

            engine.SetValue("test", test);

            Assert.Equal("a", engine.Evaluate("test.a").AsString());
            Assert.Equal("b", engine.Evaluate("test.b").AsString());

            engine.Evaluate("test.a = 5; test.b = 10; test.Name = 'Jint'");

            Assert.Equal(5, engine.Evaluate("test.a").AsNumber());
            Assert.Equal(10, engine.Evaluate("test.b").AsNumber());

            Assert.Equal("Jint", engine.Evaluate("test.Name").AsString());
            Assert.True(engine.Evaluate("test.ContainsKey('a')").AsBoolean());
            Assert.True(engine.Evaluate("test.ContainsKey('b')").AsBoolean());
            Assert.False(engine.Evaluate("test.ContainsKey('c')").AsBoolean());
        }
Example #14
0
        /// <summary>
        /// Combines the property into a list
        /// new(\"First\" as field__First, \"Last\" as field__Last) ==> Dictionary[string, string]
        /// </summary>
        /// <param name="self">The self.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <returns></returns>
        public static IEnumerable<DataItem> GetDataItems(this DynamicClass self, string propertyName)
        {
            var propertyType = self.GetType();
            var propertyInfo = propertyType.GetProperty(propertyName);

            if (propertyInfo == null)
            {
                return new List<DataItem>();
            }

            var property = propertyInfo.GetValue(self, null);
            var props = property.GetType().GetProperties().Where(p => p.Name.Contains("__"));

            return props
                // Split on __ to get the prefix and the field
                .Select(prop => new { PropertyInfo = prop, Data = prop.Name.Split(new[] { "__" }, StringSplitOptions.None) })

                // Return the Fieldname, Prefix and the the value ('First' , 'field' , 'First')
                .Select(x => new DataItem { Fieldname = x.Data.Last(), Prefix = x.Data.First(), Value = x.PropertyInfo.GetValue(property, null) })
            ;
        }
Example #15
0
        public void ExecuteAssignDotCommandWithUnknownMethod()
        {
            Machine machine = new Machine();
            var     @class  = new DynamicClass("Dog");
            var     nero    = @class.CreateInstance();

            machine.RootContext.SetLocalValue("nero", nero);
            var leftvalue            = (DotExpression)(new Parser("nero.name")).ParseExpression();
            var value                = new ConstantExpression("Nero");
            AssignDotExpressions cmd = new AssignDotExpressions(leftvalue, value);

            try
            {
                cmd.Evaluate(machine.RootContext);
                Assert.Fail();
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(ex, typeof(NoMethodError));
            }
        }
Example #16
0
    public static void Main()
    {
        dynamic dateTime = new System.DateTime();

        dateTime.AddHours(1);
        try
        {
            dateTime.AnyMethod(1);
        }
        catch (RuntimeBinderException e)
        {
            Console.Out.WriteLine("Excpeted Exception: ");
            Console.Out.WriteLine(e);
        }

        dynamic dynamicClass = new DynamicClass();

        Console.WriteLine(dynamicClass());
        Console.WriteLine(dynamicClass.test());
        Console.WriteLine(dynamicClass.test);
    }
Example #17
0
        public static void Main(string[] args)
        {
            Console.WriteLine("--start");

            DynamicProperty[] props   = new DynamicProperty[] { new DynamicProperty("Name", typeof(string)), new DynamicProperty("Birthday", typeof(DateTime)) };
            Type         type         = DynamicClassFactory.CreateType(props);
            DynamicClass dynamicClass = Activator.CreateInstance(type) as DynamicClass;

            dynamicClass.SetDynamicProperty("Name", "Albert");
            dynamicClass.SetDynamicProperty("Birthday", new DateTime(1879, 3, 14));
            Console.WriteLine(dynamicClass);

            GroupByAndSelect_TestDynamicSelectMember();
            //Select();
            //TestDyn();
            //ExpressionTests_Enum();
            //Where();
            //ExpressionTests_Sum();

            Console.WriteLine("--end");
        }
Example #18
0
        public void DefineSimpleSubClass()
        {
            Machine      machine     = new Machine();
            Context      context     = machine.RootContext;
            DynamicClass animalclass = new DynamicClass("Animal", (DynamicClass)context.GetValue("Object"));

            context.SetLocalValue("Animal", animalclass);
            StringWriter writer = new StringWriter();

            context.Self.Class.SetInstanceMethod("puts", new PutsFunction(writer));
            ClassExpression expr = new ClassExpression(new NameExpression("Dog"), new CallExpression("puts", new IExpression[] { new ConstantExpression(123) }), new NameExpression("Animal"));

            var result = expr.Evaluate(context);

            Assert.IsNull(result);

            var value = context.GetValue("Dog");

            Assert.IsInstanceOfType(value, typeof(DynamicClass));
            Assert.AreEqual(value, context.GetValue("Dog"));
            Assert.AreSame(animalclass, ((DynamicClass)value).SuperClass);
            Assert.AreEqual("123\r\n", writer.ToString());
        }
        public static void Main(string[] args)
        {
            Console.WriteLine("--start");

            DynamicProperty[] props = { new DynamicProperty("Name", typeof(string)), new DynamicProperty("Birthday", typeof(DateTime)) };
            Type type = DynamicClassFactory.CreateType(props);

            DynamicProperty[] props2 = { new DynamicProperty("Name", typeof(string)), new DynamicProperty("Birthday", typeof(DateTime)) };
            Type type2 = DynamicClassFactory.CreateType(props2);

            DynamicProperty[] props3 = { new DynamicProperty("Name", typeof(int)), new DynamicProperty("Birthday", typeof(DateTime)) };
            Type type3 = DynamicClassFactory.CreateType(props3);

            DynamicClass dynamicClass = Activator.CreateInstance(type) as DynamicClass;

            dynamicClass.SetDynamicPropertyValue("Name", "Albert");
            dynamicClass.SetDynamicPropertyValue("Birthday", new DateTime(1879, 3, 14));
            Console.WriteLine(dynamicClass);

            string n1 = dynamicClass["Name"] as string;

            Console.WriteLine("dynamicClass[\"Name\"] = '" + n1 + "'");

            dynamicClass["NameX"] = "x";
            string n2 = dynamicClass["NameX"] as string;

            Console.WriteLine("dynamicClass[\"NameX\"] = '" + n2 + "'");

            //GroupByAndSelect_TestDynamicSelectMember();
            //Select();
            //TestDyn();
            //ExpressionTests_Enum();
            //Where();
            //ExpressionTests_Sum();

            Console.WriteLine("--end");
        }
Example #20
0
        public void Execute(IBindingEnvironment environment)
        {
            DynamicClass dynclass = new DynamicClass(this.name);

            int k = 0;

            if (this.memberExpressions != null)
            {
                foreach (IExpression expression in this.memberExpressions)
                {
                    string name  = this.memberNames[k++];
                    object value = null;

                    if (expression != null)
                    {
                        value = expression.Evaluate(environment);
                    }

                    dynclass.SetMember(name, value);
                }
            }

            Machine.Current.Environment.SetValue(this.name, dynclass);
        }
Example #21
0
        static void Main(string[] args)
        {
            try
            {
                // instance 생성
                DynamicClass dynamicClass = new DynamicClass();

                // NameSpace 정의
                string nameSpace = "XyncStudio";
                dynamicClass.AddNameSpace(nameSpace);

                // 추가할 Using
                string[] imports = { "InterfaceLib", "System", "System.Collections.Generic" };

                // 상속받을 Interface
                string[] references = { "IPosition", "IID" };

                // Class 생성
                dynamicClass.AddClass(nameSpace, "StepNode", TypeAttributes.Public, imports, references);

                // Method 추가
                string[]    expressions = { };
                Parameter[] param       = { };
                dynamicClass.AddMethod("StepNode", "SetPosition", System.CodeDom.MemberAttributes.Public | System.CodeDom.MemberAttributes.Final, "", expressions, param);

                // Variable
                // Double 타입 public 변수
                dynamicClass.AddVariable("StepNode", "width", Enumeration.VARIABLE_TYPE.Double.ToString(), MemberTypes.Field, System.CodeDom.MemberAttributes.Public);

                // Int32 static private변수
                dynamicClass.AddVariable("StepNode", "height", Enumeration.VARIABLE_TYPE.Int32.ToString(), MemberTypes.Field, System.CodeDom.MemberAttributes.Private | System.CodeDom.MemberAttributes.Static);

                // string const private 변수
                dynamicClass.AddVariable("StepNode", "nodeName", Enumeration.VARIABLE_TYPE.String.ToString(), MemberTypes.Field, System.CodeDom.MemberAttributes.Private);

                // 일반 적인 { get; set; } 형태
                dynamicClass.AddVariable("StepNode", "TestProperty", Enumeration.VARIABLE_TYPE.String.ToString(), MemberTypes.Property, System.CodeDom.MemberAttributes.Public | System.CodeDom.MemberAttributes.Final);

                // private 변수를 가지는 Get Set
                dynamicClass.AddVariable("StepNode", "TestProperty2", Enumeration.VARIABLE_TYPE.String.ToString(), MemberTypes.Property, System.CodeDom.MemberAttributes.Public | System.CodeDom.MemberAttributes.Final, false);

                dynamicClass.AddVariable("StepNode", "Id", "Guid", MemberTypes.Property, System.CodeDom.MemberAttributes.Public | System.CodeDom.MemberAttributes.Final);

                dynamicClass.AddVariable("StepNode", "Properties", "List<string>", MemberTypes.Field, System.CodeDom.MemberAttributes.Public);

                //
                string getMessage = string.Format($"Properties.Find(x => x == {'"'}Test{'"'});\n" + "int a = 0;");
                // private 변수를 가지는 Get Set
                dynamicClass.AddVariable("StepNode", "TestString", Enumeration.VARIABLE_TYPE.String.ToString(), MemberTypes.Property, System.CodeDom.MemberAttributes.Public | System.CodeDom.MemberAttributes.Final, getMessage);

                // Compile 할때 필요한 Dll 을 Parameter 로
                Assembly assem = dynamicClass.CompileSource("System.dll", "InterfaceLib.dll");

                if (assem != null)
                {
                    Type fType = assem.GetTypes()[0];
                    Type iType = fType.GetInterface("InterfaceLib.IPosition");

                    if (iType != null)
                    {
                        InterfaceLib.IPosition position = (IPosition)assem.CreateInstance(fType.FullName);
                        position.SetPosition();
                    }
                }

                Console.WriteLine($"NameSpace : {dynamicClass.TargetUnit.Namespaces[0].Name}");

#if DEBUG
                GenerateUtil.GenerateCSFile($"..\\Debug\\StepNode.cs", dynamicClass.TargetUnit);
#else
                GenerateUtil.GenerateCSFile($"..\\Release\\StepNode.cs", dynamicClass.TargetUnit);
#endif
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        public void CreateDefinedClass()
        {
            DynamicClass dclass = new DynamicClass("Dog");

            Assert.AreEqual("Dog", dclass.Name);
        }
        public void DynamicToString()
        {
            DynamicClass dclass = new DynamicClass("Dog");

            Assert.AreEqual("Dog", dclass.ToString());
        }
Example #24
0
        public override object Evaluate(Context context)
        {
            object       value  = null;
            DynamicClass target = null;

            if (this.namedexpression.TargetExpression == null)
            {
                if (context.Module != null)
                {
                    if (context.Module.Constants.HasLocalValue(this.namedexpression.Name))
                    {
                        value = context.Module.Constants.GetLocalValue(this.namedexpression.Name);
                    }
                }
                else if (context.HasValue(this.namedexpression.Name))
                {
                    value = context.GetValue(this.namedexpression.Name);
                }
            }
            else
            {
                object targetvalue = this.namedexpression.TargetExpression.Evaluate(context);

                if (!(targetvalue is DynamicClass))
                {
                    throw new TypeError(string.Format("{0} is not a class/module", targetvalue.ToString()));
                }

                target = (DynamicClass)targetvalue;

                if (target.Constants.HasLocalValue(this.namedexpression.Name))
                {
                    value = target.Constants.GetLocalValue(this.namedexpression.Name);
                }
            }

            if (value == null || !(value is DynamicClass))
            {
                var    classclass = (DynamicClass)context.RootContext.GetLocalValue("Class");
                var    superclass = (DynamicClass)context.RootContext.GetLocalValue("Object");
                string name       = this.namedexpression.Name;
                var    parent     = target == null ? context.Module : target;

                if (this.superclassexpression != null)
                {
                    superclass = (DynamicClass)this.superclassexpression.Evaluate(context);
                }

                var newclass = new DynamicClass(classclass, name, superclass, parent);

                if (parent == null)
                {
                    context.RootContext.SetLocalValue(name, newclass);
                }
                else
                {
                    parent.Constants.SetLocalValue(name, newclass);
                }

                value = newclass;
            }

            var dclass = (DynamicClass)value;

            Context classcontext = new Context(dclass, context);

            classcontext.Self = dclass;

            this.expression.Evaluate(classcontext);

            return(null);
        }
Example #25
0
 public Context(DynamicClass module, Context parent)
 {
     this.module = module;
     this.parent = parent;
     this.self   = module;
 }
        public void UndefinedInstanceMethodIsNull()
        {
            DynamicClass dclass = new DynamicClass("Dog");

            Assert.IsNull(dclass.GetInstanceMethod("foo"));
        }
Example #27
0
        //<SNIPPET3>
        private void getAssemblyButton_Click(object sender, EventArgs e)
        {
            DynamicClass dc = new DynamicClass();

            MessageBox.Show("Message: " + dc.Message);
        }
 public DynamicClassProxy(DynamicClass dynamicClass)
 {
     _dynamicClass = dynamicClass;
 }
        protected virtual List <IAggregateResult> MaterializeCalculateTotalAggregateResult(DynamicClass aggregateResult)
        {
            var ret = new List <IAggregateResult>();

            Criteria.Aggregates.ForEach((a, index) =>
            {
                ret.Add(new AggregateResult()
                {
                    Path  = a.Path,
                    Type  = a.Type,
                    Value = aggregateResult?.GetDynamicPropertyValue($"Agg_{index}")
                });
            });
            return(ret);
        }
Example #30
0
 public void SetUp()
 {
     this.dynclass = new DynamicClass("MyClass");
 }