public AliasToBeanResultTransformer(System.Type resultClass)
		{
			if (resultClass == null)
			{
				throw new ArgumentNullException("resultClass");
			}
			this.resultClass = resultClass;

			constructor = resultClass.GetConstructor(flags, null, System.Type.EmptyTypes, null);

			// if resultClass is a ValueType (struct), GetConstructor will return null... 
			// in that case, we'll use Activator.CreateInstance instead of the ConstructorInfo to create instances
			if (constructor == null && resultClass.IsClass)
			{
				throw new ArgumentException("The target class of a AliasToBeanResultTransformer need a parameter-less constructor",
				                            "resultClass");
			}

			propertyAccessor =
				new ChainedPropertyAccessor(new[]
				                            	{
				                            		PropertyAccessorFactory.GetPropertyAccessor(null),
				                            		PropertyAccessorFactory.GetPropertyAccessor("field")
				                            	});
		}
        /// <summary>
        /// Finds the <see cref="IGetter"/> for the property in the <see cref="System.Type"/>.
        /// </summary>
        /// <param name="theClass"></param>
        /// <param name="propertyName"></param>
        /// <param name="propertyAccessorName"></param>
        /// <returns></returns>
        /// <remarks>
        /// This one takes a propertyAccessor name as we might know the correct strategy by now so we avoid Exceptions which are costly
        /// </remarks>
        public static IGetter GetGetter(System.Type theClass, string propertyName, string propertyAccessorName)
        {
            IPropertyAccessor accessor = null;

            accessor = PropertyAccessorFactory.GetPropertyAccessor(propertyAccessorName);
            return(accessor.GetGetter(theClass, propertyName));
        }
        /// <summary>
        /// Updates the under laying model.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="index">The index.</param>
        /// <param name="updatedData">The updated data.</param>
        protected void UpdateUnderLayingModel(string path, int index, object updatedData)
        {
            var          enumerator = ItemsSource.GetEnumerator();
            PropertyInfo yPropertyInfo;

            if (enumerator.MoveNext())
            {
                yPropertyInfo = ChartDataUtils.GetPropertyInfo(enumerator.Current, path);
                IPropertyAccessor yPropertyAccessor = null;
                if (yPropertyInfo != null)
                {
                    yPropertyAccessor = FastReflectionCaches.PropertyAccessorCache.Get(yPropertyInfo);
                }
                int i = 0;
                do
                {
                    if (i == index)
                    {
                        yPropertyAccessor.SetValue(enumerator.Current, updatedData);
                        break;
                    }

                    i++;
                }while (enumerator.MoveNext());
            }
        }
Example #4
0
        public static object Coerce([NotNull] IPropertyAccessor property,
                                    [CanBeNull] object rawValue)
        {
            Type propertyType = GetUnderlyingType(property);

            return(Coerce(propertyType, rawValue));
        }
Example #5
0
 protected ValidatingPropertyAccessorBase(WeakReference reference, string name, IPropertyAccessor accessor, Action <IValidationStatus> callback)
 {
     _reference = reference;
     _name      = name;
     _accessor  = accessor;
     _callback  = callback;
 }
Example #6
0
        public PropertyBindingExpression Bind(
            [NotNull] Expression <Func <M, object> > expression)
        {
            IPropertyAccessor accessor = ReflectionHelper.GetPropertyAccessor(expression);

            return(new PropertyBindingExpression(this, accessor));
        }
Example #7
0
        /// <summary>
        /// Constructs this type
        /// </summary>
        /// <param name="accessor">The data accessor</param>
        /// <param name="item">The contained item</param>
        public FieldExposer(IPropertyAccessor <T_Item> accessor, T_Item item)
        {
            Accessor     = accessor;
            InnerItem    = item;
            CachedValues = new Dictionary <string, object>();
            if (InnerItem is INotifyPropertyChanged)
            {
                ((INotifyPropertyChanged)InnerItem).PropertyChanged +=
                    (o, a) =>
                {
                    if (string.IsNullOrEmpty(a.PropertyName))
                    {
                        CachedValues.Clear();
                    }
                    else
                    {
                        CachedValues.Remove(a.PropertyName);
                    }

                    if (PropertyChanged != null)
                    {
                        PropertyChanged(this, a);
                    }
                };
            }
        }
