void ICollectionPropertyBagVisitor.Visit <TCollection, TElement>(ICollectionPropertyBag <TCollection, TElement> properties, ref TCollection container)
                {
                    var path = Path;

                    // This query engine filter is provided with two delegates:
                    //
                    // parameterTransformer: This function is responsible for transforming the input string into a strong generic type.
                    //                       this is done via the `TypeConversion` API in properties.
                    //
                    // filterResolver:       This function takes the data for each element being filtered, along with the original token, and the
                    //                       transformed input. The function then applies the filter and returns true or false. In this particular case
                    //                       we want to test equality with each collection element and return true if ANY match.
                    //
                    QueryEngine.AddFilter <TElement, TElement>(Token, (data, _, token, transformedInput) =>
                    {
                        if (!PropertyContainer.TryGetValue <TData, TCollection>(ref data, path, out var collection))
                        {
                            return(false);
                        }

                        if (RuntimeTypeInfoCache <TCollection> .CanBeNull && null == collection)
                        {
                            return(false);
                        }

                        return(collection.Any(e => FilterOperator.ApplyOperator(token, e, transformedInput, QueryEngine.globalStringComparison)));
                    }, s => TypeConversion.Convert <string, TElement>(ref s), FilterOperator.GetSupportedOperators <TElement>());
                }
示例#2
0
    private void ToggleBool()
    {
        Variable var = ObjectController.Get().GetObject <Variable>(ObjectCategories.Variable, Name);

        var.Value = TypeConversion.Convert(typeof(bool), Value.ToString());
        Debug.Log("Bool Toggled: " + var.Name + " Value: " + var.Value.ToString());
    }
 public static void Custom_Convert_Interface_To_String_NoImpl()
 {
     Assert.Throws <Exception>(() =>
     {
         TypeConversion.Convert <string>(new TestClass());
     });
 }
示例#4
0
        public override VisualElement Build()
        {
            base.Build();
            var range     = DrawerAttribute;
            var lowValue  = Mathf.Max(range.min, LowValue);
            var highValue = Mathf.Min(range.max, HighValue);

            m_Field.lowValue  = TypeConversion.Convert <float, TFieldType>(ref lowValue);
            m_Field.highValue = TypeConversion.Convert <float, TFieldType>(ref highValue);

            var root = new VisualElement();

            root.Add(m_Field);
            m_Field.style.flexGrow = 1;
            m_ValueField           = new FloatField
            {
                name    = Name,
                label   = null,
                tooltip = Tooltip,
            };
            m_ValueField.formatString = "0.##";
            m_ValueField.RegisterValueChangedCallback(OnChanged);
            m_ValueField.style.flexGrow = 0;
            m_ValueField.style.width    = 50;
            root.Add(m_ValueField);
            root.style.flexDirection = FlexDirection.Row;
            return(root);
        }
