Example #1
0
        internal static SetHandler GetShadowSetter(MethodInfo method)
        {
            if (AccessorsCacheCheck.PropertiesDisabled)
            {
                return((inst, v) => method.Invoke(inst, new[] { v }));
            }

            SetHandler setter;

            lock (ShadowSetters)
            {
                if (ShadowSetters.TryGetValue(method, out setter))
                {
                    return(setter);
                }
            }


            setter = DynamicMethodCompiler.CreateSetHandler(method.ReflectedType, method) ?? ((inst, v) => method.Invoke(inst, new[] { v }));

            lock (ShadowSetters)
                ShadowSetters[method] = setter;

            return(setter);
        }
Example #2
0
        /// <summary>
        /// Creates the binding functions (fills <see cref="ViewSetterCollection"/> and
        /// <see cref="ViewGetterCollection"/> or <see cref="ModelSetterCollection"/> and
        /// <see cref="ModelGetterCollection"/> with correct handlers). The handlers are
        /// dynamically compiled.
        /// </summary>
        /// <param name="sourceType">Type of the source to bound to</param>
        /// <param name="boundType">Type of the bound object</param>
        private void CreateBindingFunctions(EBindingSourceType sourceType, Type boundType)
        {
            if (sourceType == EBindingSourceType.View)
            {
                foreach (ViewHelperPropertyMappingAttribute attribute in ViewMappingDeclarations)
                {
                    if (!initializationInProgress)
                    {
                        Debug.WriteLine("View binding: " + attribute.SourcePropertyName + " -> " + attribute.declaringProperty.Name);
                    }
                    PropertyInfo sourceProp = boundType.GetProperty(attribute.SourcePropertyName);
                    ViewGetterCollection[sourceProp.Name] =
                        DynamicMethodCompiler.CreateGetHandler(boundType, sourceProp);
                    ViewSetterCollection[sourceProp.Name] =
                        DynamicMethodCompiler.CreateSetHandler(Type, attribute.declaringProperty);
                }
            }

            if (sourceType == EBindingSourceType.Model)
            {
                foreach (ModelPropertyMappingAttribute attribute in ModelMappingDeclarations)
                {
                    if (!initializationInProgress)
                    {
                        Debug.WriteLine("Model binding: " + attribute.SourcePropertyName + " -> " + attribute.declaringProperty.Name);
                    }
                    PropertyInfo sourceProp = boundType.GetProperty(attribute.SourcePropertyName);
                    ModelGetterCollection[sourceProp.Name] =
                        DynamicMethodCompiler.CreateGetHandler(boundType, sourceProp);
                    ModelSetterCollection[sourceProp.Name] =
                        DynamicMethodCompiler.CreateSetHandler(Type, attribute.declaringProperty);
                }
            }
        }
Example #3
0
        internal static Accessors GetAccessors(PropertyInfo member)
        {
            if (AccessorsCacheCheck.PropertiesDisabled)
            {
                return(new Accessors(inst => Helpers.GetPropertyValue(member, inst), (inst, v) => member.SetValue(inst, v, null)));
            }
            Accessors accessors;

            lock (Properties)
            {
                if (Properties.TryGetValue(member, out accessors))
                {
                    return(accessors);
                }
            }

            GetHandler getter = DynamicMethodCompiler.CreateGetHandler(member.ReflectedType, member) ?? (inst => Helpers.GetPropertyValue(member, inst));
            SetHandler setter = DynamicMethodCompiler.CreateSetHandler(member.ReflectedType, member) ?? ((inst, v) => member.SetValue(inst, v, null));

            accessors = new Accessors(getter, setter);

            lock (Properties)
                Properties[member] = accessors;

            return(accessors);
        }
Example #4
0
 private void ValidatePropertyGetter(string propertyName)
 {
     if (!_propertyGetters.ContainsKey(propertyName))
     {
         _propertyGetters.Add(propertyName, DynamicMethodCompiler.CreateGetHandler(_type, _type.GetProperty(propertyName)));
     }
 }