Example #8
0
        public override object GetValue(object value, object blittableValue)
        {
            var valueType = value?.GetType();

            if (_accessorType != valueType)
            {
                _accessor = null;
            }

            if (_accessor == null)
            {
                _accessor     = TypeConverter.GetPropertyAccessor(value);
                _accessorType = valueType;
            }

            value          = _accessor.GetValue(_field.Name, value);
            blittableValue = null;

            if (_field is SimpleField)
            {
                blittableValue = TypeConverter.ToBlittableSupportedType(value);
            }

            return(_field.GetValue(value, blittableValue));
        }
        public PocoComponentTuplizer(Mapping.Component component) : base(component)
        {
            componentClass = component.ComponentClass;

            string parentPropertyName = component.ParentProperty;

            if (parentPropertyName == null)
            {
                parentSetter = null;
                parentGetter = null;
            }
            else
            {
                IPropertyAccessor pa = PropertyAccessorFactory.GetPropertyAccessor(null);
                parentSetter = pa.GetSetter(componentClass, parentPropertyName);
                parentGetter = pa.GetGetter(componentClass, parentPropertyName);
            }

            if (hasCustomAccessors || !Cfg.Environment.UseReflectionOptimizer)
            {
                optimizer = null;
            }
            else
            {
                optimizer = Cfg.Environment.BytecodeProvider.GetReflectionOptimizer(componentClass, getters, setters);
            }
        }
Example #10
0
        public Expected OfProperty(string propertyName, object value = null, bool isReference = false)
        {
            SetSourcePropertyValue(propertyName, value);

            property = propertyFactory.Create(source, propertyName, isReference, validationAttributes);
            return(this);
        }
Example #11
0
        public PropertyAccessor(Type targetType, PropertyInfo propertyInfo)
        {
            Guard.NotNull(targetType, nameof(targetType));
            Guard.NotNull(propertyInfo, nameof(propertyInfo));

            internalAccessor = (IPropertyAccessor)Activator.CreateInstance(typeof(PropertyWrapper <,>).MakeGenericType(propertyInfo.DeclaringType, propertyInfo.PropertyType), propertyInfo);
        }
Example #12
0
        public virtual InternalEntityEntry GetPrincipal(IPropertyAccessor dependentEntry, IForeignKey foreignKey)
        {
            var dependentKeyValue = dependentEntry.GetDependentKeyValue(foreignKey);

            if (dependentKeyValue == EntityKey.InvalidEntityKey)
            {
                return(null);
            }

            var principalEntityType = foreignKey.PrincipalEntityType;
            var principalProperties = foreignKey.PrincipalKey.Properties;

            // TODO: Perf: Add additional indexes so that this isn't a linear lookup
            var principals = Entries.Where(
                e => e.EntityType == principalEntityType &&
                dependentKeyValue.Equals(
                    e.GetPrincipalKey(foreignKey, principalEntityType, principalProperties))).ToList();

            if (principals.Count > 1)
            {
                // TODO: Better exception message
                // Issue #739
                throw new InvalidOperationException("Multiple matching principals.");
            }

            return(principals.FirstOrDefault());
        }
Example #13
0
        public void SetEntityMembers <T>(IDataReader reader, T entity)
        {
            int count = reader.FieldCount;

            for (int i = 0; i < count; i++)
            {
                PropertyInfo property;
                if (reader[i] != DBNull.Value)
                {
                    //如果列名=实体字段名
                    if ((property = typeof(T).GetProperty(reader.GetName(i), BindFlag)) != null)
                    {
                        IPropertyAccessor propertyAccessor = Caches.PropertyAccessorCache.Get(property);
                        propertyAccessor.SetValue(entity, reader[i]);
                    }
                    else
                    {
                        //如果列名!=实体字段名
                        string propertyname = Caches.EntityInfoCache.Get(typeof(T)).Columns.FirstOrDefault(m => m.Value == reader.GetName(i)).Key;
                        if (!string.IsNullOrEmpty(propertyname) && (property = typeof(T).GetProperty(propertyname, BindFlag)) != null)
                        {
                            IPropertyAccessor propertyAccessor = Caches.PropertyAccessorCache.Get(property);
                            propertyAccessor.SetValue(entity, reader[i]);
                        }
                    }
                }
            }
        }
Example #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TextEditingElement&lt;CONTROLTYPE&gt;"/> class.
        /// </summary>
        /// <param name="property">The property.</param>
        /// <param name="control">The control.</param>
        protected TextEditingElement([NotNull] IPropertyAccessor property,
                                     [NotNull] CONTROLTYPE control)
            : base(property, control)
        {
            SetupEvents(control);

            if (CoercionUtility.IsNumeric(property.PropertyType))
            {
                SetRightAligned(control);
            }

            if (property.PropertyType == typeof(string))
            {
                int?length = MaximumStringLengthAttribute.GetLength(
                    property.InnerProperty);

                if (length.HasValue)
                {
                    SetMaximumLength(length.Value);
                }
            }

            _coercion = delegate(IPropertyAccessor accessor, string rawValue)
            {
                // default coercion
                return(CoercionUtility.Coerce(accessor, rawValue));
            };

            _format = delegate(object o) { return(o.ToString()); };
        }