示例#5
0
        public static Expression GetParamsMatch(Type type, Expression instance,
                                                string membername, List <Expression> args)
        {
            // assume params

            var methodInfos = type.GetMethods().Where(x => x.Name == membername);
            var matchScore  = new List <Tuple <MethodInfo, int> >();

            foreach (var info in methodInfos.OrderByDescending(m => m.GetParameters().Count()))
            {
                var parameterInfos = info.GetParameters();
                var lastParam      = parameterInfos.Last();
                var newArgs        = args.Take(parameterInfos.Length - 1).ToList();
                var paramArgs      = args.Skip(parameterInfos.Length - 1).ToList();

                int i = 0;
                int k = 0;

                foreach (var expression in newArgs)
                {
                    k += TypeConversion.CanConvert(expression.Type, parameterInfos[i].ParameterType);
                    i++;
                }

                if (k > 0)
                {
                    if (Attribute.IsDefined(lastParam, typeof(ParamArrayAttribute)))
                    {
                        k += paramArgs.Sum(arg => TypeConversion.CanConvert(arg.Type,
                                                                            lastParam.ParameterType.GetElementType()));
                    }
                }

                matchScore.Add(new Tuple <MethodInfo, int>(info, k));
            }

            var info2 = matchScore.OrderBy(x => x.Item2).FirstOrDefault(x => x.Item2 >= 0);

            if (info2 != null)
            {
                var parameterInfos2 = info2.Item1.GetParameters();
                var lastParam2      = parameterInfos2.Last();
                var newArgs2        = args.Take(parameterInfos2.Length - 1).ToList();
                var paramArgs2      = args.Skip(parameterInfos2.Length - 1).ToList();


                for (int i = 0; i < parameterInfos2.Length - 1; i++)
                {
                    newArgs2[i] = TypeConversion.Convert(newArgs2[i], parameterInfos2[i].ParameterType);
                }

                var targetType = lastParam2.ParameterType.GetElementType();

                newArgs2.Add(Expression.NewArrayInit(targetType,
                                                     paramArgs2.Select(x => TypeConversion.Convert(x, targetType))));
                return(Expression.Call(instance, info2.Item1, newArgs2));
            }
            return(null);
        }
 private void CheckForValueOrName()
 {
     Var = ObjectController.Get().GetObject <Variable>(ObjectCategories.Variable, Name);
     if (Val == null)
     {
         Comparer = (float)TypeConversion.Convert(typeof(float), Value);
     }
 }
            protected override VisitStatus Visit <TProperty, TContainer, TValue>(TProperty property, ref TContainer container, ref TValue value, ref ChangeTracker changeTracker)
            {
                if (string.Equals(property.GetName(), Name))
                {
                    value = TypeConversion.Convert <object, TValue>(Value);
                }

                return(base.Visit(property, ref container, ref value, ref changeTracker));
            }
示例#8
0
        public override VisualElement Build(InspectorContext <TValue> context)
        {
            base.Build(context);
            var range = context.Attributes.GetAttribute <RangeAttribute>();

            m_Field.lowValue  = TypeConversion.Convert <float, TFieldType>(Mathf.Max(range.min, LowValue));
            m_Field.highValue = TypeConversion.Convert <float, TFieldType>(Mathf.Min(range.max, HighValue));
            return(m_Field);
        }
示例#9
0
        public override void Update()
        {
            var value = TypeConversion.Convert <TValue, float>(Target);

            if (value != m_ValueField.value)
            {
                m_ValueField.SetValueWithoutNotify(TypeConversion.Convert <TValue, float>(Target));
            }
        }
示例#10
0
        void OnChanged(ChangeEvent <float> evt)
        {
            var clampedValue = Mathf.Clamp(evt.newValue, DrawerAttribute.min, DrawerAttribute.max);
            var value        = TypeConversion.Convert <float, TValue>(ref clampedValue);

            if (!value.Equals(Target))
            {
                Target = value;
                Update();
            }
        }
示例#11
0
        public static Expression BinaryOperatorFunc(
            OpFuncArgs args
            )
        {
            Expression re = args.ExprStack.Pop();
            Expression le = args.ExprStack.Pop();

            // perform implicit conversion on known types
            TypeConversion.Convert(ref le, ref re);
            return(((BinaryOperator)args.Op).Func(le, re));
        }
 public static void Custom_Convert_Interface_To_String()
 {
     TypeConversion.Register <ITestInterface, string>(v => "Test");
     try
     {
         Assert.AreEqual("Test", TypeConversion.Convert <string>(new TestClass()));
     }
     finally
     {
         TypeConversion.Unregister <ITestInterface, string>();
     }
 }
 public static void Custom_Convert_String_To_Class()
 {
     TypeConversion.Register <string, TestClass>(v => new TestClass(/* v */));
     try
     {
         Assert.IsNotNull(TypeConversion.Convert <TestClass>("Test"));
     }
     finally
     {
         TypeConversion.Unregister <string, TestClass>();
     }
 }