Example #5
0
        /// <summary>
        /// Examines the type of the bound object and initializes all neccessary structures
        /// that are needed before binding can start. This methods to be called once for
        /// each type passed as <paramref name="target"/> (not for each object of that type).
        /// </summary>
        /// <param name="target">bound object</param>
        /// <param name="sourceType">Type of binding (model/view helper).</param>
        private void PrepareBindingTo(IBindable target, EBindingSourceType sourceType)
        {
            if (sourceType == EBindingSourceType.Model)
            {
                PropertyInfo modelProperty = FindFieldByAttribute(Type, typeof(ModelElementAttribute));
                ModelElementType = modelProperty.GetValue(target, null).GetType();
                if (ModelElementType == null)
                {
                    throw new InvalidOperationException(string.Format("Model property for type {0} is not assigned or the property is not marked with ModelElementAttribute", Type));
                }
                if (!initializationInProgress)
                {
                    Debug.WriteLine("Model binding for type " + target.GetType().Name + " with model type " + ModelElementType.Name);
                }
                ModelSourceGetter = DynamicMethodCompiler.CreateGetHandler(ModelElementType, modelProperty);
                CreateBindingFunctions(sourceType, ModelElementType);
            }

            if (sourceType == EBindingSourceType.View)
            {
                PropertyInfo viewHelperProperty = FindFieldByAttribute(Type, typeof(ViewHelperElementAttribute));
                ViewHelperType = viewHelperProperty.GetValue(target, null).GetType();
                if (ViewHelperType == null)
                {
                    throw new InvalidOperationException(string.Format("ViewHelper for type {0} is not assigned or the property is not marked with ViewHelperElementAttribute", Type));
                }
                if (!initializationInProgress)
                {
                    Debug.WriteLine("View binding for type " + target.GetType().Name + " with view type " + ViewHelperType.Name);
                }
                ViewSourceGetter = DynamicMethodCompiler.CreateGetHandler(ViewHelperType, viewHelperProperty);
                CreateBindingFunctions(sourceType, ViewHelperType);
            }
        }
Example #6
0
        internal static Accessors GetAccessors(FieldInfo member)
        {
            if (AccessorsCacheCheck.PropertiesDisabled)
            {
                return(new Accessors(member.GetValue, member.SetValue));
            }
            Accessors accessors;

            lock (Fields)
            {
                if (Fields.TryGetValue(member, out accessors))
                {
                    return(accessors);
                }
            }

            GetHandler getter = DynamicMethodCompiler.CreateGetHandler(member.ReflectedType, member) ?? member.GetValue;
            SetHandler setter = DynamicMethodCompiler.CreateSetHandler(member.ReflectedType, member) ?? member.SetValue;

            accessors = new Accessors(getter, setter);

            lock (Fields)
                Fields[member] = accessors;

            return(accessors);
        }
Example #7
0
        static AccessorsCacheCheck()
        {
            var test = new TestClass();

            try
            {
                DynamicMethodCompiler.CreateSetHandler(
                    typeof(AccessorsCache),
                    typeof(TestClass).GetField("x", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))(test, 55);
            }
            catch
            {
            }
            if (test.GetX() != 55)
            {
                FieldsDisabled = true;
            }

            try
            {
                DynamicMethodCompiler.CreateSetHandler(
                    typeof(AccessorsCache),
                    typeof(TestClass).GetProperty("Y", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))(test, 55);
            }
            catch
            {
            }
            if (test.GetY() != 55)
            {
                PropertiesDisabled = true;
            }
        }
Example #8
0
        internal static GetHandler GetShadowGetter(MethodInfo method)
        {
            if (AccessorsCacheCheck.PropertiesDisabled)
            {
                return(inst => method.Invoke(inst, null));
            }

            GetHandler getter;

            lock (ShadowGetters)
            {
                if (ShadowGetters.TryGetValue(method, out getter))
                {
                    return(getter);
                }
            }


            getter = DynamicMethodCompiler.CreateGetHandler(method.ReflectedType, method) ?? (inst => method.Invoke(inst, null));

            lock (ShadowGetters)
                ShadowGetters[method] = getter;

            return(getter);
        }