Example #15
0
        /// <summary>
        /// プロパティ情報をアクセッサに変更します
        /// </summary>
        /// <param name="pi">プロパティ情報</param>
        /// <returns>アクセッサ</returns>
        public static IPropertyAccessor PropertyInfoToAccessor(PropertyInfo pi)
        {
            Type     getterDelegateType = typeof(Func <,>).MakeGenericType(pi.DeclaringType, pi.PropertyType);
            var      getMethodInfo      = pi.GetGetMethod();
            Delegate getter             = null;

            if (getMethodInfo != null)
            {
                getter = Delegate.CreateDelegate(getterDelegateType, getMethodInfo);
            }

            Type     setterDelegateType = typeof(Action <,>).MakeGenericType(pi.DeclaringType, pi.PropertyType);
            var      setMethodInfo      = pi.GetSetMethod();
            Delegate setter             = null;

            if (setMethodInfo != null)
            {
                setter = Delegate.CreateDelegate(setterDelegateType, setMethodInfo);
            }

            Type accessorType          = typeof(PropertyAccessor <,>).MakeGenericType(pi.DeclaringType, pi.PropertyType);
            IPropertyAccessor accessor = (IPropertyAccessor)Activator.CreateInstance(accessorType, getter, setter);

            return(accessor);
        }
Example #16
0
 public static void SetValues(this IPropertyAccessor propertyAccessor, Dictionary <IProperty, object> values)
 {
     foreach (var value in values)
     {
         propertyAccessor[value.Key] = value.Value;
     }
 }
Example #17
0
        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="source"></param>
        /// <param name="property"></param>
        /// <param name="parentProperty"></param>
        /// <returns></returns>
        public IEnumerable <ValidationResult> Validate(object source, IPropertyAccessor property, IPropertyAccessor parentProperty)
        {
            var results = new List <ValidationResult>();
            var context = new ValidationContext(source)
            {
                MemberName = property.Name
            };

            var value = property.GetValue(source);

            Validator.TryValidateProperty(value, context, results);

            foreach (var result in results)
            {
                // TODO replace to NullObject
                if (parentProperty == null)
                {
                    yield return(result);
                }
                else
                {
                    var memberNames = result.MemberNames.Select(n => $"{parentProperty.Name}.{n}");
                    yield return(new ValidationResult(result.ErrorMessage, memberNames));
                }
            }
        }
 protected ValidatingPropertyAccessorBase(WeakReference reference, string name, IPropertyAccessor accessor, Action<IValidationStatus> callback)
 {
     _reference = reference;
     _name = name;
     _accessor = accessor;
     _callback = callback;
 }
Example #19
0
        public void Initialize(Type concreteType, IGenericMapperConfiguration config)
        {
            // Get JSON accessor
            var jsonColumn = typeof(IGenericColumns).GetProperty(config.JsonColumn);

            _jsonAccessor = ReflectionTool.PropertyAccessor <IGenericColumns, string>(jsonColumn);

            var baseProperties       = typeof(TBase).GetProperties().Select(p => p.Name).ToArray();
            var configuredProperties = config.PropertyConfigs.Select(cm => cm.PropertyName);

            var readOnlyProperties = concreteType.GetProperties()
                                     .Where(p => p.GetSetMethod() == null).Select(p => p.Name).ToArray();

            // The json should not contain base, configured nor readonly properties
            var jsonIgnoredProperties = baseProperties
                                        .Concat(configuredProperties)
                                        .Concat(readOnlyProperties).ToArray();

            _jsonSettings = JsonSettings.Minimal
                            .Overwrite(j => j.ContractResolver = new DifferentialContractResolver <TReference>(jsonIgnoredProperties));

            // Properties where no mapper should be created for: base and read only properties
            var mapperIgnoredProperties = baseProperties
                                          .Concat(readOnlyProperties).ToArray();

            _configuredMappers = config.PropertyConfigs.Where(pc => !mapperIgnoredProperties.Contains(pc.PropertyName))
                                 .Select(pc => MapperFactory.Create(pc, concreteType)).ToArray();
        }
