private void CloneCollection(IMemberAccessor accessor, object originalValue, object target) { // support readonly collections object targetValue = accessor.HasSetter ? CreateTargetValue(accessor, originalValue, target) : accessor.GetValue(target); if (targetValue == null) return; var sourceList = originalValue as IEnumerable; if (sourceList == null) return; // must support IList var targetList = targetValue as IList; if (targetList == null) return; foreach (var sourceItem in sourceList) { var cloneItem = CloneInstance(sourceItem); targetList.Add(cloneItem); } if (!accessor.HasSetter) return; accessor.SetValue(target, targetValue); }
private static void ShouldBehaveSimilar(IMemberAccessor<TestA, string> ma, TestA a1) { Assert.That(ma.GetValue(a1), Is.EqualTo(a1.PropString)); ma.SetValue(a1, "updated " + a1.PropString); Assert.That(ma.GetValue(a1), Is.EqualTo(a1.PropString)); a1.PropString = "new " + a1.PropString; Assert.That(ma.GetValue(a1), Is.EqualTo(a1.PropString)); }
static string extractSystem(IMemberAccessor accessor) { if (accessor.MemberInfo.DeclaringType.Namespace.Contains("Standard")) return "Standard"; if (accessor.MemberInfo.DeclaringType.Namespace.Contains("JDE")) return "JDE"; if (accessor.MemberInfo.DeclaringType.Namespace.Contains("Vendors")) return accessor.MemberType.Namespace.Split('.').Last(); if (accessor.MemberInfo.DeclaringType.Namespace.Contains("DropShip")) return accessor.MemberType.Namespace.Split('.').Last(); return "unknown"; }
private PropertyPath(Type rootType,IMemberAccessor[] props) { _properties = props; _rootType = rootType; if (_properties[0].IsStatic) _rootIsStatic = true; }
public void ShouldWorkForKnownTypeAndKnownMember() { var a1 = CreateTestObject(); IMemberAccessor <TestA, string> ma = TypeAccessor <TestA> .GetMemberAccessor(x => x.PropString); ShouldBehaveSimilar(ma, a1); IObjectMemberAccessor <double> oma = a1.GetObjectMemberAccessor(x => x.Field1); ShouldBehaveSimilar(oma, a1); }
public static bool CheckAttributeOrTrue <T>(IMemberAccessor memberAccessor, Predicate <T> predicate) where T : Attribute { var attribute = memberAccessor.GetCustomAttribute <T>(); if (attribute == null) { return(true); } return(predicate(attribute)); }
public static IObjectMemberAccessor GetObjectMemberAccessor(this object obj, string memberName, bool readOnly = false, IObjectCache <string> memberCache = null) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } IMemberAccessor ma = GetMemberAccessor(obj.GetType(), memberName, readOnly, memberCache); var oaType = typeof(ObjectMemberAccessor <,>).MakeGenericType(ma.ObjectType, ma.MemberType); var result = Activator.CreateInstance(oaType, obj, ma); return((IObjectMemberAccessor)result); }
public FixedLengthComplexPropertyMapping( IFixedLengthTypeMapper <TEntity> mapper, IMemberAccessor member, int physicalIndex, int logicalIndex) { this.mapper = mapper; Member = member; columnName = member.Name; PhysicalIndex = physicalIndex; LogicalIndex = logicalIndex; }
public SeparatedValueComplexPropertyMapping( ISeparatedValueTypeMapper <TEntity> mapper, IMemberAccessor member, int physicalIndex, int logicalIndex) { this.mapper = mapper; Member = member; columnName = member.Name; PhysicalIndex = physicalIndex; LogicalIndex = logicalIndex; }
public ObjectAccessor(object data) { _data = data; if (data == null || !ObjectDescriptorFactory.Current.TryGetDescriptor(data.GetType(), out _descriptor)) { _descriptor = ObjectDescriptor.Empty; _memberAccessor = null; } else { _memberAccessor = _descriptor.MemberAccessor; } }
public PropertyMap FindOrCreatePropertyMapFor(IMemberAccessor destinationProperty) { var propertyMap = GetExistingPropertyMapFor(destinationProperty); if (propertyMap == null) { propertyMap = new PropertyMap(destinationProperty); AddPropertyMap(propertyMap); } return(propertyMap); }
public void Register(Type type, string name, IMemberAccessor getter) { if (!_map.TryGetValue(type, out var typeMap)) { typeMap = new Dictionary <string, IMemberAccessor>(IgnoreCasing ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); _map[type] = typeMap; } typeMap[name] = getter; }
private void CloneGenericDictionary(IMemberAccessor accessor, object originalValue, object target) { // support readonly dictionary object targetValue = accessor.HasSetter ? CreateTargetValue(accessor, originalValue, target) : accessor.GetValue(target); if (targetValue == null) { return; } // must support IEnumerable var sourceList = originalValue as IEnumerable; if (sourceList == null) { return; } // dynamic wrapper to call generic Add method dynamic targetDictionary = new DynamicProxy(targetValue); var e = sourceList.GetEnumerator(); while (e.MoveNext()) { // dynamic wrapper to get the key and value dynamic proxy = new DynamicProxy(e.Current); var keyProxy = proxy.Key as IDynamicProxy; var valueProxy = proxy.Value as IDynamicProxy; if (keyProxy == null) { continue; } object key = keyProxy.Wrapped; object value = valueProxy != null ? valueProxy.Wrapped : null; object cloneItem = CloneInstance(value); targetDictionary.Add(key, cloneItem); } if (!accessor.HasSetter) { return; } accessor.SetValue(target, targetValue); }
private void LoadFromKvp(IEnumerable <KeyValuePair <string, object> > expected) { foreach (var kvp in expected) { IMemberAccessor accessor = MemberAccessors.PropertyOrField(kvp.Key); object specified = kvp.Value; _items.Add(kvp.Key, new ExpectedAccessorData( kvp.Key, specified, Matcher(specified), accessor )); } }
public static IMemberAccessor GetAccessor(Type objectType, string memberName, out System.Type effectivelyAlteredValueType) { if (objectType == null) { throw new System.ArgumentNullException("objectType"); } const MemberTypes MASK_MEMBERTYPES = MemberTypes.Field | MemberTypes.Property; const BindingFlags MASK_BINDINGS = BindingFlags.Public | BindingFlags.Instance; if (memberName.Contains('.')) { var arr = memberName.Split('.'); _chainBuilder.Clear(); for (int i = 0; i < arr.Length; i++) { var matches = objectType.GetMember(arr[i], MASK_MEMBERTYPES, MASK_BINDINGS); if (matches == null || matches.Length == 0) { throw new MemberAccessorException(string.Format("Member \"{0}\" does not exist for type {1}.", memberName, objectType)); } objectType = DynamicUtil.GetReturnType(matches[0]); _chainBuilder.Enqueue(GetAccessor(matches[0], true)); } //the currentObjectType value will be the type effectively being manipulated effectivelyAlteredValueType = objectType; IMemberAccessor accessor = _chainBuilder.Dequeue(); while (_chainBuilder.Count > 0) { accessor = new ChainingAccessor(_chainBuilder.Dequeue(), accessor); } return(accessor); } else { var matches = objectType.GetMember(memberName, MASK_MEMBERTYPES, MASK_BINDINGS); if (matches == null || matches.Length == 0) { throw new MemberAccessorException(string.Format("Member \"{0}\" does not exist for type {1}.", memberName, objectType)); } effectivelyAlteredValueType = DynamicUtil.GetReturnType(matches[0]); return(GetAccessor(matches[0])); } }
/// <summary> /// /// </summary> /// <param name="describedType">Returns type described by this instance of <see cref="ObjectDescriptor"/></param> /// <param name="memberAccessor"><see cref="IMemberAccessor"/> associated with the <see cref="ObjectDescriptor"/></param> /// <param name="getProperties">Factory enabling receiving properties of specific instance</param> /// <param name="iterator"></param> /// <param name="dependencies"></param> public ObjectDescriptor( Type describedType, IMemberAccessor memberAccessor, Func <ObjectDescriptor, object, IEnumerable> getProperties, Func <ObjectDescriptor, IIterator> iterator, params object[] dependencies ) { DescribedType = describedType; GetProperties = getProperties; MemberAccessor = memberAccessor; Dependencies = dependencies; Iterator = iterator(this); }
public IMemberAccessor CreateMemberAccessor(Type targetType, string name) { string key = targetType.FullName + name; if (_cachedIMemberAccessor.Contains(key)) { return((IMemberAccessor)_cachedIMemberAccessor[key]); } else { IMemberAccessor memberAccessor = null; lock (_syncObject) { if (!_cachedIMemberAccessor.Contains(key)) { // Property PropertyInfo propertyInfo = targetType.GetProperty(name); if (propertyInfo != null) { memberAccessor = _createPropertyAccessor(targetType, name); _cachedIMemberAccessor[key] = memberAccessor; } else { // Field FieldInfo fieldInfo = targetType.GetField(name, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); if (fieldInfo != null) { memberAccessor = _createFieldAccessor(targetType, name); _cachedIMemberAccessor[key] = memberAccessor; } else { throw new ProbeException( string.Format("No property or field named \"{0}\" exists for type " + "{1}.", name, targetType)); } } } else { memberAccessor = (IMemberAccessor)_cachedIMemberAccessor[key]; } } return(memberAccessor); } }
public PropertyMap FindOrCreatePropertyMapFor(IMemberAccessor destinationProperty) { var propertyMap = GetExistingPropertyMapFor(destinationProperty); if (propertyMap != null) { return(propertyMap); } propertyMap = new PropertyMap(destinationProperty, this); _propertyMaps.Add(propertyMap); return(propertyMap); }
public sealed override void Update(object targ, float dt, float t) { if (t > _dur) { t = _dur; } var value = GetValueAt(dt, t); if (_accessor == null) { System.Type memberType; _accessor = MemberCurve.GetAccessor(targ, _memberName, out memberType); } _accessor.Set(targ, value); }
private static bool IsLoaded(AuditEntryState state, NavigationProperty navigationProperty, IMemberAccessor accessor) { var relationshipManager = state.ObjectStateEntry.RelationshipManager; var getEntityReference = _relatedAccessor.Value.MakeGenericMethod(accessor.MemberType); var parameters = new[] { navigationProperty.RelationshipType.FullName, navigationProperty.ToEndMember.Name }; var entityReference = getEntityReference.Invoke(relationshipManager, parameters) as EntityReference; return(entityReference != null && entityReference.IsLoaded); }
private void InitAccessor() { _accessor = MemberAccessorPool.GetDynamicAccessor(_target, _memberName, out _memberType); if (_accessor == null) { _status = MemberStatus.Fault; } else if (ConvertUtil.IsSupportedType(_memberType)) { _status = MemberStatus.Primitive; } else { _status = MemberStatus.Complex; } }
public IMappingExpression ForMember(string name, Action<IMemberConfigurationExpression> memberOptions) { IMemberAccessor destMember = null; var propertyInfo = _typeMap.DestinationType.GetProperty(name); if (propertyInfo != null) { destMember = new PropertyAccessor(propertyInfo); } if (destMember == null) { var fieldInfo = _typeMap.DestinationType.GetField(name); destMember = new FieldAccessor(fieldInfo); } ForDestinationMember(destMember, memberOptions); return new MappingExpression(_typeMap, _typeConverterCtor); }
private static void SetValueWithCoercion(object target, IMemberAccessor accessor, object value) { if (value == null) { return; } var pType = accessor.MemberType; var vType = value.GetType().GetUnderlyingType(); var v = ReflectionHelper.CoerceValue(pType, vType, value); if (v != null) { accessor.SetValue(target, v); } }
public TMemberMapping GetOrAddMember <TMemberMapping>(IMemberAccessor member, Func <int, int, TMemberMapping> factory) where TMemberMapping : IMemberMapping { if (lookup.TryGetValue(member.Name, out var mapping)) { return((TMemberMapping)mapping); } else { int fileIndex = lookup.Count; int workIndex = lookup.Count - ignoredCount; var newMapping = factory(fileIndex, workIndex); lookup.Add(member.Name, newMapping); return(newMapping); } }
/// <summary> /// /// </summary> /// <param name="describedType">Returns type described by this instance of <see cref="ObjectDescriptor"/></param> /// <param name="memberAccessor"><see cref="IMemberAccessor"/> associated with the <see cref="ObjectDescriptor"/></param> /// <param name="getProperties">Factory enabling receiving properties of specific instance</param> /// <param name="shouldEnumerate">Specifies whether the type should be treated as <see cref="System.Collections.IEnumerable"/></param> /// <param name="dependencies"></param> public ObjectDescriptor( Type describedType, IMemberAccessor memberAccessor, Func <ObjectDescriptor, object, IEnumerable> getProperties, bool shouldEnumerate = false, params object[] dependencies ) { DescribedType = describedType; GetProperties = getProperties; MemberAccessor = memberAccessor; ShouldEnumerate = shouldEnumerate; Dependencies = dependencies; _isNotEmpty = true; }
/// <summary> /// This method generates creates a new assembly containing /// the Type that will provide dynamic access. /// </summary> void EnsureInit() { if (_emittedMemberAccessor == null) { // Create the assembly and an instance of the // member accessor class. Assembly assembly = EmitAssembly(); _emittedMemberAccessor = assembly.CreateInstance(emmitedTypeName) as IMemberAccessor; if (_emittedMemberAccessor == null) { throw new Exception("Unable to create member accessor."); } } }
/// <summary> /// Searches for the property or field, using the specified binding constraints. /// </summary> /// <param name="type">The <see cref="Type"/> to search for the property or field in.</param> /// <param name="name">The name of the property or field to find.</param> /// <param name="flags">A bitmask comprised of one or more <see cref="BindingFlags"/> that specify how the search is conducted.</param> /// <returns> /// An <see cref="IMemberAccessor"/> instance for the property or field if found; otherwise <c>null</c>. /// </returns> public static IMemberAccessor Find(Type type, string name, BindingFlags flags) { if (type == null) { throw new ArgumentNullException("type"); } if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } TypeAccessor typeAccessor = TypeAccessor.GetAccessor(type); IMemberAccessor memberAccessor = typeAccessor.Find(name, flags); return(memberAccessor); }
public void ShouldWorkForUnknownTypeAndUnknownMember() { var a1 = CreateTestObject(); IMemberAccessor ma = TypeAccessor.GetMemberAccessor(typeof(TestA), "PropInt"); Assert.That(ma.GetValue(a1), Is.EqualTo(a1.PropInt)); ma.SetValue(a1, a1.PropInt + 10); Assert.That(ma.GetValue(a1), Is.EqualTo(a1.PropInt)); IObjectMemberAccessor oma = a1.GetObjectMemberAccessor("Field1"); Assert.That(oma.GetValue(), Is.EqualTo(a1.Field1)); oma.SetValue(12.56); Assert.That(oma.GetValue(), Is.EqualTo(a1.Field1)); a1.Field1 -= 345; Assert.That(oma.GetValue(), Is.EqualTo(a1.Field1)); }
/// <summary> /// Attempts to get the value of the Property called <paramref name="name" /> from the underlying Entity. /// <remarks> /// Only properties that exist on <see cref="EntityType" /> can be retrieved. /// Both modified and unmodified properties can be retrieved. /// </remarks> /// </summary> /// <param name="name">The name of the Property</param> /// <param name="value">The value of the Property</param> /// <param name="target">The target entity to get the value from</param> /// <returns>True if the Property was found</returns> public bool TryGetPropertyValue(string name, out object value, TEntityType target = null) { if (name == null) { throw new ArgumentNullException("name"); } if (_propertiesThatExist.ContainsKey(name)) { IMemberAccessor cacheHit = _propertiesThatExist[name]; value = cacheHit.GetValue(target ?? _entity); return(true); } value = null; return(false); }
private void CloneArray(IMemberAccessor accessor, object originalValue, object target) { var valueType = originalValue.GetType(); var sourceList = originalValue as IList; if (sourceList == null) return; var targetValue = Activator.CreateInstance(valueType, sourceList.Count); var targetList = targetValue as IList; if (targetList == null) return; for (int i = 0; i < sourceList.Count; i++) targetList[i] = CloneInstance(sourceList[i]); accessor.SetValue(target, targetList); }
public override ValueTask <FluidValue> ResolveAsync(Scope value, TemplateContext context) { async ValueTask <FluidValue> Awaited( IAsyncMemberAccessor asyncAccessor, TemplateContext ctx, string identifier) { var o = await asyncAccessor.GetAsync(ctx.Model, identifier, ctx); return(FluidValue.Create(o, context.Options)); } var result = value.GetValue(Identifier); // If there are no named property for this identifier, check in the Model if (result.IsNil() && context.Model != null) { // Check for a custom registration var modelType = context.Model.GetType(); if (modelType != _type) { _accessor = context.Options.MemberAccessStrategy.GetAccessor(modelType, Identifier); _accessor ??= MemberAccessStrategyExtensions.GetNamedAccessor(modelType, Identifier, MemberNameStrategies.Default); if (_accessor != null) { _type = modelType; } } if (_accessor != null) { if (_accessor is IAsyncMemberAccessor asyncAccessor) { return(Awaited(asyncAccessor, context, Identifier)); } return(new ValueTask <FluidValue>(FluidValue.Create(_accessor.Get(context.Model, Identifier, context), context.Options))); } return(new ValueTask <FluidValue>(NilValue.Instance)); } return(new ValueTask <FluidValue>(result)); }
public IMemberAccessor GetAccessor(Type type, string name) { IMemberAccessor accessor = null; var currentType = type; while (currentType != typeof(object) && currentType != null) { // Look for specific property map if (_map.TryGetValue(currentType, out var typeMap)) { if (typeMap.TryGetValue(name, out accessor) || typeMap.TryGetValue("*", out accessor)) { return(accessor); } } accessor = accessor ?? _parent?.GetAccessor(currentType, name); if (accessor != null) { return(accessor); } currentType = currentType.GetTypeInfo().BaseType; } // Search for accessors defined on interfaces foreach (var interfaceType in type.GetTypeInfo().GetInterfaces()) { if (_map.TryGetValue(interfaceType, out var typeMap)) { if (typeMap.TryGetValue(name, out accessor) || typeMap.TryGetValue("*", out accessor)) { if (accessor != null) { return(accessor); } } } } return(null); }
private static object GetMemberValueFromObject(MemberInfo mi, object graph) { try { object data = null; IMemberAccessor accessor = graph as IMemberAccessor; if (accessor != null) { data = accessor.GetValue(graph, mi.Name); } else { switch (mi.MemberType) { case MemberTypes.Property: PropertyInfo pi = (PropertyInfo)mi; if (pi.CanRead) { data = pi.GetValue(graph, null); } break; case MemberTypes.Field: FieldInfo fi = (FieldInfo)mi; data = fi.GetValue(graph); break; default: ThrowInvalidMemberInfoTypeException(mi); break; } } return(data); } catch (System.Exception ex) { System.Exception realEx = ExceptionHelper.GetRealException(ex); throw new ApplicationException(string.Format("读取属性{0}值的时候出错,{1}", mi.Name, realEx.Message)); } }
private Array ReadArray(Type type, IMemberAccessor memberAccessor) { int len = this.ReadInt32(); if (len == -1) { return(null); } var elementType = type.GetElementType(); var array = Array.CreateInstance(elementType, len); for (int i = 0; i < len; i++) { var instance = Activator.CreateInstance(elementType); this.StartDeserialize(instance, memberAccessor); array.SetValue(instance, i); } return(array); }
public static PropertyPath Compile(Type targetType,string[] pathParts) { var accessors = new IMemberAccessor[pathParts.Length]; Type currentType = targetType; for (int i = 0; i < pathParts.Length; i++) { string part = pathParts[i]; IMemberAccessor accessor = currentType.FindAccessor(part); if (accessor == null) return null; accessors[i] = accessor; currentType = accessor.MemberType; } return new PropertyPath(targetType, accessors); }
/// <summary> /// Sets the field value with the specified name. /// </summary> /// <param name="target">The object whose field value will be set.</param> /// <param name="name">The name of the field to set.</param> /// <param name="value">The new value to be set.</param> public static void SetField(object target, string name, object value) { if (target == null) { throw new ArgumentNullException("target"); } if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } Type type = target.GetType(); IMemberAccessor accessor = FindField(type, name); if (accessor == null) { throw new InvalidOperationException(string.Format("Could not find field '{0}' in type '{1}'.", name, type.Name)); } accessor.SetValue(target, value); }
public PropertyMap FindOrCreatePropertyMapFor(IMemberAccessor destinationProperty) { var propertyMap = GetExistingPropertyMapFor(destinationProperty); if (propertyMap == null) { propertyMap = new PropertyMap(destinationProperty); AddPropertyMap(propertyMap); } return propertyMap; }
public void AddPropertyMap(IMemberAccessor destProperty, IEnumerable<IValueResolver> resolvers) { var propertyMap = new PropertyMap(destProperty); resolvers.Each(propertyMap.ChainResolver); AddPropertyMap(propertyMap); }
private static bool IsLoaded(AuditEntryState state, NavigationProperty navigationProperty, IMemberAccessor accessor) { var relationshipManager = state.ObjectStateEntry.RelationshipManager; var getEntityReference = _relatedAccessor.Value.MakeGenericMethod(accessor.MemberType); var parameters = new[] { navigationProperty.RelationshipType.FullName, navigationProperty.ToEndMember.Name }; var entityReference = getEntityReference.Invoke(relationshipManager, parameters) as EntityReference; return (entityReference != null && entityReference.IsLoaded); }
private static object GetDisplayValue(AuditEntryState state, NavigationProperty navigationProperty, IMemberAccessor displayMember, DbDataRecord values) { if (values == null) return null; var association = navigationProperty.RelationshipType as AssociationType; if (association == null) return null; // only support first constraint var referentialConstraint = association.ReferentialConstraints.FirstOrDefault(); if (referentialConstraint == null) return null; var toProperties = referentialConstraint .ToProperties .Select(p => p.Name) .ToList(); var fromProperties = referentialConstraint .FromProperties .Select(p => p.Name) .ToList(); // make sure key columns match if (fromProperties.Count != toProperties.Count) return null; var edmType = referentialConstraint .FromProperties .Select(p => p.DeclaringType) .FirstOrDefault(); if (edmType == null) return null; var entitySet = state.ObjectContext.GetEntitySet(edmType.FullName); var sql = new StringBuilder(); sql.Append("SELECT VALUE t.") .Append(displayMember.Name) .Append(" FROM ") .Append(entitySet.Name) .Append(" as t") .Append(" WHERE "); var parameters = new List<ObjectParameter>(); for (int index = 0; index < fromProperties.Count; index++) { if (index > 0) sql.Append(" AND "); string fromProperty = fromProperties[index]; string toProperty = toProperties[index]; var value = values.GetValue(toProperty); var name = "@" + fromProperty; sql.Append(" t.").Append(fromProperty); if (value != null) { sql.Append(" == ").Append(name); parameters.Add(new ObjectParameter(fromProperty, value)); } else { sql.Append(" is null"); } } var q = state.ObjectContext.CreateQuery<object>( sql.ToString(), parameters.ToArray()); return q.FirstOrDefault(); }
private static MemberCurve Create(System.Type memberType, IMemberAccessor accessor, Ease ease, float dur, object start, object end, object option) { if (_memberTypeToCurveType == null) BuildDictionary(); if (_memberTypeToCurveType.ContainsKey(memberType)) { try { var curve = System.Activator.CreateInstance(_memberTypeToCurveType[memberType], true) as MemberCurve; curve._dur = dur; curve.Ease = ease; curve._accessor = accessor; if (curve is NumericMemberCurve && ConvertUtil.IsNumericType(memberType)) (curve as NumericMemberCurve).NumericType = System.Type.GetTypeCode(memberType); curve.ReflectiveInit(start, end, option); return curve; } catch (System.Exception ex) { throw new System.InvalidOperationException("Failed to create a MemberCurve for the desired MemberInfo.", ex); } } else { throw new System.ArgumentException("MemberInfo is for a member type that is not supported.", "info"); } }
public void AddPropertyMap(IMemberAccessor destProperty, IEnumerable<IMemberGetter> resolvers) { var propertyMap = new PropertyMap(destProperty, this); propertyMap.ChainMembers(resolvers); _propertyMaps.Add(propertyMap); }
public ReflectionAccessor(PropertyInfo propertyInfo) { Contract.Requires<ArgumentNullException>(propertyInfo != null); this.accessor = new PropertyAccessor(propertyInfo); }
private void CloneGenericDictionary(IMemberAccessor accessor, object originalValue, object target) { // support readonly dictionary object targetValue = accessor.HasSetter ? CreateTargetValue(accessor, originalValue, target) : accessor.GetValue(target); if (targetValue == null) return; // must support IEnumerable var sourceList = originalValue as IEnumerable; if (sourceList == null) return; // dynamic wrapper to call generic Add method dynamic targetDictionary = new DynamicProxy(targetValue); var e = sourceList.GetEnumerator(); while (e.MoveNext()) { // dynamic wrapper to get the key and value dynamic proxy = new DynamicProxy(e.Current); var keyProxy = proxy.Key as IDynamicProxy; var valueProxy = proxy.Value as IDynamicProxy; if (keyProxy == null) continue; object key = keyProxy.Wrapped; object value = valueProxy != null ? valueProxy.Wrapped : null; object cloneItem = CloneInstance(value); targetDictionary.Add(key, cloneItem); } if (!accessor.HasSetter) return; accessor.SetValue(target, targetValue); }
private void CloneGenericCollection(IMemberAccessor accessor, object originalValue, object target) { // support readonly collections object targetValue = accessor.HasSetter ? CreateTargetValue(accessor, originalValue, target) : accessor.GetValue(target); if (targetValue == null) return; var sourceList = originalValue as IEnumerable; if (sourceList == null) return; // dynamic wrapper to call generic Add method dynamic targetList = new DynamicProxy(targetValue); foreach (var sourceItem in sourceList) { var cloneItem = CloneInstance(sourceItem); targetList.Add(cloneItem); } if (!accessor.HasSetter) return; accessor.SetValue(target, targetValue); }
public PropertyMap GetExistingPropertyMapFor(IMemberAccessor destinationProperty) { var propertyMap = _propertyMaps.FirstOrDefault(pm => pm.DestinationProperty.Name.Equals(destinationProperty.Name)); if (propertyMap != null) return propertyMap; propertyMap = _inheritedMaps.FirstOrDefault(pm => pm.DestinationProperty.Name.Equals(destinationProperty.Name)); if (propertyMap == null) return null; var propertyInfo = propertyMap.DestinationProperty.MemberInfo as PropertyInfo; if (propertyInfo == null) return propertyMap; var baseAccessor = propertyInfo.GetAccessors()[0]; if (baseAccessor.IsAbstract || baseAccessor.IsVirtual) return propertyMap; var accessor = ((PropertyInfo) destinationProperty.MemberInfo).GetAccessors()[0]; if (baseAccessor.DeclaringType == accessor.DeclaringType) return propertyMap; return null; }
public PropertyMap FindOrCreatePropertyMapFor(IMemberAccessor destinationProperty) { var propertyMap = _propertyMaps.FirstOrDefault(pm => pm.DestinationProperty.Name.Equals(destinationProperty.Name)); if (propertyMap == null) { propertyMap = new PropertyMap(destinationProperty); AddPropertyMap(propertyMap); } return propertyMap; }
public PropertyMap GetExistingPropertyMapFor(IMemberAccessor destinationProperty) { return _propertyMaps.FirstOrDefault(pm => pm.DestinationProperty.Name.Equals(destinationProperty.Name)) ?? _inheritedMaps.FirstOrDefault(pm => pm.DestinationProperty.Name.Equals(destinationProperty.Name)); }
private object CreateTargetValue(IMemberAccessor accessor, object originalValue, object target) { var valueType = originalValue.GetType(); object targetValue; // check if this object has already been cloned // using RuntimeHelpers.GetHashCode to get object identity int hashCode = RuntimeHelpers.GetHashCode(originalValue); if (_objectReferences.TryGetValue(hashCode, out targetValue)) { accessor.SetValue(target, targetValue); return null; } targetValue = LateBinder.CreateInstance(valueType); // keep track of cloned instances _objectReferences.Add(hashCode, targetValue); return targetValue; }
// =================================================================================== // INTERNAL METHODS ------------------------------------------------------------------ /// <summary> /// Initializes the plugin after its instantiation. /// Called by Tweener after a property and plugin have been validated, and the plugin has to be set and added. /// Virtual because some classes (like PlugVector3Path) override it to avoid isRelative being TRUE. /// </summary> /// <param name="p_tweenObj"> /// The <see cref="Tweener"/> to refer to. /// </param> /// <param name="p_propertyName"> /// The name of the property to control. /// </param> /// <param name="p_easeType"> /// The <see cref="EaseType"/> to use. /// </param> /// <param name="p_targetType"> /// Directly passed from TweenParms to speed up MemberAccessor creation. /// </param> /// <param name="p_propertyInfo"> /// Directly passed from TweenParms to speed up MemberAccessor creation. /// </param> /// <param name="p_fieldInfo"> /// Directly passed from TweenParms to speed up MemberAccessor creation. /// </param> internal virtual void Init(Tweener p_tweenObj, string p_propertyName, EaseType p_easeType, Type p_targetType, PropertyInfo p_propertyInfo, FieldInfo p_fieldInfo) { _initialized = true; tweenObj = p_tweenObj; _propName = p_propertyName; targetType = p_targetType; if (easeType != EaseType.AnimationCurve && easeInfo == null || tweenObj.speedBased || easeType == EaseType.AnimationCurve && easeCurve == null) { SetEase(p_easeType); } _duration = tweenObj.duration; if (targetType == typeof(Transform)) { // Use specific transform accessors for faster performance _transformTarget = p_tweenObj.target as Transform; _useSpeedTransformAccessors = true; switch (_propName) { case "position": _setTransformVector3 = value => _transformTarget.position = value; _getTransformVector3 = () => _transformTarget.position; break; case "localPosition": _setTransformVector3 = value => _transformTarget.localPosition = value; _getTransformVector3 = () => _transformTarget.localPosition; break; case "localScale": _setTransformVector3 = value => _transformTarget.localScale = value; _getTransformVector3 = () => _transformTarget.localScale; break; case "rotation": _setTransformQuaternion = value => _transformTarget.rotation = value; _getTransformQuaternion = () => _transformTarget.rotation; break; case "localRotation": _setTransformQuaternion = value => _transformTarget.localRotation = value; _getTransformQuaternion = () => _transformTarget.localRotation; break; default: _transformTarget = null; // No valid speed property found _useSpeedTransformAccessors = false; break; } } if (!_useSpeedTransformAccessors) { #if MICRO propInfo = p_propertyInfo; fieldInfo = p_fieldInfo; #else if (HOTween.isIOS) { propInfo = p_propertyInfo; fieldInfo = p_fieldInfo; } else { if (!ignoreAccessor) { valAccessor = MemberAccessorCacher.Make(p_targetType, p_propertyName, p_propertyInfo, p_fieldInfo); } } #endif } }
protected internal override void Update(object targ, float dt, float t) { if (t < _delay) return; t = (_dur > 0) ? _ease(t - _delay, 0f, 1f, _dur) : 1f; var value = GetValue(t); if (_accessor == null) _accessor = MemberAccessorPool.GetAccessor(targ.GetType(), _memberName); _accessor.Set(targ, value); }
internal ChainingAccessor(IMemberAccessor impl, IMemberAccessor chain) { _pimp = impl; _chain = chain; }
private static object GetDisplayValue(AuditEntryState state, NavigationProperty navigationProperty, IMemberAccessor displayMember, DbDataRecord values) { if (values == null) return null; var association = navigationProperty.RelationshipType as AssociationType; if (association == null) return null; // only support first constraint var referentialConstraint = association.ReferentialConstraints.FirstOrDefault(); if (referentialConstraint == null) return null; var toProperties = referentialConstraint .ToProperties .Select(p => p.Name) .ToList(); var fromProperties = referentialConstraint .FromProperties .Select(p => p.Name) .ToList(); // make sure key columns match if (fromProperties.Count != toProperties.Count) return null; var edmType = referentialConstraint .FromProperties .Select(p => p.DeclaringType) .FirstOrDefault(); if (edmType == null) return null; var eSql = string.Format("SELECT VALUE t FROM {0} AS t", edmType.Name); var q = state.ObjectContext.CreateQuery<object>(eSql); for (int index = 0; index < fromProperties.Count; index++) { string fromProperty = fromProperties[index]; string toProperty = toProperties[index]; var value = values.GetValue(toProperty); var predicate = string.Format("it.{0} == @{0}", fromProperty); var parameter = new ObjectParameter(fromProperty, value); q = q.Where(predicate, parameter); } q = q.SelectValue<object>("it." + displayMember.Name); return q.FirstOrDefault(); }
private void CloneDictionary(IMemberAccessor accessor, object originalValue, object target) { // support readonly dictionary object targetValue = accessor.HasSetter ? CreateTargetValue(accessor, originalValue, target) : accessor.GetValue(target); if (targetValue == null) return; // must support IDictionary var sourceList = originalValue as IDictionary; if (sourceList == null) return; var targetList = targetValue as IDictionary; if (targetList == null) return; var e = sourceList.GetEnumerator(); while (e.MoveNext()) { var cloneItem = CloneInstance(e.Value); targetList.Add(e.Key, cloneItem); } if (!accessor.HasSetter) return; accessor.SetValue(target, targetValue); }
public ReflectionAccessor(FieldInfo memberInfo) { Contract.Requires<ArgumentNullException>(memberInfo != null); this.accessor = new FieldAccessor(memberInfo); }
private void CloneObject(IMemberAccessor accessor, object originalValue, object target) { if (!accessor.HasSetter) return; object value = CloneInstance(originalValue); accessor.SetValue(target, value); }
protected internal override sealed void Update(object targ, float dt, float t) { if (t < _delay) return; var value = GetValueAt(dt, t - _delay); if (_accessor == null) { System.Type memberType; _accessor = MemberCurve.GetAccessor(targ, _memberName, out memberType); } _accessor.Set(targ, value); }
public PropertyMap FindOrCreatePropertyMapFor(IMemberAccessor destinationProperty) { var propertyMap = GetExistingPropertyMapFor(destinationProperty); if (propertyMap != null) return propertyMap; propertyMap = new PropertyMap(destinationProperty, this); _propertyMaps.Add(propertyMap); return propertyMap; }