示例#14
0
        public static Expression TernaryOperatorFunc(OpFuncArgs args)
        {
            Expression falsy     = args.ExprStack.Pop();
            Expression truthy    = args.ExprStack.Pop();
            Expression condition = args.ExprStack.Pop();

            if (condition.Type != typeof(bool))
            {
                condition = Expression.Convert(condition, typeof(bool));
            }

            // perform implicit conversion on known types ???
            TypeConversion.Convert(ref falsy, ref truthy);
            return(((TernaryOperator)args.Op).Func(condition, truthy, falsy));
        }
        public static Expression GetExactMatch(Type type, Expression instance, string membername, List <Expression> args)
        {
            var argTypes = args.Select(x => x.Type);

            // Look for an exact match
            var methodInfo = type.GetMethod(membername, argTypes.ToArray());

            if (methodInfo != null)
            {
                var parameterInfos = methodInfo.GetParameters();

                for (int i = 0; i < parameterInfos.Length; i++)
                {
                    args[i] = TypeConversion.Convert(args[i], parameterInfos[i].ParameterType);
                }

                return(Expression.Call(instance, methodInfo, args));
            }
            return(null);
        }
示例#16
0
        public static Expression BinaryOperatorFunc(OpFuncArgs args)
        {
            Expression re = args.ExprStack.Pop();
            Expression le = args.ExprStack.Pop();

            // perform implicit conversion on known types
            //var isDynamic = le.Type.GetInterfaces().Contains(typeof(IDynamicMetaObjectProvider)) ||
            //    le.Type == typeof(Object);


            if (le.Type.IsDynamic() && re.Type.IsDynamic())
            {
                var expressionType = args.Op.ExpressionType;

                if (expressionType == ExpressionType.OrElse)
                {
                    le             = Expression.IsTrue(Expression.Convert(le, typeof(bool)));
                    expressionType = ExpressionType.Or;
                    return(Expression.Condition(le, Expression.Constant(true),
                                                Expression.Convert(DynamicBinaryOperatorFunc(Expression.Constant(false), re, expressionType), typeof(bool))));
                }


                if (expressionType == ExpressionType.AndAlso)
                {
                    le             = Expression.IsFalse(Expression.Convert(le, typeof(bool)));
                    expressionType = ExpressionType.And;
                    return(Expression.Condition(le, Expression.Constant(false),
                                                Expression.Convert(DynamicBinaryOperatorFunc(Expression.Constant(true), re, expressionType), typeof(bool))));
                }

                return(DynamicBinaryOperatorFunc(le, re, expressionType));
            }
            else
            {
                TypeConversion.Convert(ref le, ref re);

                return(((BinaryOperator)args.Op).Func(le, re));
            }
        }