Example #20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CheckboxElement"/> class.
 /// </summary>
 /// <param name="accessor">The accessor.</param>
 /// <param name="control">The control.</param>
 public CheckboxElement([NotNull] IPropertyAccessor accessor,
                        [NotNull] CheckBox control)
     : base(accessor, control)
 {
     control.CheckedChanged += control_CheckedChanged;
     Alias = control.Text;
 }
        public void Initialize(PropertyMapperConfig config)
        {
            Config = config;

            // Create accessor for the column property
            var columnProp = typeof(IGenericColumns).GetProperty(config.Column);

            if (columnProp == null || columnProp.PropertyType != typeof(TColumn))
            {
                throw new ArgumentException($"Column not found or type mismatch {config.PropertyName}");
            }

            ColumnAccessor = ReflectionTool.PropertyAccessor <IGenericColumns, TColumn>(columnProp);

            // Retrieve and validate properties
            var objectProp = TargetType.GetProperty(config.PropertyName);

            if (objectProp == null)
            {
                throw new ArgumentException($"Target type {TargetType.Name} does not have a property {config.PropertyName}");
            }

            // Create delegates for the object property as well
            ObjectAccessor = CreatePropertyAccessor(objectProp);
        }
        protected override void StartListeningCore(WeakReference <object> reference)
        {
            reference.TryGetTarget(out object target);

            var plugin   = ExpressionObserver.PropertyAccessors.FirstOrDefault(x => x.Match(target, PropertyName));
            var accessor = plugin?.Start(reference, PropertyName);

            if (_enableValidation && Next == null)
            {
                foreach (var validator in ExpressionObserver.DataValidators)
                {
                    if (validator.Match(reference, PropertyName))
                    {
                        accessor = validator.Start(reference, PropertyName, accessor);
                    }
                }
            }

            if (accessor == null)
            {
                throw new NotSupportedException(
                          $"Could not find a matching property accessor for {PropertyName}.");
            }

            _accessor = accessor;
            accessor.Subscribe(ValueChanged);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="Mobile.Mvvm.DataBinding.WeakBindingExpression"/> class.
        /// </summary>
        public WeakBindingExpression(object target, string targetProperty, IPropertyAccessor accessor, object source, Binding binding)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }
            
            if (string.IsNullOrEmpty(targetProperty))
            {
                throw new ArgumentNullException("targetProperty");
            }
            
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            
            if (accessor == null)
            {
                throw new ArgumentNullException("accessor");
            }

            if (binding == null)
            {
                throw new ArgumentNullException("binding");
            }
            
            this.SafelyUpdateTarget = true;
            this.PropertyAccessor = accessor;
            this.Initialize(target, targetProperty, source, binding);
        }
Example #24
0
 public AggregatedAnonymousObjects(List <object> results, IPropertyAccessor propertyAccessor, JsonOperationContext indexContext)
 {
     _outputs          = results;
     _propertyAccessor = propertyAccessor;
     _jsons            = new List <BlittableJsonReaderObject>(results.Count);
     _indexContext     = indexContext;
 }
Example #25
0
        protected override IObservable<object> StartListeningCore(WeakReference reference)
        {
            var plugin = ExpressionObserver.PropertyAccessors.FirstOrDefault(x => x.Match(reference));
            var accessor = plugin?.Start(reference, PropertyName);

            if (_enableValidation && Next == null)
            {
                foreach (var validator in ExpressionObserver.DataValidators)
                {
                    if (validator.Match(reference, PropertyName))
                    {
                        accessor = validator.Start(reference, PropertyName, accessor);
                    }
                }
            }

            // Ensure that _accessor is set for the duration of the subscription.
            return Observable.Using(
                () =>
                {
                    _accessor = accessor;
                    return Disposable.Create(() => _accessor = null);
                },
                _ => accessor);
        }
        public AliasToBeanResultTransformer(System.Type resultClass)
        {
            if (resultClass == null)
            {
                throw new ArgumentNullException("resultClass");
            }
            this.resultClass = resultClass;

            constructor = resultClass.GetConstructor(flags, null, System.Type.EmptyTypes, null);

            // if resultClass is a ValueType (struct), GetConstructor will return null...
            // in that case, we'll use Activator.CreateInstance instead of the ConstructorInfo to create instances
            if (constructor == null && resultClass.IsClass)
            {
                throw new ArgumentException("The target class of a AliasToBeanResultTransformer need a parameter-less constructor",
                                            "resultClass");
            }

            propertyAccessor =
                new ChainedPropertyAccessor(new[]
            {
                PropertyAccessorFactory.GetPropertyAccessor(null),
                PropertyAccessorFactory.GetPropertyAccessor("field")
            });
        }
Example #27
0
        protected override IObservable <object> StartListeningCore(WeakReference reference)
        {
            var plugin   = ExpressionObserver.PropertyAccessors.FirstOrDefault(x => x.Match(reference));
            var accessor = plugin?.Start(reference, PropertyName);

            if (_enableValidation && Next == null)
            {
                foreach (var validator in ExpressionObserver.DataValidators)
                {
                    if (validator.Match(reference, PropertyName))
                    {
                        accessor = validator.Start(reference, PropertyName, accessor);
                    }
                }
            }

            // Ensure that _accessor is set for the duration of the subscription.
            return(Observable.Using(
                       () =>
            {
                _accessor = accessor;
                return Disposable.Create(() => _accessor = null);
            },
                       _ => accessor));
        }
        public SourceBinding(Object?source,
                             PropertyInfo srcProp,
                             IVisualElement target,
                             PropertyInfo targetProp,
                             IValueConverter?valueConverter,
                             IPropertyAccessor sourcePropertyAccessor)
        {
            ValueConverter          = valueConverter;
            _source                 = source;
            _srcProp                = srcProp;
            _sourcePropertyName     = srcProp.Name;
            _target                 = target;
            _targetProp             = targetProp;
            _sourcePropertyAccessor = sourcePropertyAccessor;
            _targetPropertyName     = targetProp.Name;


            _targetSetter = targetProp.GetSetMethod();

            _targetGetter = targetProp.GetGetMethod()
                            ?? throw new MissingMethodException(_targetPropertyName);

            AddChangeListenersToSource(source);

            if (GetType() == typeof(SourceBinding) &&
                typeof(INotifyCollectionChanged).IsAssignableFrom(srcProp.PropertyType))
            {
                var srcValue = GetSourceValue();
                if (srcValue != null)
                {
                    throw new InvalidOperationException(
                              $"Cannot use {GetType().FullName} for collections.  Use {nameof(OneWayCollectionBinding)}, etc");
                }
            }
        }