Example #9
0
        private static void CheckAttributesNotNull(Type type, CommandBase command, IDictionary <Type, Dictionary <string, GetHandler> > getterDictionary, Type attributeType, string errorMsg, bool holderValues)
        {
            if (!getterDictionary.ContainsKey(type))
            {
                getterDictionary[type] = new Dictionary <String, GetHandler>();
                foreach (PropertyInfo property in type.GetProperties())
                {
                    if (property.GetCustomAttributes(attributeType, true).Length > 0)
                    {
                        getterDictionary[type][property.Name] = DynamicMethodCompiler.CreateGetHandler(type, property);
                    }
                }
            }

            foreach (KeyValuePair <string, GetHandler> getHandler in getterDictionary[type])
            {
                object value = getHandler.Value(command);
                if (value == null)
                {
                    Debug.Fail(String.Format(errorMsg, command, getHandler.Key));
                }
                if (holderValues)
                {
                    IHolder holder = value as IHolder;
                    if (holder != null)
                    {
                        if (holder.WrappedValue == null)
                        {
                            Debug.Fail(String.Format(errorMsg, command, getHandler.Key));
                        }
                    }
                }
            }
        }
Example #10
0
        public static Object GetPropertyValue(Object obj, PropertyInfo property)
        {
            //创建Set委托
            GetHandler getter = DynamicMethodCompiler.CreateGetHandler(obj.GetType(), property);

            //获取属性值
            return(getter(obj));
        }
