public PocoComponentTuplizer(Mapping.Component component) : base(component) { componentClass = component.ComponentClass; var parentProperty = component.ParentProperty; if (parentProperty == null) { parentSetter = null; parentGetter = null; } else { parentSetter = parentProperty.GetSetter(componentClass); parentGetter = parentProperty.GetGetter(componentClass); } if (hasCustomAccessors || !Cfg.Environment.UseReflectionOptimizer) { optimizer = null; } else { optimizer = Cfg.Environment.BytecodeProvider.GetReflectionOptimizer(componentClass, getters, setters); } }
protected override bool ShouldLog(MemberInfo m, out IGetter getter) { getter = null; /** * Check if it is annotated with ToLog */ if (!Attribute.IsDefined(m, typeof(ToLogAttribute))) { return(false); } ToLogAttribute attr = (ToLogAttribute)m.GetCustomAttribute(typeof(ToLogAttribute)); /** * Check if it is a Field */ if (m.MemberType == MemberTypes.Field) { getter = new GetterFieldFormat((FieldInfo)m, attr.formatter); return(true); } /** * Check if it is a parameterless method */ if (m.MemberType == MemberTypes.Method && (m as MethodInfo).GetParameters().Length == 0) { getter = new GetterMethodFormat((MethodInfo)m, attr.formatter); return(true); } return(false); }
public static GetterFiltered <T> MCoreend(IGetter <IEnumerable <T> > source, params Func <T, bool>[] filters) { return(new GetterFiltered <T>(source) { AFLT = filters }); }
public IGetter CreateIGetterForField(Type targetType, string memberName) { Type getterType = BuildDynamicGetterTypeFor(targetType, memberName); IGetter getter = (IGetter)Activator.CreateInstance(getterType, new object[] { }); return(getter); }
public DocumentIdMapping(string name, string propertyName, ITwoWayFieldBridge bridge, IGetter getter) : base(getter) { this.Name = name; this.PropertyName = propertyName; this.Bridge = bridge; }
/// <summary> /// Validate if that member m should be logged, i.e. it must have a ToLog annotation /// and be a field or a parameterless method. /// Also it may return an instance of GetterField or GetterMethod. /// </summary> protected virtual bool ShouldLog(MemberInfo m, out IGetter getter) { getter = null; /** * Check if it is annotated with ToLog */ if (!Attribute.IsDefined(m, typeof(ToLogAttribute))) { return(false); } /** * Check if it is a Field */ if (m.MemberType == MemberTypes.Field) { getter = new GetterField((FieldInfo)m); return(true); } /** * Check if it is a parameterless method */ if (m.MemberType == MemberTypes.Method && (m as MethodInfo).GetParameters().Length == 0) { getter = new GetterMethod((MethodInfo)m); return(true); } return(false); }
public EmbeddedMapping(DocumentMapping @class, IGetter getter) : base(getter) { this.Class = @class; this.Prefix = string.Empty; this.IsCollection = true; }
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); } }
public IBatchable Create(Input item) { string src = null, typ = "exception"; if (!item.TrySet(ref src, 1, "file")) { throw new ArgumentException("Не установлено свойство: file(1)"); } if (!item.TrySet(ref typ, 2, "modify")) { } var mdf = Helpers.ParseBehaviour(typ); IGetter <string> gfil = null; if (FFiles != null) { gfil = new GetterTextFile(FFiles, src, mdf); } else { gfil = new GetterTextFile(src, mdf); } return(new CmdReadText(gfil, Destination)); }
/// <summary> /// Generates a dynamic method on the given type. /// </summary> private GetPropertyValuesInvoker GenerateGetPropertyValuesMethod(IGetter[] getters) { var methodArguments = new[] { typeof(object), typeof(GetterCallback) }; DynamicMethod method = CreateDynamicMethod(typeof(object[]), methodArguments); ILGenerator il = method.GetILGenerator(); LocalBuilder thisLocal = il.DeclareLocal(typeOfThis); LocalBuilder dataLocal = il.DeclareLocal(typeof(object[])); // Cast the 'this' pointer to the appropriate type and store it in a local variable il.Emit(OpCodes.Ldarg_0); EmitCastToReference(il, mappedType); il.Emit(OpCodes.Stloc, thisLocal); // Allocate the values array and store it in a local variable il.Emit(OpCodes.Ldc_I4, getters.Length); il.Emit(OpCodes.Newarr, typeof(object)); il.Emit(OpCodes.Stloc, dataLocal); //get all the data from the object into the data array to be returned for (int i = 0; i < getters.Length; i++) { // get the member accessors IGetter getter = getters[i]; // queue up the array storage location for the value il.Emit(OpCodes.Ldloc, dataLocal); il.Emit(OpCodes.Ldc_I4, i); // get the value... var optimizableGetter = getter as IOptimizableGetter; if (optimizableGetter != null) { // using the getter's emitted IL code il.Emit(OpCodes.Ldloc, thisLocal); optimizableGetter.Emit(il); EmitUtil.EmitBoxIfNeeded(il, getter.ReturnType); } else { // using the getter itself via a callback MethodInfo invokeMethod = typeof(GetterCallback).GetMethod("Invoke", new[] { typeof(object), typeof(int) }); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldc_I4, i); il.Emit(OpCodes.Callvirt, invokeMethod); } //store the value il.Emit(OpCodes.Stelem_Ref); } // Return the data array il.Emit(OpCodes.Ldloc, dataLocal.LocalIndex); il.Emit(OpCodes.Ret); return((GetPropertyValuesInvoker)method.CreateDelegate(typeof(GetPropertyValuesInvoker))); }
public IQuery SetProperties(object bean) { System.Type clazz = bean.GetType(); string[] @params = NamedParameters; for (int i = 0; i < @params.Length; i++) { string namedParam = @params[i]; try { IGetter getter = ReflectHelper.GetGetter(clazz, namedParam, "property"); System.Type retType = getter.ReturnType; object obj = getter.Get(bean); if (typeof(ICollection).IsAssignableFrom(retType)) { SetParameterList(namedParam, (ICollection)obj); } else if (retType.IsArray) { SetParameterList(namedParam, (Object[])obj); } else { SetParameter(namedParam, obj, DetermineType(namedParam, retType)); } } catch (PropertyNotFoundException) { // ignore } } return(this); }
public PocoComponentTuplizer(Mapping.Component component) : base(component) { componentClass = component.ComponentClass; var parentProperty = component.ParentProperty; if (parentProperty == null) { parentSetter = null; parentGetter = null; } else { parentSetter = parentProperty.GetSetter(componentClass); parentGetter = parentProperty.GetGetter(componentClass); } //todo ÐÞ¸ÄÔ´Âë //if (hasCustomAccessors || !Cfg.Environment.UseReflectionOptimizer) //{ // optimizer = null; //} //else //{ // optimizer = Cfg.Environment.BytecodeProvider.GetReflectionOptimizer(componentClass, getters, setters); //} }
protected virtual bool ShoudlLog(MemberInfo m, out IGetter getter) { getter = null; /// /// Check if ToLog annotation exists /// if (!Attribute.IsDefined(m, typeof(ToLogAttribute))) { return(false); } /// /// Check if is a field or parameterless method /// if (m.MemberType == MemberTypes.Field) { getter = new GetterField((FieldInfo)m); return(true); } if (m.MemberType == MemberTypes.Method) { MethodInfo mi = (MethodInfo)m; if (mi.GetParameters().Length == 0) { getter = new GetterMethod((MethodInfo)m); return(true); } } return(false); }
public override IEnumerable <IGetter> GetMembers(Type t) { // First check if exist in members dictionary List <IGetter> ms; if (!members.TryGetValue(t, out ms)) { DynamicGetterBuider builder = new DynamicGetterBuider(t); ms = new List <IGetter>(); foreach (MemberInfo m in t.GetMembers()) { IGetter getter = null; if (ShoudlLog(m, out getter)) { // 1. Create the class that extends AbstractGetter for that member m in domain type t. Type getterType = builder.GenerateGetterFor(m); // 2. Instantiate the class created on 1. getter = (IGetter)Activator.CreateInstance(getterType); ms.Add(getter); } } members.Add(t, ms); } return(ms); }
public PersistenceFixture(IReferenceable refs, IConfigurable conf, IOpenable open, IClosable close, ICleanable clean, IWriter<Dummy, string> write, IGetter<Dummy, string> get, ISetter<Dummy> set) { Assert.NotNull(refs); _refs = refs; Assert.NotNull(conf); _conf = conf; Assert.NotNull(open); _open = open; Assert.NotNull(close); _close = close; Assert.NotNull(clean); _clean = clean; Assert.NotNull(write); _write = write; Assert.NotNull(get); _get = get; Assert.NotNull(set); _set = set; }
public PocoComponentTuplizer(Mapping.Component component) : base(component) { componentClass = component.ComponentClass; var parentProperty = component.ParentProperty; if (parentProperty == null) { parentSetter = null; parentGetter = null; } else { parentSetter = parentProperty.GetSetter(componentClass); parentGetter = parentProperty.GetGetter(componentClass); } SetReflectionOptimizer(); // Fix for NH-3119 instantiator = BuildInstantiator(component); ClearOptimizerWhenUsingCustomAccessors(); }
/// <summary> Constructs a new AbstractEntityTuplizer instance. </summary> /// <param name="entityMetamodel">The "interpreted" information relating to the mapped entity. </param> /// <param name="mappingInfo">The parsed "raw" mapping data relating to the given entity. </param> protected AbstractEntityTuplizer(EntityMetamodel entityMetamodel, PersistentClass mappingInfo) { this.entityMetamodel = entityMetamodel; if (!entityMetamodel.IdentifierProperty.IsVirtual) { idGetter = BuildPropertyGetter(mappingInfo.IdentifierProperty, mappingInfo); idSetter = BuildPropertySetter(mappingInfo.IdentifierProperty, mappingInfo); } else { idGetter = null; idSetter = null; } propertySpan = entityMetamodel.PropertySpan; getters = new IGetter[propertySpan]; setters = new ISetter[propertySpan]; bool foundCustomAccessor = false; int i = 0; foreach (Mapping.Property property in mappingInfo.PropertyClosureIterator) { getters[i] = BuildPropertyGetter(property, mappingInfo); setters[i] = BuildPropertySetter(property, mappingInfo); if (!property.IsBasicPropertyAccessor) { foundCustomAccessor = true; } i++; } if (log.IsDebugEnabled()) { log.Debug("{0} accessors found for entity: {1}", foundCustomAccessor ? "Custom" : "No custom", mappingInfo.EntityName); } hasCustomAccessors = foundCustomAccessor; //NH-1587 //instantiator = BuildInstantiator(mappingInfo); if (entityMetamodel.IsLazy) { proxyFactory = BuildProxyFactory(mappingInfo, idGetter, idSetter); if (proxyFactory == null) { entityMetamodel.IsLazy = false; } } else { proxyFactory = null; } Mapping.Component mapper = mappingInfo.IdentifierMapper; identifierMapperType = mapper == null ? null : (IAbstractComponentType)mapper.Type; }
public static VersionValue GetUnsavedVersionValue( String versionUnsavedValue, IGetter versionGetter, IVersionType versionType, ConstructorInfo constructor) { if (versionUnsavedValue == null) { if (constructor != null) { object defaultValue = versionGetter.Get(Instantiate(constructor)); if (defaultValue != null && defaultValue.GetType().IsValueType) { return(new VersionValue(defaultValue)); } else { // if the version of a newly instantiated object is not the same // as the version seed value, use that as the unsaved-value return (versionType.IsEqual(versionType.Seed(null), defaultValue) ? VersionValue.VersionUndefined : new VersionValue(defaultValue)); } } else { return(VersionValue.VersionUndefined); } } else if ("undefined" == versionUnsavedValue) { return(VersionValue.VersionUndefined); } else if ("null" == versionUnsavedValue) { return(VersionValue.VersionSaveNull); } else if ("negative" == versionUnsavedValue) { return(VersionValue.VersionNegative); } else { // NHibernate-specific try { return(new VersionValue(versionType.FromStringValue(versionUnsavedValue))); } catch (InvalidCastException ice) { throw new MappingException("Bad version type: " + versionType.Name, ice); } catch (Exception e) { throw new MappingException("Could not parse version unsaved-value: " + versionUnsavedValue, e); } } }
public static void RegisterGetter(Type type, IGetter getter) { var getters = _getters.GetOrAdd(type, t => new SynchronizedCollection <IGetter>()); getters.Add(getter); }
public void StringElementExtraction() { Property property = GenerateNameProperty(); IGetter getter = PropertyAccessorFactory.GetPropertyAccessor(property, EntityMode.Xml).GetGetter(null, null); var name = (string)getter.Get(dom); Assert.That(name, Is.EqualTo("NHForge")); }
public FieldMapping(string name, IFieldBridge bridge, IGetter getter) : base(getter) { this.Name = name; this.Bridge = bridge; this.Store = Attributes.Store.No; this.Index = Attributes.Index.Tokenized; }
public void LongElementAttributeExtraction() { Property property = GenerateAccountIdProperty(); IGetter getter = PropertyAccessorFactory.GetPropertyAccessor(property, EntityMode.Xml).GetGetter(null, null); var id = (long)getter.Get(dom); Assert.That(id, Is.EqualTo(456L)); }
public void StringTextExtraction() { Property property = GenerateTextProperty(); IGetter getter = PropertyAccessorFactory.GetPropertyAccessor(property, EntityMode.Xml).GetGetter(null, null); var name = (string)getter.Get(dom); Assert.That(name, Is.EqualTo("description...")); }
static IGetter CheckToFormatter(MemberInfo member, IGetter getter) { LogFormatterAttribute attr = (LogFormatterAttribute)member.GetCustomAttribute(typeof(LogFormatterAttribute)); return(attr != null ? new GetterFormatter(getter, attr) : getter); }
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); }
/// <summary> /// Generate the required code /// </summary> /// <returns>C# code</returns> private string GenerateCode() { StringBuilder sb = new StringBuilder(); sb.Append(header); sb.AppendFormat(classDef, mappedClass.FullName.Replace('.', '_').Replace("+", "__")); sb.AppendFormat(startSetMethod, mappedClass.FullName.Replace('+', '.')); for (int i = 0; i < setters.Length; i++) { ISetter setter = setters[i]; System.Type type = setters[i].Property.PropertyType; if (setter is BasicSetter && IsPublic(setter.PropertyName)) { if (type.IsValueType) { sb.AppendFormat( " t.{0} = values[{2}] == null ? new {1}() : ({1})values[{2}];\n", setter.PropertyName, type.FullName.Replace('+', '.'), i); } else { sb.AppendFormat(" t.{0} = ({1})values[{2}];\n", setter.PropertyName, type.FullName.Replace('+', '.'), i); } } else { sb.AppendFormat(" setters[{0}].Set(obj, values[{0}]);\n", i); } } sb.Append(closeSetMethod); // Close Set sb.AppendFormat(startGetMethod, mappedClass.FullName.Replace('+', '.'), getters.Length); for (int i = 0; i < getters.Length; i++) { IGetter getter = getters[i]; if (getter is BasicGetter && IsPublic(getter.PropertyName)) { sb.AppendFormat(" ret[{0}] = t.{1};\n", i, getter.PropertyName); } else { sb.AppendFormat(" ret[{0}] = getters[{0}].Get(obj);\n", i); } } sb.Append(closeGetMethod); sb.Append("}\n"); // Close class sb.Append("}\n"); // Close namespace return(sb.ToString()); }
public static VersionValue GetUnsavedVersionValue( String versionUnsavedValue, IGetter versionGetter, IVersionType versionType, ConstructorInfo constructor) { if (versionUnsavedValue == null) { if (constructor != null) { object defaultValue = versionGetter.Get(Instantiate(constructor)); if (defaultValue != null && defaultValue.GetType().IsValueType) return new VersionValue(defaultValue); else { // if the version of a newly instantiated object is not the same // as the version seed value, use that as the unsaved-value return versionType.IsEqual(versionType.Seed(null), defaultValue) ? VersionValue.VersionUndefined : new VersionValue(defaultValue); } } else { return VersionValue.VersionUndefined; } } else if ("undefined" == versionUnsavedValue) { return VersionValue.VersionUndefined; } else if ("null" == versionUnsavedValue) { return VersionValue.VersionSaveNull; } else if ("negative" == versionUnsavedValue) { return VersionValue.VersionNegative; } else { // NHibernate-specific try { return new VersionValue(versionType.FromStringValue(versionUnsavedValue)); } catch (InvalidCastException ice) { throw new MappingException("Bad version type: " + versionType.Name, ice); } catch (Exception e) { throw new MappingException("Could not parse version unsaved-value: " + versionUnsavedValue, e); } } }
/// <summary> Constructs a new AbstractEntityTuplizer instance. </summary> /// <param name="entityMetamodel">The "interpreted" information relating to the mapped entity. </param> /// <param name="mappingInfo">The parsed "raw" mapping data relating to the given entity. </param> protected AbstractEntityTuplizer(EntityMetamodel entityMetamodel, PersistentClass mappingInfo) { this.entityMetamodel = entityMetamodel; if (!entityMetamodel.IdentifierProperty.IsVirtual) { idGetter = BuildPropertyGetter(mappingInfo.IdentifierProperty, mappingInfo); idSetter = BuildPropertySetter(mappingInfo.IdentifierProperty, mappingInfo); } else { idGetter = null; idSetter = null; } propertySpan = entityMetamodel.PropertySpan; getters = new IGetter[propertySpan]; setters = new ISetter[propertySpan]; bool foundCustomAccessor = false; int i = 0; foreach (Mapping.Property property in mappingInfo.PropertyClosureIterator) { getters[i] = BuildPropertyGetter(property, mappingInfo); setters[i] = BuildPropertySetter(property, mappingInfo); if (!property.IsBasicPropertyAccessor) foundCustomAccessor = true; i++; } if (log.IsDebugEnabled) { log.DebugFormat("{0} accessors found for entity: {1}", foundCustomAccessor ? "Custom" : "No custom", mappingInfo.EntityName); } hasCustomAccessors = foundCustomAccessor; //NH-1587 //instantiator = BuildInstantiator(mappingInfo); if (entityMetamodel.IsLazy) { proxyFactory = BuildProxyFactory(mappingInfo, idGetter, idSetter); if (proxyFactory == null) { entityMetamodel.IsLazy = false; } } else { proxyFactory = null; } Mapping.Component mapper = mappingInfo.IdentifierMapper; identifierMapperType = mapper == null ? null : (IAbstractComponentType)mapper.Type; }
public override ISpanContext Extract <C>(C carrier, IGetter <C> getter) { if (carrier == null) { throw new ArgumentNullException(nameof(carrier)); } if (getter == null) { throw new ArgumentNullException(nameof(getter)); } try { ITraceId traceId; string traceIdStr = getter.Get(carrier, X_B3_TRACE_ID); if (traceIdStr != null) { if (traceIdStr.Length == TraceId.SIZE) { // This is an 8-byte traceID. traceIdStr = UPPER_TRACE_ID + traceIdStr; } traceId = TraceId.FromLowerBase16(traceIdStr); } else { throw new SpanContextParseException("Missing X_B3_TRACE_ID."); } ISpanId spanId; string spanIdStr = getter.Get(carrier, X_B3_SPAN_ID); if (spanIdStr != null) { spanId = SpanId.FromLowerBase16(spanIdStr); } else { throw new SpanContextParseException("Missing X_B3_SPAN_ID."); } TraceOptions traceOptions = TraceOptions.DEFAULT; if (SAMPLED_VALUE.Equals(getter.Get(carrier, X_B3_SAMPLED)) || FLAGS_VALUE.Equals(getter.Get(carrier, X_B3_FLAGS))) { traceOptions = TraceOptions.Builder().SetIsSampled(true).Build(); } return(SpanContext.Create(traceId, spanId, traceOptions)); } catch (Exception e) { throw new SpanContextParseException("Invalid input.", e); } }
public override IReflectionOptimizer GetReflectionOptimizer(System.Type clazz, IGetter[] getters, ISetter[] setters) { if (clazz.IsValueType) { // Cannot create optimizer for value types - the setter method will not work. log.Info("Disabling reflection optimizer for value type " + clazz.FullName); return null; } return new Generator(clazz, getters, setters).CreateReflectionOptimizer(); }
public void TestGenerateIGetterForStudentName() { // Arrange IGetter getter = dynamicIGetterInstanceCreator.CreateIGetterFor(typeof(Student), "name"); // // Asserts Assert.NotNull(getter); Assert.AreEqual("name", getter.GetName()); Assert.AreEqual(s1.name, (string)getter.GetValue(s1)); }
/// <summary> /// Generate the IGetSetHelper object /// </summary> /// <param name="mappedClass">The target class</param> /// <param name="setters">Array of setters</param> /// <param name="getters">Array of getters</param> /// <returns>null if the generation fail</returns> public static IGetSetHelper Create( System.Type mappedClass, ISetter[] setters, IGetter[] getters ) { if (mappedClass.IsValueType) { // Cannot create optimizer for value types - the setter method will not work. log.Info( "Disabling reflection optimizer for value type " + mappedClass.FullName ); return null; } return new GetSetHelperFactory( mappedClass, setters, getters ).CreateGetSetHelper(); }
public void TestGenerateIGetterForStudentNumber() { // Arrange IGetter getter = dynamicIGetterInstanceCreator.CreateIGetterForField(typeof(Student), "nr"); // // Asserts Assert.NotNull(getter); Assert.AreEqual("nr", getter.GetName()); Assert.AreEqual(s1.nr, (int)getter.GetValue(s1)); }
public AccessOptimizer(GetPropertyValuesInvoker getDelegate, SetPropertyValuesInvoker setDelegate, IGetter[] getters, ISetter[] setters) { this.getDelegate = getDelegate; this.setDelegate = setDelegate; this.getters = getters; this.setters = setters; getterCallback = OnGetterCallback; setterCallback = OnSetterCallback; }
protected FluentMappingPart(PropertyInfo propertyInfo) { this.Name(propertyInfo.Name); // set the default getter this.Getter = new BasicPropertyAccessor.BasicGetter(propertyInfo.DeclaringType, propertyInfo, propertyInfo.Name); // set the default bridge var bridge = BridgeFactory.GuessType(propertyInfo.Name, propertyInfo.PropertyType, null, null); (this as IHasBridge).FieldBridge = bridge; }
public void CamelCaseUnderscoreNamingStrategy() { IGetter fieldGetter = ReflectHelper.GetGetter(typeof(FieldGetterClass), "PropertyTwo", "field.camelcase-underscore"); Assert.IsNotNull(fieldGetter, "should have found getter"); Assert.AreEqual(typeof(FieldAccessor.FieldGetter), fieldGetter.GetType(), "IGetter should be for a field."); Assert.AreEqual(typeof(Boolean), fieldGetter.ReturnType, "returns Boolean."); Assert.IsNull(fieldGetter.Method, "no MethodInfo for fields."); Assert.IsNull(fieldGetter.PropertyName, "no Property Names for fields."); Assert.AreEqual(true, fieldGetter.Get(obj), "Get() for Boolean"); }
public DefaultTrackingModifiedEntitiesRevisionInfoGenerator(string revisionInfoEntityName, System.Type revisionInfoType, IRevisionListener revisionListener, PropertyData revisionInfoTimestampData, bool timestampAsDate, PropertyData modifiedEntityNamesData) : base(revisionInfoEntityName, revisionInfoType, revisionListener, revisionInfoTimestampData, timestampAsDate) { modifiedEntityTypesGetter = ReflectionTools.GetGetter(revisionInfoType, modifiedEntityNamesData); modifiedEntityTypesSetter = ReflectionTools.GetSetter(revisionInfoType, modifiedEntityNamesData); }
public void LowerCaseUnderscoreNamingStrategy() { IGetter fieldGetter = ReflectHelper.GetGetter(typeof(FieldGetterClass), "PropertyFour", "field.lowercase-underscore"); Assert.IsNotNull(fieldGetter, "should have found getter"); Assert.AreEqual(typeof(FieldAccessor.FieldGetter), fieldGetter.GetType(), "IGetter should be for a field."); Assert.AreEqual(typeof(Int64), fieldGetter.ReturnType, "returns Int64."); Assert.IsNull(fieldGetter.Method, "no MethodInfo for fields."); Assert.IsNull(fieldGetter.PropertyName, "no Property Names for fields."); Assert.AreEqual(Int64.MaxValue, fieldGetter.Get(obj), "Get() for Int64"); }
/* * 1. Create a new implementation of IGetter for member memberName in domain type targetType * 2. Creates an instance of that type created in 1. */ public IGetter CreateIGetterFor(Type targetType, MemberInfo member) { if (member.MemberType != MemberTypes.Field) { throw new InvalidOperationException("LogDynamic does not support other kind of members beyond Fields like " + member.Name); } Type getterType = BuildDynamicGetterTypeFor(targetType, (FieldInfo)member); IGetter getter = (IGetter)Activator.CreateInstance(getterType, new object[] { }); return(getter); }
public void NoGetter() { IGetter[] getters = new IGetter[] { new BasicPropertyAccessor.BasicGetter(typeof (NoGetterClass), typeof (NoGetterClass).GetProperty("Property"), "Property") }; ISetter[] setters = new ISetter[] { new BasicPropertyAccessor.BasicSetter(typeof (NoGetterClass), typeof (NoGetterClass).GetProperty("Property"), "Property") }; Assert.Throws<PropertyNotFoundException>(() => new ReflectionOptimizer(typeof (NoGetterClass), getters, setters)); }
/// <summary> /// Return an IdentifierValue for the specified unsaved-value. If none is specified, /// guess the unsaved value by instantiating a test instance of the class and /// reading it's id property, or if that is not possible, using the java default /// value for the type /// </summary> public static IdentifierValue GetUnsavedIdentifierValue( string unsavedValue, IGetter identifierGetter, IType identifierType, ConstructorInfo constructor) { if (unsavedValue == null) { if (identifierGetter != null && constructor != null) { // use the id value of a newly instantiated instance as the unsaved-value object defaultValue = identifierGetter.Get(Instantiate(constructor)); return new IdentifierValue(defaultValue); } var idTypeAsPrimitiveType = identifierType as PrimitiveType; if (identifierGetter != null && idTypeAsPrimitiveType != null) { object defaultValue = idTypeAsPrimitiveType.DefaultValue; return new IdentifierValue(defaultValue); } return IdentifierValue.SaveNull; } if ("null" == unsavedValue) { return IdentifierValue.SaveNull; } if ("undefined" == unsavedValue) { return IdentifierValue.Undefined; } if ("none" == unsavedValue) { return IdentifierValue.SaveNone; } if ("any" == unsavedValue) { return IdentifierValue.SaveAny; } try { return new IdentifierValue(((IIdentifierType) identifierType).StringToObject(unsavedValue)); } catch (InvalidCastException cce) { throw new MappingException("Bad identifier type: " + identifierType.Name, cce); } catch (Exception e) { throw new MappingException("Could not parse identifier unsaved-value: " + unsavedValue, e); } }
public ComponentType(System.Type componentClass, string[] propertyNames, IGetter[] propertyGetters, ISetter[] propertySetters, // currently not used, see the comment near the end of the method body bool foundCustomAcessor, IType[] propertyTypes, bool[] nullabilities, FetchMode[] joinedFetch, Cascades.CascadeStyle[] cascade, string parentProperty) { this.componentClass = componentClass; this.propertyTypes = propertyTypes; this.propertyNullability = nullabilities; propertySpan = propertyNames.Length; getters = propertyGetters; setters = propertySetters; string[] getterNames = new string[propertySpan]; string[] setterNames = new string[propertySpan]; System.Type[] propTypes = new System.Type[propertySpan]; for (int i = 0; i < propertySpan; i++) { getterNames[i] = getters[i].PropertyName; setterNames[i] = setters[i].PropertyName; propTypes[i] = getters[i].ReturnType; } if (parentProperty == null) { parentSetter = null; parentGetter = null; } else { IPropertyAccessor pa = PropertyAccessorFactory.GetPropertyAccessor(null); parentSetter = pa.GetSetter(componentClass, parentProperty); parentGetter = pa.GetGetter(componentClass, parentProperty); } this.propertyNames = propertyNames; this.cascade = cascade; this.joinedFetch = joinedFetch; if (Environment.UseReflectionOptimizer) { // NH: reflection optimizer works with custom accessors this.optimizer = Environment.BytecodeProvider.GetReflectionOptimizer(componentClass, getters, setters); } }
/// <summary> /// Class constructor. /// </summary> public ReflectionOptimizer(System.Type mappedType, IGetter[] getters, ISetter[] setters) { // save off references this.mappedType = mappedType; typeOfThis = mappedType.IsValueType ? mappedType.MakeByRefType() : mappedType; //this.getters = getters; //this.setters = setters; GetPropertyValuesInvoker getInvoker = GenerateGetPropertyValuesMethod(getters); SetPropertyValuesInvoker setInvoker = GenerateSetPropertyValuesMethod(getters, setters); accessOptimizer = new AccessOptimizer(getInvoker, setInvoker, getters, setters); createInstanceMethod = CreateCreateInstanceMethod(mappedType); }
protected internal override IProxyFactory BuildProxyFactory(PersistentClass mappingInfo, IGetter idGetter, ISetter idSetter) { IProxyFactory pf = new MapProxyFactory(); try { //TODO: design new lifecycle for ProxyFactory pf.PostInstantiate(EntityName, null, null, null, null, null); } catch (HibernateException he) { log.Warn("could not create proxy factory for:" + EntityName, he); pf = null; } return pf; }
/// <summary> /// /// </summary> /// <param name="property"></param> /// <param name="getter"></param> /// <param name="setter"></param> public PropertyAction(PropertyInfo property, IGetter getter, ISetter setter) { if (property == null) throw new PropertyAccessorException("The propertyInfo for the current PropertyAction cannot be null."); if (getter == null && setter == null) throw new PropertyAccessorException(string.Format("The current PropertyAction doesn't have no accessor, property name: {0} - declaring type: {1}", property.Name, property.DeclaringType == null ? string.Empty : property.DeclaringType.FullName)); if (getter != null && setter != null) this.accessType = AccessType.ReadWrite; else this.accessType = getter != null ? AccessType.Read : AccessType.Write; this.property = property; this.getter = getter; this.setter = setter; }
/// <summary> /// Generates a dynamic method on the given type. /// </summary> private GetPropertyValuesInvoker GenerateGetPropertyValuesMethod(IGetter[] getters) { System.Type[] methodArguments = new System.Type[] { typeof(object), typeof(GetterCallback) }; DynamicMethod method = CreateDynamicMethod(typeof(object[]), methodArguments); ILGenerator il = method.GetILGenerator(); LocalBuilder thisLocal = il.DeclareLocal(typeOfThis); LocalBuilder dataLocal = il.DeclareLocal(typeof(object[])); // Cast the 'this' pointer to the appropriate type and store it in a local variable il.Emit(OpCodes.Ldarg_0); EmitCastToReference(il, mappedType); il.Emit(OpCodes.Stloc, thisLocal); // Allocate the values array and store it in a local variable il.Emit(OpCodes.Ldc_I4, getters.Length); il.Emit(OpCodes.Newarr, typeof(object)); il.Emit(OpCodes.Stloc, dataLocal); //get all the data from the object into the data array to be returned for (int i = 0; i < getters.Length; i++) { // get the member accessors IGetter getter = getters[i]; // queue up the array storage location for the value il.Emit(OpCodes.Ldloc, dataLocal); il.Emit(OpCodes.Ldc_I4, i); // get the value... IOptimizableGetter optimizableGetter = getter as IOptimizableGetter; if (optimizableGetter != null) { // using the getter's emitted IL code il.Emit(OpCodes.Ldloc, thisLocal); optimizableGetter.Emit(il); EmitUtil.EmitBoxIfNeeded(il, getter.ReturnType); } else { // using the getter itself via a callback MethodInfo invokeMethod = typeof(GetterCallback).GetMethod( "Invoke", new System.Type[] { typeof(object), typeof(int) }); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldc_I4, i); il.Emit(OpCodes.Callvirt, invokeMethod); } //store the value il.Emit(OpCodes.Stelem_Ref); } // Return the data array il.Emit(OpCodes.Ldloc, dataLocal.LocalIndex); il.Emit(OpCodes.Ret); return (GetPropertyValuesInvoker)method.CreateDelegate(typeof(GetPropertyValuesInvoker)); }
/// <summary> /// Generate the IReflectionOptimizer object /// </summary> /// <param name="mappedClass">The target class</param> /// <param name="setters">Array of setters</param> /// <param name="getters">Array of getters</param> /// <returns><see langword="null" /> if the generation fails</returns> public IReflectionOptimizer GetReflectionOptimizer( System.Type mappedClass, IGetter[] getters, ISetter[] setters) { return new ReflectionOptimizer(mappedClass, getters, setters); }
protected virtual IProxyFactory BuildProxyFactoryInternal(PersistentClass @class, IGetter getter, ISetter setter) { return Cfg.Environment.BytecodeProvider.ProxyFactoryFactory.BuildProxyFactory(); }
IReflectionOptimizer IBytecodeProvider.GetReflectionOptimizer( System.Type clazz, IGetter[] getters, ISetter[] setters ) { return new ReflectionOptimizer( kernel, clazz, getters, setters ); }
protected override IProxyFactory BuildProxyFactory(PersistentClass persistentClass, IGetter idGetter, ISetter idSetter) { bool needAccesorCheck = true; // NH specific (look the comment below) // determine the id getter and setter methods from the proxy interface (if any) // determine all interfaces needed by the resulting proxy var proxyInterfaces = new HashedSet<System.Type> {typeof (INHibernateProxy)}; System.Type _mappedClass = persistentClass.MappedClass; System.Type _proxyInterface = persistentClass.ProxyInterface; if (_proxyInterface != null && !_mappedClass.Equals(_proxyInterface)) { if (!_proxyInterface.IsInterface) { throw new MappingException("proxy must be either an interface, or the class itself: " + EntityName); } needAccesorCheck = false; // NH (the proxy is an interface all properties can be overridden) proxyInterfaces.Add(_proxyInterface); } if (_mappedClass.IsInterface) { needAccesorCheck = false; // NH (the mapped class is an interface all properties can be overridden) proxyInterfaces.Add(_mappedClass); } foreach (Subclass subclass in persistentClass.SubclassIterator) { System.Type subclassProxy = subclass.ProxyInterface; System.Type subclassClass = subclass.MappedClass; if (subclassProxy != null && !subclassClass.Equals(subclassProxy)) { if (!subclassProxy.IsInterface) { throw new MappingException("proxy must be either an interface, or the class itself: " + subclass.EntityName); } proxyInterfaces.Add(subclassProxy); } } /* * NH Different Implementation (for Error logging): * - Check if the logger is enabled * - Don't need nothing to check if the mapped-class or proxy is an interface */ if (log.IsErrorEnabled && needAccesorCheck) { LogPropertyAccessorsErrors(persistentClass); } /**********************************************************/ MethodInfo idGetterMethod = idGetter == null ? null : idGetter.Method; MethodInfo idSetterMethod = idSetter == null ? null : idSetter.Method; MethodInfo proxyGetIdentifierMethod = idGetterMethod == null || _proxyInterface == null ? null : ReflectHelper.TryGetMethod(_proxyInterface, idGetterMethod); MethodInfo proxySetIdentifierMethod = idSetterMethod == null || _proxyInterface == null ? null : ReflectHelper.TryGetMethod(_proxyInterface, idSetterMethod); IProxyFactory pf = BuildProxyFactoryInternal(persistentClass, idGetter, idSetter); try { pf.PostInstantiate(EntityName, _mappedClass, proxyInterfaces, proxyGetIdentifierMethod, proxySetIdentifierMethod, persistentClass.HasEmbeddedIdentifier ? (IAbstractComponentType) persistentClass.Identifier.Type: null); } catch (HibernateException he) { log.Warn("could not create proxy factory for:" + EntityName, he); pf = null; } return pf; }
internal ReflectionOptimizer (System.Type mappedType, IGetter[] getters, ISetter[] setters) : base(mappedType, getters, setters) { }
/// <summary> /// Initializes a new instance of the <see cref="AutofacReflectionOptimizer"/> class. /// </summary> /// <param name="container">The container.</param> /// <param name="mappedType">The type being mapped.</param> /// <param name="getters">The getters.</param> /// <param name="setters">The setters.</param> public AutofacReflectionOptimizer(IComponentContext container, Type mappedType, IGetter[] getters, ISetter[] setters) : base(mappedType, getters, setters) { _container = container; }
/// <summary> /// Retrieve the <see cref="IReflectionOptimizer" /> delegate for this provider /// capable of generating reflection optimization components. /// </summary> /// <param name="clazz">The class to be reflected upon.</param> /// <param name="getters">All property getters to be accessed via reflection.</param> /// <param name="setters">All property setters to be accessed via reflection.</param> /// <returns> /// The reflection optimization delegate. /// </returns> public IReflectionOptimizer GetReflectionOptimizer(Type clazz, IGetter[] getters, ISetter[] setters) { return new AutofacReflectionOptimizer(_container, clazz, getters, setters); }
/// <summary> /// Return an IdentifierValue for the specified unsaved-value. If none is specified, /// guess the unsaved value by instantiating a test instance of the class and /// reading it's id property, or if that is not possible, using the java default /// value for the type /// </summary> public static Cascades.IdentifierValue GetUnsavedIdentifierValue( string unsavedValue, IGetter identifierGetter, IType identifierType, ConstructorInfo constructor ) { if( unsavedValue == null ) { if( identifierGetter != null && constructor != null ) { // use the id value of a newly instantiated instance as the unsaved-value object defaultValue = identifierGetter.Get( Instantiate( constructor ) ); return new Cascades.IdentifierValue( defaultValue ); } // TODO: NH - the branch below is actually never visited, so it's commented out /* else if( identifierGetter != null && ( identifierType is ValueTypeType ) ) { object defaultValue = ( ( ValueTypeType ) identifierType ).DefaultValue; return new Cascades.IdentifierValue( defaultValue ); } */ else { return Cascades.IdentifierValue.SaveNull; } } else if( "null" == unsavedValue ) { return Cascades.IdentifierValue.SaveNull; } // TODO: H3 only, IdentifierValue.IsUnsaved may return true/false/null in H3 // and SaveUndefined always returns null. /* else if( "undefined" == unsavedValue ) { return Cascades.IdentifierValue.SaveUndefined; } */ else if( "none" == unsavedValue ) { return Cascades.IdentifierValue.SaveNone; } else if( "any" == unsavedValue ) { return Cascades.IdentifierValue.SaveAny; } else { try { return new Cascades.IdentifierValue( ( ( IIdentifierType ) identifierType ).StringToObject( unsavedValue ) ); } catch( InvalidCastException cce ) { throw new MappingException( "Bad identifier type: " + identifierType.Name, cce ); } catch( Exception e ) { throw new MappingException( "Could not parse identifier unsaved-value: " + unsavedValue, e ); } } }
/// <summary> /// Generates a dynamic method on the given type. /// </summary> /// <returns></returns> private SetPropertyValuesInvoker GenerateSetPropertyValuesMethod(IGetter[] getters, ISetter[] setters) { System.Type[] methodArguments = new System.Type[] { typeof(object), typeof(object[]), typeof(SetterCallback) }; DynamicMethod method = CreateDynamicMethod(null, methodArguments); ILGenerator il = method.GetILGenerator(); // Declare a local variable used to store the object reference (typed) LocalBuilder thisLocal = il.DeclareLocal(typeOfThis); il.Emit(OpCodes.Ldarg_0); EmitCastToReference(il, mappedType); il.Emit(OpCodes.Stloc, thisLocal.LocalIndex); for (int i = 0; i < setters.Length; i++) { // get the member accessor ISetter setter = setters[i]; System.Type valueType = getters[i].ReturnType; IOptimizableSetter optimizableSetter = setter as IOptimizableSetter; if (optimizableSetter != null) { // load 'this' il.Emit(OpCodes.Ldloc, thisLocal); // load the value from the data array il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Ldc_I4, i); il.Emit(OpCodes.Ldelem_Ref); EmitUtil.PreparePropertyForSet(il, valueType); // using the setter's emitted IL optimizableSetter.Emit(il); } else { // using the setter itself via a callback MethodInfo invokeMethod = typeof(SetterCallback).GetMethod( "Invoke", new System.Type[] { typeof(object), typeof(int), typeof(object) }); il.Emit(OpCodes.Ldarg_2); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldc_I4, i); // load the value from the data array il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Ldc_I4, i); il.Emit(OpCodes.Ldelem_Ref); il.Emit(OpCodes.Callvirt, invokeMethod); } } // Setup the return il.Emit(OpCodes.Ret); return (SetPropertyValuesInvoker)method.CreateDelegate(typeof(SetPropertyValuesInvoker)); }
public static void BindComponent( XmlNode node, Component model, System.Type reflectedClass, string className, string path, bool isNullable, Mappings mappings ) { XmlAttribute classNode = node.Attributes[ "class" ]; if( "dynamic-component".Equals( node.Name ) ) { model.IsEmbedded = false; model.IsDynamic = true; } else if( classNode != null ) { model.ComponentClass = ClassForNameChecked( classNode.Value, mappings, "component class not found: {0}" ); model.IsEmbedded = false; } else if( reflectedClass != null ) { model.ComponentClass = reflectedClass; model.IsEmbedded = false; } else { // an "embedded" component (ids only) model.ComponentClass = model.Owner.MappedClass; model.IsEmbedded = true; } foreach( XmlNode subnode in node.ChildNodes ) { //I am only concerned with elements that are from the nhibernate namespace if( subnode.NamespaceURI != Configuration.MappingSchemaXMLNS ) { continue; } string name = subnode.LocalName; //.Name; string propertyName = GetPropertyName( subnode ); string subpath = propertyName == null ? null : StringHelper.Qualify( path, propertyName ); CollectionType collectType = CollectionType.CollectionTypeFromString( name ); IValue value = null; if( collectType != null ) { Mapping.Collection collection = collectType.Create( subnode, className, subpath, model.Owner, mappings ); mappings.AddCollection( collection ); value = collection; } else if( "many-to-one".Equals( name ) || "key-many-to-one".Equals( name ) ) { value = new ManyToOne( model.Table ); BindManyToOne( subnode, ( ManyToOne ) value, subpath, isNullable, mappings ); } else if( "one-to-one".Equals( name ) ) { value = new OneToOne( model.Table, model.Owner.Identifier ); BindOneToOne( subnode, ( OneToOne ) value, isNullable, mappings ); } else if( "any".Equals( name ) ) { value = new Any( model.Table ); BindAny( subnode, ( Any ) value, isNullable, mappings ); } else if( "property".Equals( name ) || "key-property".Equals( name ) ) { value = new SimpleValue( model.Table ); BindSimpleValue( subnode, ( SimpleValue ) value, isNullable, subpath, mappings ); } else if( "component".Equals( name ) || "dynamic-component".Equals( name ) || "nested-composite-element".Equals( name ) ) { System.Type subreflectedClass = model.ComponentClass == null ? null : GetPropertyType( subnode, mappings, model.ComponentClass, propertyName ); value = ( model.Owner != null ) ? new Component( model.Owner ) : // a class component new Component( model.Table ); // a composite element BindComponent( subnode, ( Component ) value, subreflectedClass, className, subpath, isNullable, mappings ); } else if( "parent".Equals( name ) ) { model.ParentProperty = propertyName; } if( value != null ) { model.AddProperty( CreateProperty( value, propertyName, model.ComponentClass, subnode, mappings ) ); } } int span = model.PropertySpan; string[ ] names = new string[span]; IType[ ] types = new IType[span]; Cascades.CascadeStyle[ ] cascade = new Cascades.CascadeStyle[span]; OuterJoinFetchStrategy[ ] joinedFetch = new OuterJoinFetchStrategy[span]; int i = 0; foreach( Mapping.Property prop in model.PropertyCollection ) { if( prop.IsFormula ) { throw new MappingException( "properties of components may not be formulas: " + prop.Name ); } if( !prop.IsInsertable || !prop.IsUpdateable ) { throw new MappingException( "insert=\"false\", update=\"false\" not supported for properties of components: " + prop.Name ); } names[ i ] = prop.Name; types[ i ] = prop.Type; cascade[ i ] = prop.CascadeStyle; joinedFetch[ i ] = prop.Value.OuterJoinFetchSetting; i++; } IType componentType; if( model.IsDynamic ) { componentType = new DynamicComponentType( names, types, joinedFetch, cascade ); } else { IGetter[ ] getters = new IGetter[span]; ISetter[ ] setters = new ISetter[span]; bool foundCustomAccessor = false; i = 0; foreach( Mapping.Property prop in model.PropertyCollection ) { setters[ i ] = prop.GetSetter( model.ComponentClass ); getters[ i ] = prop.GetGetter( model.ComponentClass ); if( !prop.IsBasicPropertyAccessor ) { foundCustomAccessor = true; } i++; } componentType = new ComponentType( model.ComponentClass, names, getters, setters, foundCustomAccessor, types, joinedFetch, cascade, model.ParentProperty ); } model.Type = componentType; }