Example #29
0
        /// <summary>
        /// 准备批量更新
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entities"></param>
        /// <returns></returns>
        protected int UpdateBatchT <T>(List <T> entities)
        {
            try
            {
                EntityInfo entityInfo = Caches.EntityInfoCache.Get(typeof(T));
                if (entityInfo.PrimaryKey.Count == 0)
                {
                    throw new KeyLossException();
                }
                //分批次
                int count = entities.Count;
                if (count == 0)
                {
                    return(0);
                }
                int batchSize = BatchSize;
                int batch     = (count - 1) / batchSize + 1;
                int effect    = 0;

                //批次循环
                for (int b = 0; b < batch; b++)
                {
                    StringBuilder      updateBatchSql = new StringBuilder();
                    List <DbParameter> parms          = new List <DbParameter>();
                    //单批次内部循环
                    for (int itemIndex = b * batchSize; itemIndex < batchSize * (b + 1) && itemIndex < count; itemIndex++)
                    {
                        StringBuilder updateSql = new StringBuilder();
                        updateSql.AppendFormat(" UPDATE {0} SET ", entityInfo.TableName);
                        StringBuilder updateValues = new StringBuilder();
                        StringBuilder whereClause  = new StringBuilder();
                        foreach (PropertyInfo property in entityInfo.NotKeyColumnProperties)
                        {
                            object            propertyValue    = null;
                            IPropertyAccessor propertyAccessor = Caches.PropertyAccessorCache.Get(property);
                            if ((propertyValue = propertyAccessor.GetValue(entities[itemIndex])) != null)
                            {
                                updateValues.AppendFormat("{0}={1}{2}{3},", entityInfo.Columns[property.Name], DataBase.ParameterPrefix, property.Name, itemIndex.ToString());
                                parms.Add(DataBase.GetDbParameter(property.Name + itemIndex.ToString(), propertyValue));
                            }
                        }
                        updateSql.AppendFormat("{0} WHERE ", updateValues.ToString().TrimEnd(','));
                        foreach (PropertyInfo property in entityInfo.KeyProperties)
                        {
                            whereClause.AppendFormat(" {0}={1}{2}{3} AND", entityInfo.Columns[property.Name], DataBase.ParameterPrefix, property.Name, itemIndex.ToString());
                            parms.Add(DataBase.GetDbParameter(property.Name + itemIndex.ToString(), property.GetValue(entities[itemIndex], null)));
                        }
                        updateSql.Append(whereClause.ToString().TrimEnd("AND".ToArray()));
                        updateBatchSql.Append(updateSql.ToString() + ";");
                    }
                    effect += DataBase.ExecuteSql(updateBatchSql.ToString(), parms.ToArray());
                }
                return(effect);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
		public virtual void SetUp()
		{
			_accessor = PropertyAccessorFactory.GetPropertyAccessor("field");
			_getter = _accessor.GetGetter(typeof(FieldClass), "Id");
			_setter = _accessor.GetSetter(typeof(FieldClass), "Id");
			_instance = new FieldClass();
			_instance.InitId(0);
		}
Example #31
0
        private static bool HasRequiredAttribute(IPropertyAccessor property, out RequiredAttribute validator)
        {
            validator = property.Attributes
                        .OfType <RequiredAttribute>()
                        .FirstOrDefault();

            return(validator != null);
        }
            public Accessor(WeakReference <object> reference, string name, IPropertyAccessor inner)
                : base(inner)
            {
                reference.TryGetTarget(out object target);

                _context            = new ValidationContext(target);
                _context.MemberName = name;
            }
Example #33
0
        /*
         * public static RootAccessor<TClass> RunVisitor<TClass, TProperty>(Expression<Func<TClass, TProperty>> expr, RootAccessor<TClass> root = null)
         *  where TClass : class
         *  where TProperty : class
         * {
         *  if (root == null)
         *  {
         *      root = new RootAccessor<TClass>();
         *  }
         *
         *  var visitor = new PropertyVisitor(root);
         *  visitor.Visit(expr);
         *  var accessor = visitor.latestAccessor as IPropertyAccessor<TClass>;
         *  //dupes at this point
         *  if (!root.Properties.Contains(accessor))
         *  {
         *      root.Properties.Add(accessor);
         *  }
         *
         *  return root;
         * }
         */

        protected override Expression VisitMember(MemberExpression node)
        {
            //check PropertyAccessor for the property does not already exist
            var localAccessor = CreateAccessor(node);

            latestAccessor = localAccessor;
            return(base.VisitMember(node));
        }
Example #34
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TextboxElement"/> class.
        /// </summary>
        /// <param name="accessor">The accessor.</param>
        /// <param name="control">The control.</param>
        public TextboxElement([NotNull] IPropertyAccessor accessor,
                              [NotNull] TextBox control)
            : base(accessor, control)
        {
            Assert.ArgumentNotNull(control, nameof(control));

            control.GotFocus += control_GotFocus;
        }
Example #35
0
 public ConversionPropertyMapper(
     IPropertyAccessor sourceAccessor,
     IPropertyAccessor targetAccessor,
     Type targetType)
     : base(sourceAccessor, targetAccessor)
 {
     this.targetType = targetType;
 }
		public AliasToBeanResultTransformer(System.Type resultClass)
		{
			if (resultClass == null)
				throw new ArgumentNullException("resultClass");
			this.resultClass = resultClass;
			propertyAccessor = new ChainedPropertyAccessor(
				new IPropertyAccessor[]
					{
						// TODO H3:	PropertyAccessorFactory.GetPropertyAccessor(resultClass, null),
						PropertyAccessorFactory.GetPropertyAccessor(null),
						PropertyAccessorFactory.GetPropertyAccessor("field")
					});
		}
        /// <summary>
        /// 
        /// </summary>
        /// <param name="propertyAccessor"></param>
        /// <param name="pocoType"></param>
        public PocoAccessor(IPropertyAccessor propertyAccessor, System.Type pocoType)
        {
            this.pocoType = pocoType;

            BindingFlags flags = BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetProperty;
            IEnumerable<PropertyInfo> properties = pocoType.GetProperties(flags);

            List<IPropertyAction> customAccessors = new List<IPropertyAction>();
            
            foreach (var property in properties)
            {
                try
                {
                    #region getter..
                    IGetter getter = null;
                    try
                    {
                        getter = propertyAccessor.GetGetter(pocoType, property.Name);
                    }
                    catch
                    {
                    }
                    #endregion

                    #region setter..
                    ISetter setter = null;
                    try
                    {
                        setter = propertyAccessor.GetSetter(pocoType, property.Name);
                    }
                    catch
                    {
                    }
                    #endregion

                    if (getter != null || setter != null)
                        customAccessors.Add(new PropertyAction(property, getter, setter));
                }
                catch
                {
                    
                }
            }

            if (customAccessors.Count == 0)
                throw new MissingAccessorsException(string.Format("The resultType object doens't exposes non private members to map, resultType: {0}", pocoType.Name));

            this.propertyActions = new HashSet<IPropertyAction>(customAccessors);
            this.constructor = pocoType.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, System.Type.EmptyTypes, null);
        }
Example #38
0
 public Binding(string propertyName, IPropertyAccessor accessor)
 {
     if (string.IsNullOrEmpty(propertyName))
     {
         throw new ArgumentNullException("propertyName");
     }
     
     if (accessor == null)
     {
         throw new ArgumentNullException("accessor");
     }
     
     this.Mode = BindingMode.TwoWay;
     this.PropertyName = propertyName;
     this.PropertyAccessor = accessor;
 }
        public AliasToObjectResultTransformer(System.Type resultClass)
        {
            if (resultClass == null)
            {
                throw new ArgumentNullException("resultClass");
            }
            this.resultClass = resultClass;

            constructor = resultClass.GetConstructor(flags, null, System.Type.EmptyTypes, null);

            // if resultClass is a ValueType (struct), GetConstructor will return null...
            // in that case, we'll use Activator.CreateInstance instead of the ConstructorInfo to create instances
            if (constructor == null && resultClass.IsClass)
            {
                throw new ArgumentException("The target class of a AliasToObjectResultTransformer need a parameter-less constructor",
                                            "resultClass");
            }

            propertyAccessor =
                new ChainedPropertyAccessor(new[]
                                                {
                                                    PropertyAccessorFactory.GetPropertyAccessor(null),
                                                    PropertyAccessorFactory.GetPropertyAccessor("field")
                                                });

            // Get and store the public and non-public type for the instance properties
            var properties = resultClass.GetProperties(flags);
            propertyTypes = new Dictionary<string, System.Type>(properties.Length);

            foreach (var property in properties)
            {
                propertyTypes.Add(property.Name, property.PropertyType);
            }

            // Get and store the public and non-public type for the instance fields
            var fields = resultClass.GetFields(flags);
            fieldTypes = new Dictionary<string, System.Type>(fields.Length);

            foreach (var field in fields)
            {
                fieldTypes.Add(field.Name, field.FieldType);
            }
        }
        public override EntityKey Create(
            IEntityType entityType, IReadOnlyList<IProperty> properties, IPropertyAccessor propertyAccessor)
        {
            var components = new object[properties.Count];

            for (var i = 0; i < properties.Count; i++)
            {
                var value = propertyAccessor[properties[i]];

                if (value == null
                    || Equals(value, _sentinels[i]))
                {
                    return EntityKey.InvalidEntityKey;
                }

                components[i] = value;
            }

            return new CompositeEntityKey(entityType, components);
        }
Example #41
0
        protected override void SubscribeAndUpdate(object target)
        {
            if (target != null)
            {
                var plugin = ExpressionObserver.PropertyAccessors.FirstOrDefault(x => x.Match(target));

                if (plugin != null)
                {
                    _accessor = plugin.Start(target, PropertyName, SetCurrentValue);

                    if (_accessor != null)
                    {
                        SetCurrentValue(_accessor.Value);
                        return;
                    }
                }
            }

            CurrentValue = PerspexProperty.UnsetValue;
        }
		/// <summary>
		/// Initializes a new instance of the PositionalToBeanResultTransformer class.
		/// </summary>
		/// <param name="resultClass">The return <see cref="Type"/>.</param>
		/// <param name="positionalAliases">Alias for each position of the query.</param>
		public PositionalToBeanResultTransformer(Type resultClass, string[] positionalAliases)
		{
			if (resultClass == null)
			{
				throw new ArgumentNullException("resultClass");
			}
			this.resultClass = resultClass;
			if (positionalAliases == null || positionalAliases.Length == 0)
			{
				throw new ArgumentNullException("positionalAliases");
			}
			this.positionalAliases = positionalAliases;
			propertyAccessor =
				new ChainedPropertyAccessor(new[]
				                            	{
				                            		PropertyAccessorFactory.GetPropertyAccessor("field"),
				                            		PropertyAccessorFactory.GetPropertyAccessor(null)
				                            	});
			AssignSetters();
		}
        protected override void SubscribeAndUpdate(WeakReference reference)
        {
            var instance = reference.Target;

            if (instance != null && instance != AvaloniaProperty.UnsetValue)
            {
                var accessorPlugin = ExpressionObserver.PropertyAccessors.FirstOrDefault(x => x.Match(reference));

                if (accessorPlugin != null)
                {
                    _accessor = ExceptionValidationPlugin.Instance.Start(
                        reference,
                        PropertyName,
                        accessorPlugin.Start(reference, PropertyName, SetCurrentValue),
                        SendValidationStatus);

                    if (_enableValidation)
                    {
                        foreach (var validationPlugin in ExpressionObserver.ValidationCheckers)
                        {
                            if (validationPlugin.Match(reference))
                            {
                                _accessor = validationPlugin.Start(reference, PropertyName, _accessor, SendValidationStatus);
                            }
                        }
                    }

                    if (_accessor != null)
                    {
                        SetCurrentValue(_accessor.Value);
                        return;
                    }
                }
            }

            CurrentValue = UnsetReference;
        }
        private void Init()
        {
            this.InitTypes();

            // Create the assembly and an instance of the
            // Property accessor class.
            var assembly = this.EmitAssembly();
            this.emittedPropertyAccessor = assembly.CreateInstance("Property") as IPropertyAccessor;

            if (this.emittedPropertyAccessor == null)
            {
                throw new Exception("Unable to create Property accessor.");
            }
        }
Example #45
0
 public EmitAccessor(Type targetType, string propertyName)
 {
     TargetType = targetType;
     PropertyName = propertyName;
     TargetProperty = new PropertyAccessor(TargetType, PropertyName);
 }
        /// <summary>
        /// This method generates creates a new assembly containing
        /// the Type that will provide dynamic access.
        /// </summary>
        private void Init()
        {
            this.InitTypes();

            // Create the assembly and an instance of the
            // property accessor class.
            Assembly assembly = EmitAssembly();

            mEmittedPropertyAccessor =
                assembly.CreateInstance("Property") as IPropertyAccessor;

            if (mEmittedPropertyAccessor == null)
            {
                throw new Exception("Unable to create property accessor."); // do not localize
            }
        }
 protected override void Unsubscribe(object target)
 {
     _accessor?.Dispose();
     _accessor = null;
 }
 // Methods
 public CustomAliasToBeanResultTransformer(System.Type resultClass)
 {
     if (resultClass == null)
     {
         throw new ArgumentNullException("resultClass");
     }
     this.resultClass = resultClass;
     this.constructor = resultClass.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, System.Type.EmptyTypes, null);
     if ((this.constructor == null) && resultClass.IsClass)
     {
         throw new ArgumentException("The target class of a AliasToBeanResultTransformer need a parameter-less constructor", "resultClass");
     }
     this.propertyAccessor = new ChainedPropertyAccessor(new IPropertyAccessor[] { PropertyAccessorFactory.GetPropertyAccessor(null), PropertyAccessorFactory.GetPropertyAccessor("field") });
 }
