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); } }
/// <summary> /// Generates a dynamic method on the given type. /// </summary> /// <returns></returns> private SetPropertyValuesInvoker GenerateSetPropertyValuesMethod(IGetter[] getters, ISetter[] setters) { var methodArguments = new[] { 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; var 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[] { 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 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(); }
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; 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 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 override Func <PropertyInfo, Delegate> Call <TObj, TValue>() { ClassVisitor <DeserializeContext, TValue> elementVisitor = visitorFactory.GetClassVisitor <TValue>(); return(property => { ISetter <TObj, IList <TValue> > setter = Setter.Create <TObj, IList <TValue> >(property); return new ProcessField <DeserializeContext, TObj, IList <TValue> >( (DeserializeContext context, TObj obj, ref IList <TValue> value) => { value = new List <TValue>(); setter.Apply(obj, value); int length = PrimitiveDeserializer.Impl <int> .Instance(context.Stream); for (int i = 0; i < length; i++) { TValue element = new TValue(); if (elementVisitor.Visit(context, element) == VisitStatus.Exit) { return VisitStatus.Exit; } value.Add(element); } return VisitStatus.SkipChildren; }); }); }
/// <param name="destination">To output filecontents to</param> /// <param name="ffiles"> /// Filepath factory that creates filenames out of filestrings. /// Usualy is a part of Program.Core. Otherwise pass new TEO.General.FactoryFiles() /// </param> public static IFactory <Input, IBatchable> Factory(ISetter <string> destination, IFactory <string> ffiles) { return(new factory(destination) { FFiles = ffiles }); }
/// <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; }
private static Expression GetSetExpression( ISetter <T> setter, Type fieldType) { return((Expression)_getSetExpressionHelper .MakeGenericMethod(new[] { fieldType }) .Invoke(null, new object[] { setter })); }
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); }
static void Main() { ISetter setter = Setter.Create(typeof(Foo), "Bar"); Foo foo = new Foo(); setter.SetValue(foo, "abc"); string s = foo.ToString(); // prove working }
/// <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()); }
/// <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; }
/// <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 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; }
void ISetterValue.Initialize(ISetter setter) { // ContextMenu can be assigned to the ContextMenu property in a setter. This overrides // the behavior defined in Control which requires controls to be wrapped in a <template>. if (!(setter is Setter s && s.Property == ContextMenuProperty)) { throw new InvalidOperationException( "Cannot use a control as a Setter value. Wrap the control in a <Template>."); } }
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 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 DefaultRevisionInfoGenerator(string revisionInfoEntityName, System.Type revisionInfoType, IRevisionListener revisionListener, PropertyData revisionInfoTimestampData, bool timestampAsDate) { _revisionInfoEntityName = revisionInfoEntityName; _revisionInfoType = revisionInfoType; _timestampAsDate = timestampAsDate; _revisionTimestampSetter = ReflectionTools.GetSetter(revisionInfoType, revisionInfoTimestampData); _listener = revisionListener; }
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, null, null)); }
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)); }
public static void BuildTest() { ICounter <int, int> c1 = null; ICounter <int> c2 = null; ICriterionMatcher <int> cm1 = null; IFactory <int> f1 = null; IProperties <int, int, int> p1 = null; IProperty <int, int> p2 = null; IProvider <int, int> p3 = null; IProvider <int> p4 = null; ISetter <int, int> s1 = null; ISetter <int> s2 = null; }
protected override Func <PropertyInfo, Delegate> Call <TObj, TValue>() { return(property => { ISetter <TObj, TValue> setter = Setter.Create <TObj, TValue>(property); return new ProcessField <DeserializeContext, TObj, TValue>( (DeserializeContext context, TObj obj, ref TValue value) => { value = new TValue(); setter.Apply(obj, value); return VisitStatus.Continue; }); }); }
/// <summary> /// Retrieve the <see cref="IReflectionOptimizer" /> delegate for this provider /// capable of generating reflection optimization components. /// </summary> /// <param name="bytecodeProvider">The bytecode provider.</param> /// <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> /// <param name="specializedGetter">The specialized getter for the given type.</param> /// <param name="specializedSetter">The specialized setter for the given type.</param> /// <returns>The reflection optimization delegate.</returns> //6.0 TODO: Merge into IBytecodeProvider. public static IReflectionOptimizer GetReflectionOptimizer( this IBytecodeProvider bytecodeProvider, System.Type clazz, IGetter[] getters, ISetter[] setters, IGetter specializedGetter, ISetter specializedSetter) { if (bytecodeProvider is BytecodeProviderImpl bytecodeProviderImpl) { return(bytecodeProviderImpl.GetReflectionOptimizer(clazz, getters, setters, specializedGetter, specializedSetter)); } #pragma warning disable 618 return(bytecodeProvider.GetReflectionOptimizer(clazz, getters, setters)); #pragma warning restore 618 }
protected override Func <PropertyInfo, Delegate> Call <TObj, TPrimitive>() { return(property => { ISetter <TObj, TPrimitive> setter = Setter.Create <TObj, TPrimitive>(property); return new ProcessField <DeserializeContext, TObj, TPrimitive>( (DeserializeContext context, TObj obj, ref TPrimitive value) => { value = Impl <TPrimitive> .Instance(context.Stream); setter.Apply(obj, value); return VisitStatus.SkipChildren; }); }); }
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); }
public override void Inject <C>(ISpanContext spanContext, C carrier, ISetter <C> setter) { if (spanContext == null) { throw new ArgumentNullException(nameof(spanContext)); } if (carrier == null) { throw new ArgumentNullException(nameof(carrier)); } if (setter == null) { throw new ArgumentNullException(nameof(setter)); } }
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="componentClass"></param> /// <param name="propertyNames"></param> /// <param name="propertyGetters"></param> /// <param name="propertySetters"></param> /// <param name="foundCustomAcessor"></param> /// <param name="propertyTypes"></param> /// <param name="joinedFetch"></param> /// <param name="cascade"></param> /// <param name="parentProperty"></param> 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, OuterJoinFetchStrategy[] joinedFetch, Cascades.CascadeStyle[] cascade, string parentProperty) { this.componentClass = componentClass; this.propertyTypes = propertyTypes; 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; // NH: reflection optimizer works with custom accessors if (/*!foundCustomAcessor &&*/ Cfg.Environment.UseReflectionOptimizer) { this.getset = GetSetHelperFactory.Create(componentClass, setters, getters); } }
protected override Func <PropertyInfo, Delegate> Call <TObj>() { return(property => { ISetter <TObj, string> setter = Setter.Create <TObj, string>(property); return new ProcessField <DeserializeContext, TObj, string>( (DeserializeContext context, TObj obj, ref string value) => { int length = PrimitiveDeserializer.Impl <int> .Instance(context.Stream); byte[] bytes = new byte[length]; context.Stream.Read(bytes, 0, length); value = Marshallers <string> .Instance.FromBytes(bytes); setter.Apply(obj, value); return VisitStatus.SkipChildren; }); }); }
protected 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); }
protected override void OnSelectedPropertyChanged() { base.OnSelectedPropertyChanged(); if (this.Model.DummyObject == null || this.TargetType == null) { this.ValueSetter?.Dispose(); this.ValueSetter = null; return; } if (this.SelectedProperty == null) { return; } var pi = TargetType.GetProperty(SelectedProperty.Name); var attr = pi.GetAttribute <DesignElementAttribute>(); this.ValueSetter?.Dispose(); if (string.IsNullOrEmpty(attr.Key)) { this.ValueSetter = SetterManager.CreateSetter(this.Model.DummyObject, pi); } else { this.ValueSetter = SetterManager.CreateSetter(this.Model.DummyObject, pi, attr.Key); } if (this.ValueSetter != null) { (this.ValueSetter as FrameworkElement).Width = 150; if (this.ValueSetter is ValueBoxSetter vBoxSetter) { vBoxSetter.Foreground = Brushes.Black; vBoxSetter.Background = Brushes.Transparent; } BindingHelper.SetBinding( this.ValueSetter as BaseSetter, BaseSetter.ValueProperty, this.Model.ValueBinder, PBinder.DirectValueProperty); } }
public DeepSetter(ISetter inheritSetter, T entity, string propertyName) { _inheritSetter = inheritSetter; _entity = entity; _type = _entity.GetType(); var algorithm = _type.GetCustomAttributes(typeof(AlgorithmAttribute), false).Cast <AlgorithmAttribute>().First().Algorithm; var dependencyOf = _type.GetProperty(propertyName).GetCustomAttributes(typeof(ModifyStrategyAttribute), false).Cast <ModifyStrategyAttribute>().First(); _method = algorithm.GetMethod(dependencyOf.Method); _dependencProperty = _type.GetProperties().Where(p => dependencyOf.Parameters.Contains(p.Name)); _setter = new Setter <T>(entity, propertyName); }
/// <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; }
protected override Func <PropertyInfo, Delegate> Call <TObj, TStruct>() { int size = Unsafe.SizeOf <TStruct>(); return(property => { ISetter <TObj, TStruct> setter = Setter.Create <TObj, TStruct>(property); return new ProcessField <DeserializeContext, TObj, TStruct>( (DeserializeContext context, TObj obj, ref TStruct value) => { byte[] bytes = new byte[size]; context.Stream.Read(bytes, 0, size); value = Marshallers <TStruct> .Instance.FromBytes(bytes); setter.Apply(obj, value); return VisitStatus.SkipChildren; }); }); }
public void CompanyElementGeneration() { ISetter idSetter = PropertyAccessorFactory.GetPropertyAccessor(GenerateIdProperty(), EntityMode.Xml).GetSetter(null, null); ISetter nameSetter = PropertyAccessorFactory.GetPropertyAccessor(GenerateNameProperty(), EntityMode.Xml).GetSetter(null, null); ISetter textSetter = PropertyAccessorFactory.GetPropertyAccessor(GenerateTextProperty(), EntityMode.Xml).GetSetter(null, null); ISetter accountIdSetter = PropertyAccessorFactory.GetPropertyAccessor(GenerateAccountIdProperty(), EntityMode.Xml).GetSetter(null, null); XmlNode root = GenerateRootTestElement(); idSetter.Set(root, 123L); textSetter.Set(root, "description..."); nameSetter.Set(root, "NHForge"); accountIdSetter.Set(root, 456L); Console.WriteLine(dom.OuterXml); //Assert.That(new NodeComparator().Compare(dom, root) == 0); }
public override void Inject <C>(ISpanContext spanContext, C carrier, ISetter <C> setter) { if (spanContext == null) { throw new ArgumentNullException(nameof(spanContext)); } if (carrier == null) { throw new ArgumentNullException(nameof(carrier)); } if (setter == null) { throw new ArgumentNullException(nameof(setter)); } setter.Put(carrier, X_B3_TRACE_ID, spanContext.TraceId.ToLowerBase16()); setter.Put(carrier, X_B3_SPAN_ID, spanContext.SpanId.ToLowerBase16()); if (spanContext.TraceOptions.IsSampled) { setter.Put(carrier, X_B3_SAMPLED, SAMPLED_VALUE); } }
/// <summary> /// Class constructor. /// </summary> public ReflectionOptimizer( System.Type mappedType, IGetter[] getters, ISetter[] setters, IGetter specializedGetter, ISetter specializedSetter) { // 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(setters); var getMethods = new GetPropertyValueInvoker[getters.Length]; for (var i = 0; i < getters.Length; i++) { getMethods[i] = GenerateGetPropertyValueMethod(getters[i]); } var setMethods = new SetPropertyValueInvoker[setters.Length]; for (var i = 0; i < setters.Length; i++) { setMethods[i] = GenerateSetPropertyValueMethod(setters[i]); } accessOptimizer = new AccessOptimizer( getInvoker, setInvoker, getMethods, setMethods, GenerateGetPropertyValueMethod(specializedGetter), GenerateSetPropertyValueMethod(specializedSetter) ); createInstanceMethod = CreateCreateInstanceMethod(mappedType); }
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; }
private void EmitIL(AssemblyBuilder assemblyBuilder, ModuleBuilder moduleBuilder) { // Create a new type object for the the field accessor class. EmitType(moduleBuilder); // Create a new instance _emittedSetter = assemblyBuilder.CreateInstance("SetFor" + _targetType.FullName + _fieldName) as ISetter; this.nullInternal = this.GetNullInternal(_fieldType); if (_emittedSetter == null) { throw new NotSupportedException( string.Format("Unable to create a set field accessor for '{0}' field on class '{0}'.", _fieldName, _fieldType)); } }
/// <summary> /// ctor /// </summary> /// <param name="mappedClass">The target class</param> /// <param name="setters">Array of setters</param> /// <param name="getters">Array of getters</param> public Generator(System.Type mappedClass, IGetter[] getters, ISetter[] setters) { this.mappedClass = mappedClass; this.getters = getters; this.setters = setters; }
public override IReflectionOptimizer GetReflectionOptimizer(System.Type clazz, IGetter[] getters, ISetter[] setters) { return null; }
/// <summary> Build an appropriate ProxyFactory for the given mapped entity. </summary> /// <param name="mappingInfo">The mapping information regarding the mapped entity. </param> /// <param name="idGetter">The constructed Getter relating to the entity's id property. </param> /// <param name="idSetter">The constructed Setter relating to the entity's id property. </param> /// <returns> An appropriate ProxyFactory instance. </returns> protected abstract IProxyFactory BuildProxyFactory(PersistentClass mappingInfo, IGetter idGetter, ISetter idSetter);
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; }
/// <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 ); }
/// <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 ReflectionOptimizer(IServiceLocator serviceLocator, Type mappedType, IGetter[] getters, ISetter[] setters) : base(mappedType, getters, setters) { _serviceLocator = serviceLocator; }
///<summary> ///</summary> ///<param name="listableObjectFactory"></param> ///<param name="mappedType"></param> ///<param name="getters"></param> ///<param name="setters"></param> public ReflectionOptimizer(IListableObjectFactory listableObjectFactory, Type mappedType, IGetter[] getters, ISetter[] setters) : base(mappedType, getters, setters) { this.listableObjectFactory = listableObjectFactory; }
/// <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> 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> public 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; instantiator = BuildInstantiator(mappingInfo); if (entityMetamodel.IsLazy) { /* NH Different implementation * When we are using an interface we need to use the interface itself to have * the getter and setter of the identifier to prevent proxy initialization. * The BasicLazyInitializer use method.Equals to recognize the the identifier setter. */ IGetter pidGetter = idGetter; ISetter pidSetter = idSetter; if (mappingInfo.HasIdentifierProperty && mappingInfo.ProxyInterface != null) { pidGetter = mappingInfo.IdentifierProperty.GetGetter(mappingInfo.ProxyInterface); pidSetter = mappingInfo.IdentifierProperty.GetSetter(mappingInfo.ProxyInterface); } proxyFactory = BuildProxyFactory(mappingInfo, pidGetter, pidSetter); /*******************************************************************************/ if (proxyFactory == null) { entityMetamodel.IsLazy = false; } } else { proxyFactory = null; } Mapping.Component mapper = mappingInfo.IdentifierMapper; identifierMapperType = mapper == null ? null : (IAbstractComponentType)mapper.Type; }