Example #11
0
        public static Object GetFieldValue(Object obj, FieldInfo field)
        {
            //创建Set委托
            GetHandler getter = DynamicMethodCompiler.CreateGetHandler(obj.GetType(), field);

            //获取字段值
            return(getter(obj));
        }
        private void BuildSetter()
        {
            Setter   = new SetHandler[rdr.FieldCount];
            EnumType = new Type[rdr.FieldCount];

            Type     tp = typeof(TEntity);
            TableDef td = MetaData.GetTableDef(tp);

            for (int i = 0; i < rdr.FieldCount; i++)
            {
                string   Name = rdr.GetName(i);
                FieldDef fld  = td.GetFieldDef(Name);
                if (fld != null)
                {
                    Setter[i] = fld.GetLoadSetHandler();
                    if (fld.IsEnum)
                    {
                        EnumType[i] = fld.FieldType;
                    }
                }
                else
                {
                    MemberInfo[] mis = tp.GetMember("_" + Name,
                                                    BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                    if (mis.Length == 0)
                    {
                        mis = tp.GetMember(Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                    }
                    if (mis.Length == 0)
                    {
                        Setter[i] = null;
                    }
                    else
                    {
                        if (mis[0].MemberType == MemberTypes.Field)
                        {
                            Type ft = ((FieldInfo)mis[0]).FieldType;
                            if (ft.IsEnum)
                            {
                                EnumType[i] = ft;
                            }
                        }
                        else
                        {
                            Type ft = ((PropertyInfo)mis[0]).PropertyType;
                            if (ft.IsEnum)
                            {
                                EnumType[i] = ft;
                            }
                        }
                        Setter[i] = DynamicMethodCompiler.CreateSetHandler(mis[0]);
                    }
                }
            }
        }
Example #13
0
        private Dictionary <string, object> CalculteValues <T>(T parameter, IEnumerable <PropertyInfo> props)
        {
            Dictionary <string, object> values = new Dictionary <string, object>();
            var type = typeof(T);

            foreach (var prop in props)
            {
                values.Add(prop.Name, DynamicMethodCompiler.CreateGetHandler(type, prop)(parameter));
            }
            return(values);
        }
Example #14
0
 private void ValidateFieldGetter(string fieldName)
 {
     if (!_fieldGetters.ContainsKey(fieldName))
     {
         FieldInfo fieldInfo = _type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
         if (fieldInfo == null)
         {
             throw new ArgumentOutOfRangeException(fieldName, "Unable to find fieldname");
         }
         _fieldGetters.Add(fieldName, DynamicMethodCompiler.CreateGetHandler(_type, fieldInfo));
     }
 }
Example #15
0
        private void AssignValue <T>(IDataReader reader, IEnumerable <string> allFieldNames, PropertyInfo propertyInfo, T target)
        {
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }
            if (propertyInfo == null)
            {
                throw new ArgumentNullException(nameof(propertyInfo));
            }
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            string col      = GetColumnName(propertyInfo);
            string typeName = typeof(T).FullName;

            if (allFieldNames.Where(a => a.Equals(col, StringComparison.InvariantCultureIgnoreCase)).Any())
            {
                var index = reader.GetOrdinal(col);
                var value = reader.GetValue(index);
                if (value == DBNull.Value)
                {
                    value = null;
                }

                if (index > -1)
                {
                    var type = typeof(T);
                    if (propertyInfo.PropertyType.IsEnum)
                    {
                        DynamicMethodCompiler.CreateSetHandler(type, propertyInfo)(target, Enum.ToObject(propertyInfo.PropertyType, value));
                    }
                    else
                    {
                        var handler = DynamicMethodCompiler.CreateSetHandler(type, propertyInfo);
                        handler(target, ConvertTo(propertyInfo.PropertyType, value));
                        //try
                        //{
                        //    handler(target, value);
                        //}
                        //catch
                        //{
                        //    handler(target, ConvertTo(propertyInfo.PropertyType, value));
                        //}
                    }
                }
            }
        }
Example #16
0
        public static void SetFieldValue(Object obj, FieldInfo field, Object value)
        {
            //创建Set委托
            SetHandler setter = DynamicMethodCompiler.CreateSetHandler(obj.GetType(), field);

            //先获取该私有成员的数据类型
            Type type = field.FieldType;

            //通过数据类型转换
            value = TypeUtils.ConvertForType(value, type);

            //将值设置到对象中
            setter(obj, value);
        }
Example #17
0
        public static void SetPropertyValue(Object obj, PropertyInfo property, Object value)
        {
            //创建Set委托
            SetHandler setter = DynamicMethodCompiler.CreateSetHandler(obj.GetType(), property);

            //先获取该私有成员的数据类型
            Type type = property.PropertyType;

            //通过数据类型转换
            value = TypeUtils.ConvertForType(value, type);

            //将值设置到对象中
            setter(obj, value);
        }
        public static object CreateInstance(Type ObjectType, params object[] args)
        {
            Type NewType = GetObjType(ObjectType);

            if (args == null)
            {
                InstantiateObjectHandler NewMethod;
                if (!ListNewType.TryGetValue(NewType, out NewMethod))
                {
                    NewMethod = DynamicMethodCompiler.CreateInstantiateObjectHandler(NewType);
                    ListNewType.Add(NewType, NewMethod);
                }
                return(NewMethod());
            }
            else
            {
                return(Activator.CreateInstance(NewType, args));
            }
        }
Example #19
0
        private IDbCommand CreateCommandByObject <T>(string commandText, T parameter)
        {
            var commd = Connection.CreateCommand();

            commd.Transaction    = Transaction;
            commd.CommandText    = ReplaceProfixTag(commandText);
            commd.CommandTimeout = DefaultCommandTimeoutBySeconds;

            var commandType = commd.GetType();
            var type        = typeof(T);

            PropertyInfo[] props = type.GetProperties();

            foreach (var prop in props)
            {
                var handler = DynamicMethodCompiler.CreateGetHandler(type, prop);
                commd.Parameters.Add(CreateIDataParameter(TagName + GetColumnName(prop), handler(parameter), ParameterDirection.Input));
            }
            return(commd);
        }
Example #20
0
            public xCol(GridColumn gcol,
                        RepositoryItemLookUpEditBase rle, TableDef td, Type ParentType)
            {
                this.rle = rle;
                if (td != null)
                {
                    fldDisplay = td[rle.DisplayMember] ?? td[gcol.FieldName];
                }

                if (fldDisplay == null)
                {
                    DisplayMember = rle.DisplayMember;
                }

                if (ParentType != null)
                {
                    GetSrcHandler = DynamicMethodCompiler.CreateGetHandler(
                        ParentType.GetMember(
                            ((BindingSource)rle.DataSource).DataMember)[0]);
                }
            }
Example #21
0
        private static void CheckAttributesNotNull(Type type, CommandBase command, IDictionary <Type, Dictionary <string, GetHandler> > getterDictionary, Type attributeType, string errorMsg)
        {
            #if SILVERLIGHT
            foreach (PropertyInfo property in type.GetProperties())
            {
                if (property.GetCustomAttributes(attributeType, true).Length > 0)
                {
                    object value = property.GetValue(command, null);
                    if (value == null)
                    {
                        Debug.Assert(false, String.Format(errorMsg, command, property.Name));
                    }
                }
            }
            #else
            if (!getterDictionary.ContainsKey(type))
            {
                getterDictionary[type] = new Dictionary <String, GetHandler>();
                foreach (PropertyInfo property in type.GetProperties())
                {
                    object[] customAttributes = property.GetCustomAttributes(attributeType, true);
                    if (customAttributes.Length > 0 && !((PublicArgumentAttribute)customAttributes[0]).AllowNullInput)
                    {
                        getterDictionary[type][property.Name] = DynamicMethodCompiler.CreateGetHandler(type, property);
                    }
                }
            }

            foreach (KeyValuePair <string, GetHandler> getHandler in getterDictionary[type])
            {
                object value = getHandler.Value(command);
                if (value == null)
                {
                    Debug.Assert(false, String.Format(errorMsg, command, getHandler.Key));
                }
            }
            #endif
        }
Example #22
0
        /// <summary>
        /// Creates new <see cref="PropertyBinder"/>, bject that copies value of a
        /// property from one object to another object each time the value
        /// changes.
        /// </summary>
        /// <param name="source">Source object</param>
        /// <param name="target">Target object</param>
        /// <param name="sourceField">Field of the <paramref name="source"/> that is bound to <paramref name="targetField"/></param>
        /// <param name="targetField">Field of the <paramref name="target"/> that recieves updated values of from <paramref name="sourceField"/></param>
        public PropertyBinder(INotifyPropertyChanged source, object target, string sourceField, string targetField, Dictionary <KeyValuePair <Type, string>, GetHandler> getCache, Dictionary <KeyValuePair <Type, string>, SetHandler> setCache)
        {
            Source      = source;
            Target      = target;
            SourceField = sourceField;
            TargetField = targetField;

            Source.PropertyChanged += Source_PropertyChanged;
            KeyValuePair <Type, string> keyGet = new KeyValuePair <Type, string>(source.GetType(), sourceField);
            KeyValuePair <Type, string> keySet = new KeyValuePair <Type, string>(target.GetType(), targetField);

            if (getCache.ContainsKey(keyGet))
            {
                sourceGetHandler = getCache[keyGet];
            }
            else
            {
                PropertyInfo sourceProp = Source.GetType().GetProperty(SourceField);
                sourceGetHandler = DynamicMethodCompiler.CreateGetHandler(Source.GetType(), sourceProp);                 /**/
                getCache[keyGet] = sourceGetHandler;
            }

            if (getCache.ContainsKey(keySet))
            {
                targetSetHandler = setCache[keySet];
            }
            if (targetSetHandler == null)
            {
                PropertyInfo targetProp = Target.GetType().GetProperty(TargetField);                     /**/
                targetSetHandler = DynamicMethodCompiler.CreateSetHandler(Target.GetType(), targetProp); /**/
                setCache[keySet] = targetSetHandler;
            }

            //Debug.Assert(sourceProp != null, "Source property not found");
            //Debug.Assert(targetProp != null, "Target property not found");

            Source_PropertyChanged(null, new PropertyChangedEventArgs(SourceField));
        }
        public void Write(object obj, object val)
        {
            string strType = field.FieldType.ToString();

            if ((val != null) && !field.FieldType.Equals(val.GetType()))
            {
                switch (strType)
                {
                case "System.String":
                    val = Convert.ToString(val);
                    break;

                case "System.Int16":
                    val = Convert.ToInt16(val);
                    break;

                case "System.Int32":
                    val = Convert.ToInt32(val);
                    break;

                case "System.Int64":
                    val = Convert.ToInt64(val);
                    break;

                case "System.Decimal":
                    val = Convert.ToDecimal(val);
                    break;

                case "System.DateTime":
                    val = Convert.ToDateTime(val);
                    break;
                }
            }

            DynamicMethodCompiler.GetCachedSetFieldHandlerDelegate(obj.GetType(), field)(obj, val);
        }
 public object Read(object obj)
 {
     return(DynamicMethodCompiler.GetCachedGetFieldHandlerDelegate(obj.GetType(), field)(obj));
 }