Example #49
0
        public virtual InternalEntityEntry GetPrincipal(IPropertyAccessor dependentEntry, IForeignKey foreignKey)
        {
            var dependentKeyValue = dependentEntry.GetDependentKeyValue(foreignKey);
            if (dependentKeyValue == EntityKey.InvalidEntityKey)
            {
                return null;
            }

            InternalEntityEntry principalEntry;
            _identityMap.TryGetValue(dependentKeyValue, out principalEntry);

            return principalEntry;
        }
Example #50
0
        /// <summary>
        /// 初始化
        /// </summary>
        private void Init()
        {
            this.opCodes = new Hashtable();

            this.opCodes[typeof( sbyte )] = OpCodes.Ldind_I1;
            this.opCodes[typeof( byte )] = OpCodes.Ldind_U1;
            this.opCodes[typeof( char )] = OpCodes.Ldind_U2;
            this.opCodes[typeof( short )] = OpCodes.Ldind_I2;
            this.opCodes[typeof( ushort )] = OpCodes.Ldind_U2;
            this.opCodes[typeof( int )] = OpCodes.Ldind_I4;
            this.opCodes[typeof( uint )] = OpCodes.Ldind_U4;
            this.opCodes[typeof( long )] = OpCodes.Ldind_I8;
            this.opCodes[typeof( ulong )] = OpCodes.Ldind_I8;
            this.opCodes[typeof( bool )] = OpCodes.Ldind_I1;
            this.opCodes[typeof( double )] = OpCodes.Ldind_R8;
            this.opCodes[typeof( float )] = OpCodes.Ldind_R4;

            this.accessor = this.CreateDynamicAssembly().CreateInstance( "Property" ) as IPropertyAccessor;

            if( this.accessor == null )
            {
                throw new Exception( "不能创建属性访问器。" );
            }
        }
		public void SetUp()
		{
			_accessor = PropertyAccessorFactory.GetPropertyAccessor("property");
			_setter = _accessor.GetSetter(typeof(A), "Id");
		}
        public virtual InternalEntityEntry GetPrincipal(IPropertyAccessor dependentEntry, IForeignKey foreignKey)
        {
            var dependentKeyValue = dependentEntry.GetDependentKeyValue(foreignKey);

            if (dependentKeyValue == EntityKey.InvalidEntityKey)
            {
                return null;
            }

            var principalEntityType = foreignKey.PrincipalEntityType;
            var principalProperties = foreignKey.PrincipalKey.Properties;

            // TODO: Perf: Add additional indexes so that this isn't a linear lookup
            var principals = Entries.Where(
                e => e.EntityType == principalEntityType
                     && dependentKeyValue.Equals(
                         e.GetPrincipalKey(foreignKey, principalEntityType, principalProperties))).ToList();

            if (principals.Count > 1)
            {
                // TODO: Better exception message
                // Issue #739
                throw new InvalidOperationException("Multiple matching principals.");
            }

            return principals.FirstOrDefault();
        }
		public DynamicPropertyAccessor(IPropertyAccessor accessor)
		{
			this.accessor = accessor;
		}
		public void SetUp()
		{
			_accessor = PropertyAccessorFactory.GetPropertyAccessor("field");
			_setter = _accessor.GetSetter( typeof(FieldSetterExceptionFixture.A), "Id" );
		}
 public virtual IKeyValue CreateKey(IKey key, IReadOnlyList<IProperty> properties, IPropertyAccessor propertyAccessor)
     => _keyValueFactorySource
         .GetKeyFactory(key)
         .Create(properties, propertyAccessor);
 /// <summary>
 /// Sets the binding between target and source.
 /// </summary>
 public static IBindingExpression AddBinding(this IBindingScope scope, object target, string propertyName, IPropertyAccessor propertyAccessor, object source, Binding binding)
 {
     var expression = new WeakBindingExpression(target, propertyName, propertyAccessor, source, binding);
     scope.Add(expression);
     return expression;
 }
 public virtual EntityKey CreateKey(IEntityType entityType, IReadOnlyList<IProperty> properties, IPropertyAccessor propertyAccessor)
     => _entityKeyFactorySource
         .GetKeyFactory(properties)
         .Create(entityType, properties, propertyAccessor);
Example #58
0
		public ChainedPropertyAccessor(IPropertyAccessor[] chain)
		{
			this.chain = chain;
		}
 public InternalEntityEntry GetPrincipal(IPropertyAccessor dependentEntry, IForeignKey foreignKey)
 {
     throw new NotImplementedException();
 }
 public override EntityKey Create(
     IEntityType entityType, IReadOnlyList<IProperty> properties, IPropertyAccessor propertyAccessor) 
     => Create(entityType, properties, p => propertyAccessor[p]);