示例#17
0
    private static void SetProperty(object obj, string property, string value, string typeOverride = "NullType")
    {
        /*Debug.Log("Properties found for " + obj.GetType().ToString() + ":");
         * foreach (PropertyInfo p in obj.GetType().GetProperties())
         * {
         * Debug.Log(p.Name);
         * }*/

        if (property == "Value")
        {
            Debug.Log("Working With Value");
        }

        PropertyInfo pInfo = obj.GetType().GetProperty(PP.GetParameterLiteralName(property));

        if (pInfo == null)
        {
            Debug.LogError(property + " was not found in type " + obj.GetType().ToString());
        }
        else
        {
            object val;
            if (typeOverride == "NullType")
            {
                val = TypeConversion.Convert(PP.GetParameterType(property), value);
            }
            else
            {
                val = TypeConversion.Convert(Type.GetType(typeOverride), value);
            }

            pInfo.SetValue(obj, val, null);
            try
            {
                Debug.Log("Successfully set " + property + " for " + obj.GetType().ToString() + " as " + pInfo.GetValue(obj, null).ToString());
            }
            catch { Debug.LogWarning("If not \"Path\", report to programmer: " + pInfo.Name); } // SoundObjs should be the only thing to cause this
        }
    }
        public void FromJson(string json)
        {
            if (string.IsNullOrEmpty(json))
            {
                return;
            }

            object workspaceObject;

            Properties.Serialization.Json.TryDeserializeObject(json, out workspaceObject);
            var workspaceDictionary = workspaceObject as IDictionary <string, object>;

            if (null != workspaceDictionary)
            {
                ActiveEntityGroup = Parser.ParseSceneReference(Parser.GetValue(workspaceDictionary, s_ActiveEntityGroupProperty.Name));

                object openedScenesObject;
                workspaceDictionary.TryGetValue(s_OpenedEntityGroupsProperty.Name, out openedScenesObject);
                var openedScenesList = openedScenesObject as IList <object>;

                if (null != openedScenesList)
                {
                    foreach (var obj in openedScenesList)
                    {
                        OpenedEntityGroups.Add(Parser.ParseSceneReference(obj));
                    }
                }

                if (workspaceDictionary.ContainsKey(s_PreviewProperty.Name))
                {
                    Preview = TypeConversion.Convert <bool>(Parser.GetValue(workspaceDictionary, s_PreviewProperty.Name));
                }

                if (workspaceDictionary.ContainsKey(s_BuildConfigurationProperty.Name))
                {
                    BuildConfiguration = (UTinyBuildConfiguration)TypeConversion.Convert <int>(Parser.GetValue(workspaceDictionary, s_BuildConfigurationProperty.Name));
                }
            }
        }
 public static void BuiltIn_Convert_Enum_To_Int()
 {
     Assert.AreEqual(3, TypeConversion.Convert <int>(TestEnum.Fourth));
 }
 public static void BuiltIn_Convert_Int_To_Enum()
 {
     Assert.AreEqual(TestEnum.Third, TypeConversion.Convert <TestEnum>(2));
 }
 public static void BuiltIn_Convert_Enum_To_String()
 {
     Assert.AreEqual("Second", TypeConversion.Convert <string>(TestEnum.Second));
 }
 public static void BuiltIn_Convert_String_To_Enum()
 {
     Assert.AreEqual(TestEnum.First, TypeConversion.Convert <TestEnum>("First"));
 }
 public static void BuiltIn_Convert_String_To_Int()
 {
     Assert.AreEqual(10, TypeConversion.Convert <int>("10"));
 }
 public static void BuiltIn_Convert_Int_To_String()
 {
     Assert.AreEqual("10", TypeConversion.Convert <string>(10));
 }
        /// <summary>
        /// Returns an Expression that accesses a member on an Expression
        /// </summary>
        /// <param name="le">The expression that contains the member to be accessed</param>
        /// <param name="membername">The name of the member to access</param>
        /// <param name="args">Optional list of arguments to be passed if the member is a method</param>
        /// <returns></returns>
        public static Expression MemberAccess(Expression le, string membername, List <Expression> args)
        {
            List <Type> argTypes = new List <Type>();

            args.ForEach(x => argTypes.Add(x.Type));

            Expression instance = null;
            Type       type     = null;

            if (le.Type.Name == "RuntimeType")
            {
                type = ((Type)((ConstantExpression)le).Value);
            }
            else
            {
                type     = le.Type;
                instance = le;
            }

            MethodInfo mi = type.GetMethod(membername, argTypes.ToArray());

            if (mi != null)
            {
                ParameterInfo[] pi = mi.GetParameters();
                for (int i = 0; i < pi.Length; i++)
                {
                    args[i] = TypeConversion.Convert(args[i], pi[i].ParameterType);
                }
                return(Expression.Call(instance, mi, args));
            }
            else
            {
                Expression exp = null;

                PropertyInfo pi = type.GetProperty(membername);
                if (pi != null)
                {
                    exp = Expression.Property(instance, pi);
                }
                else
                {
                    FieldInfo fi = type.GetField(membername);
                    if (fi != null)
                    {
                        exp = Expression.Field(instance, fi);
                    }
                }

                if (exp != null)
                {
                    if (args.Count > 0)
                    {
                        return(Expression.ArrayAccess(exp, args));
                    }
                    else
                    {
                        return(exp);
                    }
                }
                else
                {
                    throw new Exception(string.Format("Member not found: {0}.{1}", le.Type.Name, membername));
                }
            }
        }
