public void Attach(object o, string propertyName) { Detach(); PropertyInfo property = GetProperty(o, propertyName); if (property != null) { MethodInfo setMethod = property.GetSetMethod(true); if (setMethod != null) { setter = Delegate.CreateDelegate(typeof(PropertySetter), o, setMethod) as PropertySetter; } MethodInfo getMethod = property.GetGetMethod(true); if (getMethod != null) { getter = Delegate.CreateDelegate(typeof(PropertyGetter), o, getMethod) as PropertyGetter; } if (setter == null || getMethod == null) { Detach(); } else { attached = true; } } }
public void PropertyGetter2WorksWithBoxing() { var bar = new Bar { Baz = new Baz(123) }; var property = typeof(Bar).GetProperty(nameof(Bar.Baz)); var getter = new PropertyGetter <Bar, IBaz>(property); getter.Func.Target.Should().BeSameAs(getter); getter.Func.Method.Name.Should().Be(nameof(getter.GetValueReflection)); getter.Func.Method.DeclaringType.Should().Be(typeof(PropertyGetter <Bar, IBaz>)); var reflectionTimer = Stopwatch.StartNew(); IBaz reflectionValue = getter.GetValue(bar); reflectionTimer.Stop(); getter.SetOptimizedFunc(); getter.Func.Target.Should().NotBeSameAs(getter); getter.Func.Method.Name.Should().Be(PropertyGetter.GetValueOptimized); getter.Func.Method.DeclaringType.Should().NotBe(typeof(PropertyGetter <Bar, IBaz>)); var optimizedTimer = Stopwatch.StartNew(); IBaz optimizedValue = getter.GetValue(bar); optimizedTimer.Stop(); optimizedValue.Should().Be(reflectionValue); optimizedTimer.Elapsed.Should().BeLessThan(reflectionTimer.Elapsed); }
public VirtualPropertyInfo( string name, Type propertyType, Func <object, object> getter, Action <object, object> setter, IEnumerable <Attribute> propertyAttributes, IEnumerable <Attribute> getterAttributes, IEnumerable <Attribute> setterAttributes, CustomReflectionContext context) : base(propertyType, name, context) { if (getter == null && setter == null) { throw new ArgumentException(SR.ArgumentNull_GetterOrSetterMustBeSpecified); } CustomType rcType = propertyType as CustomType; if (rcType == null || rcType.ReflectionContext != context) { throw new ArgumentException(SR.Argument_PropertyTypeFromDifferentContext); } if (getter != null) { _getter = new PropertyGetter(this, getter, getterAttributes); } if (setter != null) { _setter = new PropertySetter(this, setter, setterAttributes); } _attributes = propertyAttributes ?? CollectionServices.Empty <Attribute>(); }
public void PropertyGetterWorksWithStatic() { var property = typeof(Garply).GetProperty(nameof(Garply.Bar)); var getter = new PropertyGetter(property); getter.Func.Target.Should().BeSameAs(property); getter.Func.Method.Name.Should().Be(nameof(property.GetValue)); getter.Func.Method.DeclaringType.Should().Be(typeof(PropertyInfo)); var reflectionTimer = Stopwatch.StartNew(); object reflectionValue = getter.GetValue(null); reflectionTimer.Stop(); getter.SetOptimizedFunc(); getter.Func.Target.Should().NotBeSameAs(property); getter.Func.Method.Name.Should().Be(PropertyGetter.GetValueOptimized); getter.Func.Method.DeclaringType.Should().NotBe(typeof(PropertyInfo)); var optimizedTimer = Stopwatch.StartNew(); object optimizedValue = getter.GetValue(null); optimizedTimer.Stop(); optimizedValue.Should().Be(reflectionValue); optimizedTimer.Elapsed.Should().BeLessThan(reflectionTimer.Elapsed); }
/// <summary> /// Método que genera los Getters de un determinado tipo de objeto (clase) y los /// devuelve en un diccionario que contiene todas las propiedades de la clase /// junto con los métodos creados dinámicamente. /// </summary> /// <param name="type">Tipo (Clase) del que se obtendran las propiedades.</param> /// <param name="cache">Si es true, el Diccionario creado se alamacenará en caché, /// en caso contrario, no se almacenará en caché.</param> /// <returns>Diccionario de duplas (NombrePropiedad, MétodoGetDinámico).</returns> public static IPropertyGetterDictionary GetPropertyGetters(Type type, bool cache) { //Si los Getters ya habian sido creados se devuelven PropertyGetterDictionary getters = GetGettersFromCache(type); if (getters != null) { return(getters); } //Lo primero obtengo las propiedades de ese tipo (clase). //Cada PropertyInfo contiene el tipo y el nombre de una propiedad de la clase (type). PropertyInfo[] props = type.GetProperties(); //Diccionario en el que la clave es el Nombre de la propiedad y el valor el método Get obtenido por reflection Dictionary <string, PropertyGetter> internalGetters = new Dictionary <string, PropertyGetter>(props.Length); foreach (PropertyInfo pi in props) { //Obtenemos en 'setter' el método Get dinámico para el atributo o propiedad 'pi'. PropertyGetter getter = GetPropertyGetter(pi); if (getter != null) { internalGetters.Add(pi.Name.ToLower(), getter); } } getters = new PropertyGetterDictionary(internalGetters); if (cache) { AddGettersToCache(getters, type); } return(getters); }
/// <summary> /// 属性 /// </summary> /// <param name="property">属性信息</param> private PropertyDescriptor(PropertyInfo property) { var aliasAsAttribute = property.GetAttribute <AliasAsAttribute>(true); if (aliasAsAttribute != null && aliasAsAttribute.IsDefinedScope(keyValueFormatScope)) { this.Name = aliasAsAttribute.Name; } else { this.Name = property.Name; } var datetimeFormatAttribute = property.GetCustomAttribute <DateTimeFormatAttribute>(); if (datetimeFormatAttribute != null && datetimeFormatAttribute.IsDefinedScope(keyValueFormatScope)) { this.DateTimeFormat = datetimeFormatAttribute.Format; } if (property.CanRead == true) { this.getter = new PropertyGetter(property); this.IsSupportGet = true; } this.IgnoreSerialized = property.IsDefinedFormatScope <IgnoreSerializedAttribute>(keyValueFormatScope); this.IgnoreWhenNull = property.IsDefinedFormatScope <IgnoreWhenNullAttribute>(keyValueFormatScope); }
public static void AssignPropertiesFrom(this object target, object source) { if (target == null) { throw new ArgumentNullException("target"); } if (source == null) { throw new ArgumentNullException("source"); } Type targetType = target.GetType(); Type sourceType = source.GetType(); var setters = PropertyHelper.GetPropertySetters(targetType); var getters = PropertyHelper.GetPropertyGetters(sourceType); foreach (var kvSetter in setters) { string propertyName = kvSetter.Key; PropertySetter setter = kvSetter.Value; PropertyGetter getter = null; if (getters.TryGetValue(propertyName, out getter)) { setter(target, getter(source)); } } }
/// <summary> /// Representa un mapeo entre los ordinales de los campos del IDataReader y los Getters. /// Devuelve un array en el que su índice y el de los ordinales de los campos del /// IDataReader tienen que coincidir. /// </summary> /// <param name="reader">Estructura de datos que contiene los datos obtenidos de la BD.</param> /// <param name="itemType">Tipo de datos cuyas propiedades deben estar mapeadas con los /// campos de la BD.</param> /// <returns>Vector de Getters.</returns> private static PropertyGetter[] GetPropertyGetters(IDataReader reader, Type itemType) { int fieldCount = reader.FieldCount; PropertyGetter[] propertyGetters = new PropertyGetter[fieldCount]; //Posiblemente esta en la cache y lo devuelve, sino se crea y se devuelve. IPropertyGetterDictionary gettersDictionary = PropertyHelper.GetPropertyGetters(itemType); //Recorremos todos los campos del IDataReader for (int fieldOrdinal = 0; fieldOrdinal < fieldCount; fieldOrdinal++) { PropertyGetter getter; //Mapeo entre ordinal del campo y el nombre de la propiedad de la clase. //Aqui es importante que los campos del IDataReader se llamen exactamente //igual que las propiedades de la clase. Puesto que se buscará el nombre del //campo en el diccionario creado a partir de las propiedades de la clase. if (gettersDictionary.TryGetValue(reader.GetName(fieldOrdinal), out getter)) { propertyGetters[fieldOrdinal] = getter; } } return(propertyGetters); }
public void PropertyObjectTypeConversion() { var inst = new PropertyTests(); Type instType = inst.GetType(); PropertyInfo propRO = instType.GetProperty("MyReadOnlyProperty"); PropertyInfo propRW = instType.GetProperty("MyProperty"); Assert.IsNotNull(propRO); inst.MyWriteOnlyProperty = 999; PropertyGetter <PropertyTests, object> getter = propRO.CreatePropertyGetter <PropertyTests, object>(); Assert.IsNotNull(getter); object actual = getter(inst); Assert.IsNotNull(actual); Assert.AreEqual("999", actual); PropertySetter <PropertyTests, object> setter = propRW.CreatePropertySetter <PropertyTests, object>(); Assert.IsNotNull(setter); setter(inst, 123); Assert.AreEqual(123, inst.MyProperty); }
internal static IDictionary <string, PropertyGetter> GetTypePropertyGetters(Type type) { IDictionary <string, PropertyGetter> getters = new Dictionary <string, PropertyGetter>(); PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo p in props) { if (!p.CanWrite) { continue; } object[] att = p.GetCustomAttributes(typeof(JsonIgnoreAttribute), false); if (att != null && att.Length > 0) { continue; } PropertyGetter g = CreatePeropertyGetter(p); if (g != null) { getters.Add(p.Name, g); } } return(getters); }
public void Fixture_Thing2() { var getter = new PropertyGetter(); var fixture = new Fixture_Thing2() { Thing1 = new Fixture_Thing() { A = "123", B = 1, C = null }, D = 123, E = 1234L }; var value = getter.Get(fixture, "Thing1.A"); value.Should().Be("123"); value = getter.Get(fixture, "Thing1.B"); value.Should().Be(1); value = getter.Get(fixture, "Thing1.C"); value.Should().BeNull(); value = getter.Get(fixture, "D"); value.Should().Be(123); value = getter.Get(fixture, "E"); value.Should().Be(1234L); }
/// <summary> /// Factory method to create an <see cref="IValidationRule"/> based on this attribute. /// </summary> public IValidationRule CreateRule(PropertyInfo property, IResourceResolver resourceResolver) { PropertyGetter getter = CreatePropertyGetter(property); string customMessage = GetLocalizedCustomMessage(resourceResolver); return(CreateRule(property, getter, customMessage)); }
/// <summary> /// Factory method to create an <see cref="IValidationRule"/> based on this attribute. /// </summary> /// <param name="property">The property on which the attribute is applied.</param> /// <param name="getter">A delegate that, when invoked, returns the current value of the property.</param> /// <param name="customMessage">A custom message to be displayed, or null if none was supplied.</param> /// <returns></returns> protected override IValidationRule CreateRule(PropertyInfo property, PropertyGetter getter, string customMessage) { CheckPropertyIsType(property, typeof(IComparable)); if (_referenceProperty != null) { // check that reference property is same type as validating property PropertyInfo refProp = property.DeclaringType.GetProperty(_referenceProperty); if (refProp.PropertyType != property.PropertyType) throw new ValidationAttributeException(SR.ExceptionReferencePropertyMustBeOfSameType); PropertyGetter refPropGetter = CreatePropertyGetter(refProp); return new ValidationRule(property.Name, delegate(IApplicationComponent c) { IComparable value = (IComparable)getter(c); object refValue = refPropGetter(c); return new ValidationResult(Compare(value, refValue, _inclusive), customMessage ?? GetDefaultMessage(refValue)); }); } else { // check that reference value is same type as validating property if (_referenceValue.GetType() != property.PropertyType) throw new ValidationAttributeException(SR.ExceptionReferenceValueMustBeOfSameType); // compare against fixed reference value return new ValidationRule(property.Name, delegate(IApplicationComponent c) { IComparable value = (IComparable)getter(c); return new ValidationResult(Compare(value, _referenceValue, _inclusive), customMessage ?? GetDefaultMessage(_referenceValue)); }); } }
public static void GetDelegates(object obj, string displayName, out PropertyGetter <T> getter, out PropertySetter <T> setter) { var inspector = new PropertyDelegateInspector <T>(obj, displayName); getter = inspector.Getter; setter = inspector.Setter; }
/// <summary> /// Factory method to create an <see cref="IValidationRule"/> based on this attribute. /// </summary> /// <param name="property">The property on which the attribute is applied.</param> /// <param name="getter">A delegate that, when invoked, returns the current value of the property.</param> /// <param name="customMessage">A custom message to be displayed, or null if none was supplied.</param> /// <returns></returns> protected override IValidationRule CreateRule(PropertyInfo property, PropertyGetter getter, string customMessage) { CheckPropertyIsType(property, typeof(string)); string message = customMessage; if (message == null) { if (_maxLength == -1) { message = string.Format(SR.FormatMoreThanXCharactersRequired, _minLength); } else { message = string.Format(SR.FormatRangeCharactersRequired, _minLength, _maxLength); } } return(new ValidationRule(property.Name, delegate(IApplicationComponent component) { // convert null string to "" string value = ((string)getter(component)) ?? ""; return new ValidationResult(value.Length >= _minLength && (_maxLength == -1 || value.Length <= _maxLength), message); })); }
public AProperty(string name, PropertyGetter <T> getter, PropertySetter <T> setter) { Dirty = false; Name = name; Getter = getter; Setter = setter; }
public void PropertyGetter2Works() { var foo = new Foo("abc"); var property = typeof(Foo).GetProperty(nameof(Foo.Bar)); var getter = new PropertyGetter <Foo, string>(property); getter.Func.Target.Should().BeSameAs(getter); getter.Func.Method.Name.Should().Be(nameof(getter.GetValueReflection)); getter.Func.Method.DeclaringType.Should().Be(typeof(PropertyGetter <Foo, string>)); var reflectionTimer = Stopwatch.StartNew(); string reflectionValue = getter.GetValue(foo); reflectionTimer.Stop(); getter.SetOptimizedFunc(); getter.Func.Target.Should().NotBeSameAs(getter); getter.Func.Method.Name.Should().Be(PropertyGetter.GetValueOptimized); getter.Func.Method.DeclaringType.Should().NotBe(typeof(PropertyGetter <Foo, string>)); var optimizedTimer = Stopwatch.StartNew(); string optimizedValue = getter.GetValue(foo); optimizedTimer.Stop(); optimizedValue.Should().Be(reflectionValue); optimizedTimer.Elapsed.Should().BeLessThan(reflectionTimer.Elapsed); }
public PropertyEnumeration Get(PropertyGetter getter) { foreach (Amendment.Property property in this) { property.GetterMethod = getter.Method; } return(this); }
public void ValueTypePropertyGetterObjectTest(string propertyName) { PropertyGetter <TestStruct, object> getInt32 = DynamicType <TestStruct> .CreatePropertyGetter <object>(propertyName); TestStruct obj = TestStruct.Default; Assert.IsTrue(getInt32(obj).GetType() == typeof(object)); }
public void Fixture_IndexInvalid(object fixture, string path) { var getter = new PropertyGetter(); Action a = () => getter.Get(fixture, path); a.Should().Throw <ArgumentException>(); }
public CustomerService(ICustomerRepository customerRepository, IPurchaseRepository purchaseRepository, IProductRepository productRepository, IConfiguration config) { _customerRepository = customerRepository; _purchaseRepository = purchaseRepository; _productRepository = productRepository; _propertyGetter = new PropertyGetter(config.GetConnectionString("ChainStoreDBVer2")); }
public void ValueTypePropertyGetterStringTest(string propertyName, object expected) { PropertyGetter <TestStruct, string> getInt32 = DynamicType <TestStruct> .CreatePropertyGetter <string>(propertyName); TestStruct obj = TestStruct.Default; Assert.AreEqual(expected, getInt32(obj)); }
public void Fixture_Dictionary(object fixture, string path, object expected) { var getter = new PropertyGetter(); var result = getter.Get(fixture, path); result.Should().Be(expected); }
public void PropertyGetterIntTest(string propertyName, object expected) { PropertyGetter <TestClass, int> getInt32 = DynamicType <TestClass> .CreatePropertyGetter <int>(propertyName); TestClass obj = new TestClass(); Assert.AreEqual(expected, getInt32(obj)); }
public void Fixture_Enumerable_WithSeperator(object fixture, string path, object expected) { var getter = new PropertyGetter("__"); var result = getter.Get(fixture, path); result.Should().Be(expected); }
public void PropertyGetterObjectTest(string propertyName) { PropertyGetter <TestClass, object> getInt32 = DynamicType <TestClass> .CreatePropertyGetter <object>(propertyName); TestClass obj = new TestClass(); Assert.IsTrue(getInt32(obj).GetType() == typeof(object)); }
public void ReferenceTypePropertyGetterGetHashCode() { TestClass obj = new TestClass(); PropertyGetter <TestClass, int> getHashCode = DynamicType <TestClass> .CreatePropertyGetterGetHashCode("PublicPhone"); Assert.AreEqual(obj.PublicPhone.GetHashCode(), getHashCode(obj)); }
public void ValueTypePropertyGetterGetHashCode() { PropertyGetter <TestStruct, int> getHashCode = DynamicType <TestStruct> .CreatePropertyGetterGetHashCode("PublicPhone"); TestStruct testStruct = TestStruct.Default; Assert.AreEqual(testStruct.PublicPhone.GetHashCode(), getHashCode(testStruct)); }
public void ReferenceTypePropertyGetterAsObject(string propertyName, object expected) { PropertyGetter <TestClass, object> getObject = DynamicType <TestClass> .CreatePropertyGetterAsObject(propertyName); TestClass obj = new TestClass(); Assert.AreEqual(expected, getObject(obj)); }
public void ValueTypePropertyGetterAsObject(string propertyName, object expected) { PropertyGetter <TestStruct, object> getObject = DynamicType <TestStruct> .CreatePropertyGetterAsObject(propertyName); TestStruct testStruct = TestStruct.Default; Assert.AreEqual(expected, getObject(testStruct)); }
public void PropertyGetterStringTest(string propertyName, object expected) { PropertyGetter <TestClass, string> getString = DynamicType <TestClass> .CreatePropertyGetter <string>(propertyName); TestClass obj = new TestClass(); Assert.AreEqual(expected, getString(obj)); }
/// <summary> /// Factory method to create an <see cref="IValidationRule"/> based on this attribute. /// </summary> /// <param name="property">The property on which the attribute is applied.</param> /// <param name="getter">A delegate that, when invoked, returns the current value of the property.</param> /// <param name="customMessage">A custom message to be displayed, or null if none was supplied.</param> /// <returns></returns> protected override IValidationRule CreateRule(PropertyInfo property, PropertyGetter getter, string customMessage) { string message = customMessage ?? SR.MessageValueRequired; return new ValidationRule(property.Name, delegate(IApplicationComponent component) { object value = getter(component); return new ValidationResult((value is string) ? !string.IsNullOrEmpty(value as string) : value != null, message); }); }
/// <summary> /// Constructs the property manager. /// </summary> /// <param name="platformType">The platform type to represent.</param> /// <param name="getter">Receives property get requests and returns mock values.</param> /// <param name="setter">Receives property set requests and checks them.</param> public MockPropertyManager( ProjectPlatformType platformType, PropertyGetter getter, PropertySetter setter) { this.PlatformType = platformType; if (platformType == ProjectPlatformType.NaCl) this.PlatformName = Strings.NaCl64PlatformName; else this.PlatformName = Strings.PepperPlatformName; getter_ = getter; setter_ = setter; }
/// <summary> /// Factory method to create an <see cref="IValidationRule"/> based on this attribute. /// </summary> /// <param name="property">The property on which the attribute is applied.</param> /// <param name="getter">A delegate that, when invoked, returns the current value of the property.</param> /// <param name="customMessage">A custom message to be displayed, or null if none was supplied.</param> /// <returns></returns> protected override IValidationRule CreateRule(PropertyInfo property, PropertyGetter getter, string customMessage) { CheckPropertyIsType(property, typeof(string)); string message = customMessage ?? SR.MessageUnrecognizedFormat; return new ValidationRule(property.Name, delegate(IApplicationComponent component) { string value = (string)getter(component); if (_allowNull && string.IsNullOrEmpty(value)) return new ValidationResult(true, ""); else return new ValidationResult(Regex.Match(value ?? "", _pattern).Success == SuccessOnMatch, message); }); }
/// <summary> /// Factory method to create an <see cref="IValidationRule"/> based on this attribute. /// </summary> /// <param name="property">The property on which the attribute is applied.</param> /// <param name="getter">A delegate that, when invoked, returns the current value of the property.</param> /// <param name="customMessage">A custom message to be displayed, or null if none was supplied.</param> /// <returns></returns> protected override IValidationRule CreateRule(PropertyInfo property, PropertyGetter getter, string customMessage) { CheckPropertyIsType(property, typeof(string)); string message = customMessage; if (message == null) { if (_maxLength == -1) message = string.Format(SR.FormatMoreThanXCharactersRequired, _minLength); else message = string.Format(SR.FormatRangeCharactersRequired, _minLength, _maxLength); } return new ValidationRule(property.Name, delegate(IApplicationComponent component) { // convert null string to "" string value = ((string)getter(component)) ?? ""; return new ValidationResult(value.Length >= _minLength && (_maxLength == -1 || value.Length <= _maxLength), message); }); }
/// <summary> /// 생성자 /// </summary> public SqlCommandSet() { if(IsDebugEnabled) log.Debug("{0}를 동적으로 생성하고, 내부 함수를 Delegate로 이용하여, 노출시킵니다.", SqlCommandSetTypeName); _sqlCommandSetInstance = ActivatorTool.CreateInstance(_sqlCommandSetType, true); _sqlCommandSetInstance.ShouldNotBeNull(SqlCommandSetTypeName); _connectionSettter = (PropertySetter<SqlConnection>)CreateDelegate(typeof(PropertySetter<SqlConnection>), _sqlCommandSetInstance, "set_Connection"); _transactionSetter = (PropertySetter<SqlTransaction>)CreateDelegate(typeof(PropertySetter<SqlTransaction>), _sqlCommandSetInstance, "set_Transaction"); _commandTimeoutSetter = (PropertySetter<int>)CreateDelegate(typeof(PropertySetter<int>), _sqlCommandSetInstance, "set_CommandTimeout"); _connectionGetter = (PropertyGetter<SqlConnection>)CreateDelegate(typeof(PropertyGetter<SqlConnection>), _sqlCommandSetInstance, "get_Connection"); _batchCommandGetter = (PropertyGetter<SqlCommand>)CreateDelegate(typeof(PropertyGetter<SqlCommand>), _sqlCommandSetInstance, "get_BatchCommand"); _doAppend = (AppendCommand)CreateDelegate(typeof(AppendCommand), _sqlCommandSetInstance, "Append"); _doExecuteNonQuery = (ExecuteNonQueryCommand)CreateDelegate(typeof(ExecuteNonQueryCommand), _sqlCommandSetInstance, "ExecuteNonQuery"); _doDispose = (DisposeCommand)CreateDelegate(typeof(DisposeCommand), _sqlCommandSetInstance, "Dispose"); }
/// <summary> /// Collects a property of a tool across across multiple property sheets /// with inheritance (i.e. respecting $(Inherit) and $(NoInherit) macros). /// </summary> /// <param name="configuration">The project configuration.</param> /// <param name="toolName">The name of the tool, e.g. "VCCLCompilerTool".</param> /// <param name="propGetter">The getter that retrieves the property.</param> /// <remarks> /// This method tries to emulate Visual Studio, since the Extensibility API /// doesn't seem to provide anything like this. /// </remarks> public static List<string> Get(VCConfiguration configuration, string toolName, PropertyGetter propGetter) { ArgData data = new ArgData(); data.conf = configuration; data.sheets = Utils.call(() => (data.conf.PropertySheets as IVCCollection)); data.numSheets = Utils.call(() => (data.sheets.Count)); data.toolName = toolName; data.propGetter = propGetter; data.result = new List<string>(); _Get(data, 0); return data.result; }
/// <summary> /// Factory method to create an <see cref="IValidationRule"/> based on this attribute. /// </summary> /// <param name="property">The property on which the attribute is applied.</param> /// <param name="getter">A delegate that, when invoked, returns the current value of the property.</param> /// <param name="customMessage">A custom message to be displayed, or null if none was supplied.</param> /// <returns></returns> protected abstract IValidationRule CreateRule(PropertyInfo property, PropertyGetter getter, string customMessage);