示例#26
0
        /// <summary>
        /// Returns an Expression that accesses a member on an Expression
        /// </summary>
        /// <param name="isFunction">Determines whether the member being accessed is a function or a property</param>
        /// <param name="isCall">Determines whether the member returns void</param>
        /// <param name="le">The expression that contains the member to be accessed</param>
        /// <param name="membername">The name of the member to access</param>
        /// <param name="args">Optional list of arguments to be passed if the member is a method</param>
        /// <returns></returns>
        public static Expression MemberAccess(bool isFunction, bool isCall, Expression le, string membername, List <Expression> args)
        {
            var argTypes = args.Select(x => x.Type);

            Expression instance = null;
            Type       type     = null;

            var isDynamic     = false;
            var isRuntimeType = false;

            if (le.Type.Name == "RuntimeType")
            {
                isRuntimeType = true;
                type          = ((Type)((ConstantExpression)le).Value);
            }
            else
            {
                type      = le.Type;
                instance  = le;
                isDynamic = type.IsDynamic();
            }

            if (isFunction)
            {
                if (isDynamic)
                {
                    var expArgs = new List <Expression> {
                        instance
                    };

                    expArgs.AddRange(args);

                    if (isCall)
                    {
                        var binderMC = Binder.InvokeMember(
                            CSharpBinderFlags.ResultDiscarded,
                            membername,
                            null,
                            type,
                            expArgs.Select(x => CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null))
                            );

                        return(Expression.Dynamic(binderMC, typeof(void), expArgs));
                    }

                    var binderM = Binder.InvokeMember(
                        CSharpBinderFlags.None,
                        membername,
                        null,
                        type,
                        expArgs.Select(x => CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null))
                        );

                    return(Expression.Dynamic(binderM, typeof(object), expArgs));
                }
                else
                {
                    var mis        = MethodResolution.GetApplicableMembers(type, membername, args);
                    var methodInfo = (MethodInfo)mis[0];

                    if (methodInfo != null)
                    {
                        var parameterInfos = methodInfo.GetParameters();

                        foreach (var parameterInfo in parameterInfos)
                        {
                            var index = parameterInfo.Position;

                            args[index] = TypeConversion.Convert(args[index], parameterInfo.ParameterType);
                        }

                        return(Expression.Call(instance, methodInfo, args.ToArray()));
                    }

                    var match = MethodResolution.GetExactMatch(type, instance, membername, args) ??
                                MethodResolution.GetParamsMatch(type, instance, membername, args);

                    if (match != null)
                    {
                        return(match);
                    }
                }
            }
            else
            {
                if (isDynamic)
                {
                    var binder = Binder.GetMember(
                        CSharpBinderFlags.None,
                        membername,
                        type,
                        new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }
                        );

                    var result = Expression.Dynamic(binder, typeof(object), instance);


                    if (args.Count > 0)
                    {
                        var expArgs = new List <Expression>()
                        {
                            result
                        };

                        expArgs.AddRange(args);

                        var indexedBinder = Binder.GetIndex(
                            CSharpBinderFlags.None,
                            type,
                            expArgs.Select(x => CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null))
                            );

                        result =
                            Expression.Dynamic(indexedBinder, typeof(object), expArgs);
                    }

                    return(result);
                }
                else
                {
                    Expression exp = null;

                    var propertyInfo = type.GetProperty(membername);
                    if (propertyInfo != null)
                    {
                        exp = Expression.Property(instance, propertyInfo);
                    }
                    else
                    {
                        var fieldInfo = type.GetField(membername);
                        if (fieldInfo != null)
                        {
                            exp = Expression.Field(instance, fieldInfo);
                        }
                    }

                    if (exp != null)
                    {
                        if (args.Count > 0)
                        {
                            return(Expression.ArrayAccess(exp, args));
                        }
                        else
                        {
                            return(exp);
                        }
                    }
                }
            }

            throw new Exception(string.Format("Member not found: {0}.{1}", le.Type.Name, membername));
        }
 protected override void OnChanged(ChangeEvent <TFieldValue> evt, InspectorContext <TValue> context)
 {
     context.Data = Connector.ToValue(
         TypeConversion.Convert <float, TFieldValue>(
             Mathf.Max(m_MinValue, TypeConversion.Convert <TFieldValue, float>(evt.newValue))));
 }