public abstract Invoke ( BindingFlags invokeAttr, |
||
invokeAttr | BindingFlags | |
binder | ||
parameters | Object | |
culture | ||
Résultat | Object |
private object GetInstanceByConstructor(ConstructorInfo constructorInfo, TypeConfig config) { ParameterInfo[] constructorParametersInfo = constructorInfo.GetParameters(); object[] constructorParameters = new object[constructorParametersInfo.Length]; object instance = null; var tuple = new Tuple<Type, Type>(config.TargetType, config.AttributeSelector); this.resolvingObjectsRepository.Add(tuple); for (int i = 0; i < constructorParameters.Length; i++) { object parameterValue = this.GetParameterValueFromPropertyInfo(constructorParametersInfo[i], config); if (parameterValue != null) { constructorParameters[i] = parameterValue; } else { Type parameterType = constructorParametersInfo[i].ParameterType; Type colorAttributeType = this.GetColorAtributeFromParameter(constructorParametersInfo[i]); constructorParameters[i] = this.GetInstance(parameterType, colorAttributeType); } } switch (config.Lifecycle) { case Lifecycle.PerRequest: instance = this.resolvedObjectsRepository.ContainsKey(tuple) ? this.resolvedObjectsRepository[tuple] : constructorInfo.Invoke(constructorParameters); break; case Lifecycle.Singleton: if (this.singletonsRepository.ContainsKey(tuple)) { instance = this.singletonsRepository[tuple]; } else { instance = constructorInfo.Invoke(constructorParameters); this.singletonsRepository.Add(tuple, instance); } break; } this.resolvingObjectsRepository.Remove(tuple); if (config.InitializeObjectWith != null) { config.InitializeObjectWith.Invoke(instance); } return instance; }
/// <summary> /// 得到构造函数委托 /// </summary> /// <param name="constructor">构造函数</param> /// <returns>返回构造函数委托</returns> public static ConstructorHandler GetCreator(this System.Reflection.ConstructorInfo constructor) { Guard.NotNull(constructor, "constructor"); ConstructorHandler ctor = constructor.DeclaringType.IsValueType ? (args) => constructor.Invoke(args) : DefaultDynamicMethodFactory.CreateConstructorMethod(constructor); ConstructorHandler handler = args => { if (args == null) { args = new object[constructor.GetParameters().Length]; } try { return(ctor(args)); } catch (TargetInvocationException ex) { throw ex.InnerException; } catch (Exception ex) { throw ex; } }; return(handler); }
public static void AddCustomSize(SizeType sizeType, int width, int height, string baseText) { // Create a new game view size var sizesType = typeof(Editor).Assembly.GetType("UnityEditor.GameViewSize"); var gameviewsizetypeType = typeof(Editor).Assembly.GetType("UnityEditor.GameViewSizeType"); System.Reflection.ConstructorInfo constructor = sizesType.GetConstructor(new System.Type[] { gameviewsizetypeType, typeof(int), typeof(int), typeof(string) }); object customGameViewSize = constructor.Invoke(new object[] { (int)sizeType, width, height, baseText }); // Add it to the view size group object group = GetGroup(); System.Reflection.MethodInfo addCustomSize = group.GetType().GetMethod("AddCustomSize"); addCustomSize.Invoke(group, new object[] { customGameViewSize }); }
public static object newInstance(System.Type t, System.Collections.Generic.IDictionary <System.Type, object> paramArray) { if (t == null) { throw new System.ArgumentNullException("t"); } int num = (paramArray == null) ? 0 : paramArray.Count; System.Type[] array = new System.Type[num]; object[] array2 = new object[num]; if (num > 0) { System.Collections.Generic.IEnumerator <System.Type> enumerator = paramArray.Keys.GetEnumerator(); int num2 = 0; while (enumerator.MoveNext()) { array[num2] = enumerator.Current; array2[num2] = paramArray[array[num2]]; num2++; } } System.Reflection.ConstructorInfo constructor = t.GetConstructor(array); if (constructor == null) { throw new System.Exception(); } return(constructor.Invoke(array2)); }
/// <summary> ///Get Accounting Class /// </summary> /// <param name="ass">accounting schema array</param> /// <param name="dr">result set</param> /// <param name="trxName">trx</param> /// <returns>instance or null</returns> public AccountingInterface GetAccountingInstance(MAcctSchema[] ass, DataRow dr, Trx trxName) { //Class<?> clazz = getAccountingClass(); Type clazz = GetAccountingClass(); if (clazz == null) { return(null); } try { //Constructor<?> constr = clazz.getConstructor(MAcctSchema[].class, ResultSet.class, String.class); System.Reflection.ConstructorInfo constr = clazz.GetConstructor(new Type[] { typeof(MAcctSchema[]), typeof(DataRow), typeof(Trx) }); log.Info(constr.Name + ": Constructor check "); //AccountingInterface retValue = (AccountingInterface)constr.newInstance(ass, rs, trxName); AccountingInterface retValue = (AccountingInterface)constr.Invoke(new object[] { ass, dr, trxName }); log.Info(retValue.ToString() + ": Constructor invoke check "); return(retValue); } catch (Exception e) { log.Warning("Error instanciating " + GetName() + ": - " + e.ToString()); } return(null); }
protected static void CheckAssembly <T>(Assembly assembly, List <T> list, List <object> existing) where T : class { foreach (Type type in assembly.GetTypes()) { if (type.IsAbstract) { continue; } if (typeof(T).IsAssignableFrom(type)) { System.Reflection.ConstructorInfo constructor = type.GetConstructor(new Type[0]); if (constructor != null) { T item = constructor.Invoke(new object[0]) as T; if (item != null) { list.Add(item); if (existing != null) { existing.Add(item); } } } } } }
/// <summary> /// 重写LoadControl,带参数。 /// </summary> private UserControl LoadControl(string UserControlPath, params object[] constructorParameters) { List <Type> constParamTypes = new List <Type>(); foreach (object constParam in constructorParameters) { constParamTypes.Add(constParam.GetType()); } UserControl ctl = Page.LoadControl(UserControlPath) as UserControl; // Find the relevant constructor System.Reflection.ConstructorInfo constructor = ctl.GetType().BaseType.GetConstructor(constParamTypes.ToArray()); //And then call the relevant constructor if (constructor == null) { throw new MemberAccessException("The requested constructor was not found on : " + ctl.GetType().BaseType.ToString()); } else { constructor.Invoke(ctl, constructorParameters); } // Finally return the fully initialized UC return(ctl); }
public object CreateObject(string typeName, object[] arguments) { object createdObject = null; System.Type[] argumentTypes = null; if (arguments == null || arguments.GetLength(0) == 0) { argumentTypes = System.Type.EmptyTypes; } else { argumentTypes = arguments.Select(p => p.GetType()).ToArray(); } System.Type typeToConstruct = Assembly.GetType(typeName); System.Reflection.ConstructorInfo constructorInfoObj = typeToConstruct.GetConstructor(argumentTypes); if (constructorInfoObj == null) { Debug.Assert(false, "DynamicAssembly.CreateObject Failed to get the constructorInfoObject"); } else { createdObject = constructorInfoObj.Invoke(arguments); } Debug.Assert(createdObject != null); return(createdObject); }
public void ReturnCodeExceptions() { Type[] list = { typeof(DISCOVERY_RESULT /*_SocketException*/), typeof(PORT_RETURN_CODE /*_WidcommSocketException*/), typeof(REM_DEV_INFO_RETURN_CODE /*_WidcommSocketException*/), typeof(SdpService.SDP_RETURN_CODE /*_WidcommSocketException*/), }; // Type baseType = typeof(WidcommSocketException); Assembly baseAssm = baseType.Assembly; foreach (Type cur in list) { //Exception ex = (Exception)Activator.CreateInstance(cur, 1, RcValue, Location); string curTypeName = cur.Name; string exTypeName = string.Format(System.Globalization.CultureInfo.InvariantCulture, "InTheHand.Net.Bluetooth.Widcomm.{0}_WidcommSocketException", curTypeName); Type exType = baseAssm.GetType(exTypeName, true); System.Reflection.ConstructorInfo[] ciList = exType.GetConstructors(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); System.Reflection.ConstructorInfo ci = exType.GetConstructor( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(int), cur, typeof(string) }, null); #if !NETCF int rcValue2 = RcValue; #else object rcValue2 = Enum.Parse(cur, RcValue.ToString(), false); #endif Exception ex = (Exception)ci.Invoke(new object[] { 1, rcValue2, Location }); // DoTest(ex, cur, curTypeName); // }//for }
private void TestOneParameterForNull(ConstructorInfo constructor, object[] parameters, int parameterToTest, Type classUnderTest) { // copy parameters to not destroy them var parametersCopy = (object[])parameters.Clone(); parametersCopy[parameterToTest] = null; var catched = false; try { constructor.Invoke(parametersCopy); } catch (TargetInvocationException e) { if (e.InnerException != null && e.InnerException.GetType() == typeof(ArgumentNullException)) catched = true; } if (!catched) _results.Add(new Weakness { Type = classUnderTest, Constructor = constructor, ParameterPosition = parameterToTest + 1 }); }
private static object CoerceObject(object value, Type to) { if (value == null) { return(null); } var result = value; if (typeof(Select).IsAssignableFrom(to)) { var ctorChain = new List <System.Reflection.ConstructorInfo>(); System.Reflection.ConstructorInfo ctor = null; if (STEPListener.TypeHasConstructorForSelectChoice(to, value.GetType(), out ctor, ref ctorChain)) { result = ctor.Invoke(new object[] { value }); if (ctorChain.Any()) { // Construct the necessary wrappers working // backwards. For the first constructor, the parameter // will be the constructed instance. for (var y = ctorChain.Count - 1; y >= 0; y--) { result = ctorChain[y].Invoke(new object[] { result }); } } } } return(result); }
/// <summary> /// Crea una instancia de un Lbl.ElementoDeDatos a partir de un registro de base de datos. /// </summary> public static T Instanciar <T>(Lfx.Data.IConnection dataBase, Lfx.Data.Row row) where T : Lbl.ElementoDeDatos { Type tipo = typeof(T); System.Reflection.ConstructorInfo TConstr = tipo.GetConstructor(new Type[] { typeof(Lfx.Data.Connection), typeof(Lfx.Data.Row) }); return((T)(TConstr.Invoke(new object[] { dataBase, row }))); }
static SingletonFactory() { try { Type type = typeof(Singleton); System.Reflection.ConstructorInfo[] constructorInfoArray = type.GetConstructors(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public); System.Reflection.ConstructorInfo noParameterConstructorInfo = null; foreach (System.Reflection.ConstructorInfo constructorInfo in constructorInfoArray) { System.Reflection.ParameterInfo[] parameterInfoArray = constructorInfo.GetParameters(); if (0 == parameterInfoArray.Length) { noParameterConstructorInfo = constructorInfo; break; } } if (null == noParameterConstructorInfo) { throw new NotSupportedException("No constructor without 0 parameter"); } singleton = (Singleton)noParameterConstructorInfo.Invoke(null); } catch (Exception e) { Console.WriteLine("e=" + e.ToString()); } }
public static IEntity Build(Mobile from, ConstructorInfo ctor, object[] values, string[,] props, PropertyInfo[] realProps, ref bool sendError) { object built = ctor.Invoke(values); if (built != null && realProps != null) { bool hadError = false; for (int i = 0; i < realProps.Length; ++i) { if (realProps[i] == null) continue; string result = Properties.InternalSetValue(from, built, built, realProps[i], props[i, 1], props[i, 1], false); if (result != "Property has been set.") { if (sendError) from.SendMessage(result); hadError = true; } } if (hadError) sendError = false; } return (IEntity)built; }
/// <summary> /// Get a registry key from a pointer. /// </summary> /// <param name="hKey">Pointer to the registry key</param> /// <param name="writable">Whether or not the key is writable.</param> /// <param name="ownsHandle">Whether or not we own the handle.</param> /// <returns>Registry key pointed to by the given pointer.</returns> private static RegistryKey _pointerToRegistryKey(IntPtr hKey, bool writable, bool ownsHandle) { //Get the BindingFlags for private contructors System.Reflection.BindingFlags privateConstructors = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; //Get the Type for the SafeRegistryHandle Type safeRegistryHandleType = typeof(Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid).Assembly.GetType("Microsoft.Win32.SafeHandles.SafeRegistryHandle"); //Get the array of types matching the args of the ctor we want Type[] safeRegistryHandleCtorTypes = new Type[] { typeof(IntPtr), typeof(bool) }; //Get the constructorinfo for our object System.Reflection.ConstructorInfo safeRegistryHandleCtorInfo = safeRegistryHandleType.GetConstructor( privateConstructors, null, safeRegistryHandleCtorTypes, null); //Invoke the constructor, getting us a SafeRegistryHandle Object safeHandle = safeRegistryHandleCtorInfo.Invoke(new Object[] { hKey, ownsHandle }); //Get the type of a RegistryKey Type registryKeyType = typeof(RegistryKey); //Get the array of types matching the args of the ctor we want Type[] registryKeyConstructorTypes = new Type[] { safeRegistryHandleType, typeof(bool) }; //Get the constructorinfo for our object System.Reflection.ConstructorInfo registryKeyCtorInfo = registryKeyType.GetConstructor( privateConstructors, null, registryKeyConstructorTypes, null); //Invoke the constructor, getting us a RegistryKey RegistryKey resultKey = (RegistryKey)registryKeyCtorInfo.Invoke(new Object[] { safeHandle, writable }); //return the resulting key return(resultKey); }
/// <summary> /// Creates one new blank chunk of the corresponding type, according to factoryMap (PngChunkUNKNOWN if not known) /// </summary> /// <param name="cid">Chunk Id</param> /// <param name="info"></param> /// <returns></returns> internal static PngChunk FactoryFromId(String cid, ImageInfo info) { PngChunk chunk = null; if (factoryMap == null) { initFactory(); } if (isKnown(cid)) { Type t = factoryMap[cid]; if (t == null) { System.Diagnostics.Debug.WriteLine("What?? " + cid); } System.Reflection.ConstructorInfo cons = t.GetTypeInfo().DeclaredConstructors.Single( c => { var p = c.GetParameters(); return(p.Length == 1 && p[0].ParameterType == typeof(ImageInfo)); }); object o = cons.Invoke(new object[] { info }); chunk = (PngChunk)o; } if (chunk == null) { chunk = new PngChunkUNKNOWN(cid, info); } return(chunk); }
public static object ResolveWithDependencies(this IEnumerable<ParameterInfo> parameterInfos, ConstructorInfo constructorInfo, ITypeResolver typeResolver) { var objects = new List<object>(); objects.AddRange(parameterInfos.GetDependencies(typeResolver)); return constructorInfo.Invoke(objects.ToArray()); }
private static void CallPageInjectionConstructor(Control control, ConstructorInfo constructor) { var parameters = from parameter in constructor.GetParameters() let parameterType = parameter.ParameterType select Rest.Configuration.ServiceLocator.GetService(parameterType); constructor.Invoke(control, parameters.ToArray()); }
/// <summary> Used to Convert an RfcLdapMessage object to the appropriate /// LdapExtendedResponse object depending on the operation being performed. /// /// </summary> /// <param name="inResponse"> The LdapExtendedReponse object as returned by the /// extendedOperation method in the LdapConnection object. /// </param> /// <returns> An object of base class LdapExtendedResponse. The actual child /// class of this returned object depends on the operation being /// performed. /// </returns> static public LdapExtendedResponse convertToExtendedResponse(RfcLdapMessage inResponse) { LdapExtendedResponse tempResponse = new LdapExtendedResponse(inResponse); // Get the oid stored in the Extended response System.String inOID = tempResponse.ID; RespExtensionSet regExtResponses = LdapExtendedResponse.RegisteredResponses; try { System.Type extRespClass = regExtResponses.findResponseExtension(inOID); if (extRespClass == null) { return(tempResponse); } System.Type[] argsClass = new System.Type[] { typeof(RfcLdapMessage) }; System.Object[] args = new System.Object[] { inResponse }; System.Exception ex; try { System.Reflection.ConstructorInfo extConstructor = extRespClass.GetConstructor(argsClass); try { System.Object resp = null; resp = extConstructor.Invoke(args); return((LdapExtendedResponse)resp); } catch (System.UnauthorizedAccessException e) { ex = e; } catch (System.Reflection.TargetInvocationException e) { ex = e; } catch (System.Exception e) { // Could not create the ResponseControl object // All possible exceptions are ignored. We fall through // and create a default LdapControl object ex = e; } } catch (System.MethodAccessException e) { // bad class was specified, fall through and return a // default LdapExtendedResponse object ex = e; } } catch (System.FieldAccessException e) { } // If we get here we did not have a registered extendedresponse // for this oid. Return a default LdapExtendedResponse object. return(tempResponse); }
private static Func<KeyValuePair<string, Task<ScenarioResult>>> FromMethodInfo(MethodInfo method, ConstructorInfo constructor) { return () => { var instance = constructor.Invoke(new object[0]); return new KeyValuePair<string, Task<ScenarioResult>>(constructor.DeclaringType.FullName, (Task<ScenarioResult>) method.Invoke(instance, new object[0])); }; }
internal static object ConstructorInfoInvoke(ConstructorInfo ctor, object[] args) { Type declaringType = ctor.DeclaringType; if ((declaringType != null) && (!declaringType.IsVisible || !ctor.IsPublic)) { DemandReflectionAccess(declaringType); } return ctor.Invoke(args); }
private IHasName GetChild(Type childType, string name) { if (childType != null && name != null) { System.Reflection.ConstructorInfo ci = childType.GetConstructor(new Type[] { typeof(string) }); IHasName child = ci.Invoke(new object[] { name }) as IHasName; return(child); } return(null); }
public static void SimpleParseASN1(string publicKey, ref byte[] modulus, ref byte[] exponent) { byte[] publicKey64 = System.Convert.FromBase64String(publicKey); // The ASN1 structure for the public key looks like this: // // SubjectPublicKeyInfo ::= SEQUENCE { // algorithm AlgorithmIdentifier, // publicKey BIT STRING } // // Where the BIT STRING is a SEQUENCE of 2 INTEGERs (the modulus and the exponent) System.Type ASN1 = System.Type.GetType("Mono.Security.ASN1"); System.Reflection.ConstructorInfo Ctor = ASN1.GetConstructor(new System.Type[] { typeof(byte[]) }); System.Reflection.PropertyInfo Value = ASN1.GetProperty("Value"); System.Reflection.PropertyInfo Item = ASN1.GetProperty("Item"); object asn = Ctor.Invoke(new object[] { publicKey64 }); object bits = Item.GetValue(asn, new object[] { 1 }); byte[] value = (byte[])Value.GetValue(bits, null); byte[] seq = new byte[value.Length - 1]; System.Array.Copy(value, 1, seq, 0, value.Length - 1); asn = Ctor.Invoke(new object[] { seq }); object asn0 = Item.GetValue(asn, new object[] { 0 }); object asn1 = Item.GetValue(asn, new object[] { 1 }); modulus = (byte[])Value.GetValue(asn0, null); exponent = (byte[])Value.GetValue(asn1, null); // non-reflected version // Mono.Security.ASN1 asn = new Mono.Security.ASN1(publicKey64); // Mono.Security.ASN1 bits = asn[1]; // byte[] seq = new byte[bits.Length-1]; // System.Array.Copy(bits.Value, 1, seq, 0, bits.Length-1); // asn = new Mono.Security.ASN1(seq); // modulus = asn[0].Value; // exponent = asn[1].Value; }
private static object Instantiate( ConstructorInfo constructor ) { try { return constructor.Invoke( NoParameters ); } catch( Exception e ) { throw new InstantiationException( "could not instantiate test object", e, constructor.DeclaringType ); } }
public static object NewInstance(ConstructorInfo ctor, params object[] args) { try { return ctor.Invoke(args); } catch(Exception e) { throw new Db4oException(e); } }
private static void NewInstance(ExternalPtr ptr, AtomList args) { External instance; Class cl = Internal.pass.klass; // set by native side Internal.extptr = ptr; // Post("CLASS-NEW {0}",cl); try { // TODO: create dynamic delegate for that.... System.Reflection.ConstructorInfo m = cl.extclass.GetConstructor(new Type[1] { typeof(Atom[]) }); if (m != null) { instance = (External)m.Invoke(new object[1] { (Atom[])args }); } else { // search for the argument-less constructor... it must exist, we searched before m = cl.extclass.GetConstructor(System.Type.EmptyTypes); instance = (External)m.Invoke(null); } } catch (Exception exc) { instance = null; PostError(exc.ToString()); } #if DEBUG Internal.extptr.Clear(); #endif Internal.pass.ext = instance; // back to native }
public static object ObjectFromConstructor(ConstructorInfo C) { ParameterInfo[] ps = C.GetParameters(); List<object> o = new List<object>(); for (int i = 0; i < ps.Length; i++) { // if (ps[i].DefaultValue != null) o.Add(ps[i].DefaultValue); else if (ps[i].ParameterType.IsValueType) o.Add(Activator.CreateInstance(ps[i].ParameterType)); else o.Add(ps[i].ParameterType.GetConstructor (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null).Invoke(null)); } return C.Invoke(o.ToArray()); }
public static Parameter CreateParameter(string stat, string event_name, float value, bool class_name_stat = true) { string class_name = (class_name_stat) ? stat : event_name; Type t = Type.GetType(class_name); if (t != null) { System.Reflection.ConstructorInfo ci = t.GetConstructor(new Type[] { typeof(string), typeof(string), typeof(float) }); return(ci.Invoke(new object[] { stat, event_name, value }) as Parameter); } Debug.LogErrorFormat("Class {0} Error", class_name); return(null); }
public void TransitionState(System.Type stateType) { System.Type[] argTypes = { typeof(Entity), typeof(EntityState) }; System.Reflection.ConstructorInfo ci = stateType.GetConstructor(argTypes); // If a constructor accepting an EntityState was found if (ci != null) { System.Object[] args = { this, state }; EntityState newState = (EntityState)ci.Invoke(args); TransitionState(newState); } }
public static object InvokeConstructorWithoutTargetInvocationException(ConstructorInfo constructor, object[] args) { if (constructor == null) throw new ArgumentNullException("constructor"); try { return constructor.Invoke(args); } catch (TargetInvocationException ex) { RethrowWithNoStackTraceLoss(ex.InnerException); throw; } }
public static generate_interface.typ Create_From_Menu(string name, string filename) { System.Type type = Generator_List[name]; System.Type[] param_types = new Type[1]; generate_interface.typ result = null; object[] parameters = new object[1]; param_types[0] = typeof(string); System.Reflection.ConstructorInfo constructor = type.GetConstructor(param_types); parameters[0] = filename; result = constructor.Invoke(parameters) as generate_interface.typ; return(result); }
public override object GetInstance(ConstructorInfo constructor, object[] parameters = null) { var dependencies = constructor.GetParameters(); if (dependencies.Count() == 0) { return Activator.CreateInstance(constructor.DeclaringType); } if (parameters == null || parameters.Count() != dependencies.Count()) { throw new Exception("Incorrect number of parameters to invoke instance."); } return constructor.Invoke(parameters); }
/// <summary> /// This method constructs a language service given the guid found in the /// registry associated with this package. The default implementation assumes /// the guid is registered and uses Type.GetTypeFromCLSID to construct the /// language service. You can override this method if you want to construct /// the language service directly without having to register it as a COM object. /// </summary> /// <returns></returns> public virtual ILanguageService CreateLanguageService(ref Guid guid) { Type type = Type.GetTypeFromCLSID(guid, true); if (type != null) { System.Reflection.ConstructorInfo ci = type.GetConstructor(new Type[0]); if (ci != null) { ILanguageService svc = (ILanguageService)ci.Invoke(new object[0]); return(svc); } } return(null); }
/// <summary>Invokes OnConstruct directly.</summary> public object ConstructInstance(object[] paramSet) { MethodBase resMethod = (OnConstruct as MethodBase); System.Reflection.ConstructorInfo ctr = resMethod as System.Reflection.ConstructorInfo; if (ctr != null) { // Actual constructor call: return(ctr.Invoke(paramSet)); } // Ordinary method: return(resMethod.Invoke(CtrInstance, paramSet)); }
/// <summary> /// Funktion gibt eine Linq To SQL Expression zurück, welche bezüglich der gewählten Spalte /// in der gewählten Richtung sortiert. /// </summary> /// <param name="tab"></param> /// <param name="ViewColName"></param> /// <param name="SortDescending"></param> /// <returns></returns> public IQueryable <TEntity> sort(IQueryable <TEntity> tab, SortColumnDef sc) { Debug.Assert(!string.IsNullOrEmpty(sc.ColName)); Debug.Assert(tab != null); Debug.Assert(tab.Count() > 0); if (sc.ViewType == typeof(TEntityView)) { // Fall: Die Spalte stammt aus der aktuellen View Debug.Assert(typeof(TEntityView).GetProperty(sc.ColName) != null); // Namen der Eigenschaft einer EntityView auf die Eigenschaft eines zugrundeliegenden Entity abbilden string Colname = mapPropertyToColName(typeof(TEntityView), sc.ColName); // Sortieren bezüglich abgeleiteter Spalten in den Views IQueryable <TEntity> tabSorted; if (sortByDerivat(tab, Colname, sc.SortDescending, out tabSorted)) { return(tabSorted); } // Wenn die Spalte keine abgeleitete Spalte ist, dann sortieren nach den tatsächlichen Spalten return(OrderFunc <TEntity>(tab, Colname, sc.SortDescending)); } else { // Fall: Die Spalte stammt aus einer anderen View als der aktuellen System.Reflection.PropertyInfo pinfo = sc.ViewType.GetProperty(_sortColname); Debug.Assert(pinfo != null); // Businessobjekt für andere View erstellen Type[] constuctorArgTypes = Type.EmptyTypes; System.Reflection.ConstructorInfo ctor = GetBoThatInclude(sc.ViewType).GetConstructor(constuctorArgTypes); Debug.Assert(ctor != null); object[] constructorArgs = { }; object boOther = ctor.Invoke(constructorArgs); // sort- Methode des anderen Businessobjekts aufrufen Type[] sortArgTypes = new Type[] { typeof(IQueryable <TEntity>), typeof(SortColumnDef) }; System.Reflection.MethodInfo miSort = GetBoThatInclude(sc.ViewType).GetMethod("sort", sortArgTypes); Debug.Assert(miSort != null, "Die Sortiermethode ist im Business- Objekt nicht enthalten"); object[] sortArgs = { tab, sc }; return(miSort.Invoke(boOther, sortArgs) as IQueryable <TEntity>); } }
/// <summary> /// Gets the value of initialization according to the InitialValueMethod of this provider. /// </summary> /// <param name="bFixedLengthString">Optional bolean flag that indicates if the current array type is fixed length string (original vb6 code) - /// its default value is false, because it will be generated in upgraded code when current array type used to be a fixed length string.</param> /// <param name="iFixedLengthStringSize">Optional integer value that indicates what is the fixed length string size, used in conjunction with previous (bFixedLengthString) parameter.</param> /// <returns>The value of initialization.</returns> public Object GetInitialValue(bool bFixedLengthString = false, int iFixedLengthStringSize = 0) { Initialize(); switch (_initializeMethod) { #if ACTIVEX_COMPONENTSERVER case InitialValueMethod.CsFactory: try { Type factoryType = null; foreach (Type possibleFactory in _elementType.Assembly.GetExportedTypes()) { if (possibleFactory.BaseType.Name == "ComponentServerFactory") { factoryType = possibleFactory; } } if (factoryType != null) { MethodInfo mi = factoryType.GetMethod("CreateInstance", BindingFlags.Static | BindingFlags.Public); MethodInfo miGeneric = mi.MakeGenericMethod(_elementType); return(miGeneric.Invoke(null, new object[] { })); } } catch (Exception ex) { return(new Exception("Error while trying to get initial value for an array", ex)); } break; #endif case InitialValueMethod.String: return(bFixedLengthString ? new string('\0', iFixedLengthStringSize) : string.Empty); case InitialValueMethod.Constructor: return(_constructor.Invoke(_constructorParams)); case InitialValueMethod.ValueType: return(Activator.CreateInstance(_elementType)); case InitialValueMethod.CreateInstanceValueType: return(_method.Invoke(null, new object[] { })); case InitialValueMethod.Null: return(null); } return(null); }
/// <summary> /// Creates a constructor method with no parameters for an object. /// </summary> /// <param name="type">Object type.</param> /// <param name="constructor">Constructor info used to create the function.</param> /// <returns>The object constructor.</returns> public static Constructor CreateConstructor(Type type, ConstructorInfo constructor) { #if UNITY_IOS return () => { return constructor.Invoke(null); }; #else var method = new DynamicMethod(type.Name, type, null, type); ILGenerator generator = method.GetILGenerator(); generator.Emit(OpCodes.Newobj, constructor); generator.Emit(OpCodes.Ret); return (Constructor)method.CreateDelegate(typeof(Constructor)); #endif }
/// <summary> /// Creates a constructor method with parameters for an object of type <typeparamref name="T"/>. /// </summary> /// <param name="type">Object type.</param> /// <param name="constructor">Constructor info used to create the function.</param> /// <returns>The object constructor.</returns> public static ParamsConstructor CreateConstructorWithParams(Type type, ConstructorInfo constructor) { #if UNITY_IOS return (object[] parameters) => { return constructor.Invoke(parameters); }; #else var parameters = constructor.GetParameters(); Type[] parametersTypes = new Type[] { typeof(object[]) }; var method = new DynamicMethod(type.Name, type, parametersTypes, type); ILGenerator generator = method.GetILGenerator(); //Define parameters. for (int paramIndex = 0; paramIndex < parameters.Length; paramIndex++) { generator.Emit(OpCodes.Ldarg_0); //Define parameter position. switch (paramIndex) { case 0: generator.Emit(OpCodes.Ldc_I4_0); break; case 1: generator.Emit(OpCodes.Ldc_I4_1); break; case 2: generator.Emit(OpCodes.Ldc_I4_2); break; case 3: generator.Emit(OpCodes.Ldc_I4_3); break; case 4: generator.Emit(OpCodes.Ldc_I4_4); break; case 5: generator.Emit(OpCodes.Ldc_I4_5); break; case 6: generator.Emit(OpCodes.Ldc_I4_6); break; case 7: generator.Emit(OpCodes.Ldc_I4_7); break; case 8: generator.Emit(OpCodes.Ldc_I4_8); break; default: generator.Emit(OpCodes.Ldc_I4, paramIndex); break; } //Define parameter type. generator.Emit(OpCodes.Ldelem_Ref); Type paramType = parameters[paramIndex].ParameterType; generator.Emit(paramType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, paramType); } generator.Emit(OpCodes.Newobj, constructor); generator.Emit(OpCodes.Ret); return (ParamsConstructor)method.CreateDelegate(typeof(ParamsConstructor)); #endif }
protected int freecount; // # of free objects in pool public MyObjectPool(int size, params System.Object[] args){ pool = new T[size]; indexlookup = new Dictionary<T, int>(); freecount = size; System.Reflection.ConstructorInfo constructorInfo = typeof(T).GetConstructor(Utils.GetTypes(args)); if (constructorInfo == null) { throw new Exception("Could not find constructor with argument types: " + Utils.ListToString(Utils.GetTypes(args))); } for (int i = 0; i < size; i++) { pool[i] = (T)constructorInfo.Invoke(args); indexlookup.Add(pool[i], i); } front = 0; back = size - 1; }
private static List <T> BuscarDesdeDB(string condicion) { string tablaGen = ObtenTabla(); Datos.AccesoDatosMySql ad = new Datos.AccesoDatosMySql(); { List <T> lista = new List <T>(); List <List <object> > filas = ad.SelectOne(DaCampos(true), tablaGen, condicion, ""); if (filas != null) { foreach (var item in filas) { System.Reflection.ConstructorInfo ci = typeof(T).GetConstructor(new Type[] { typeof(List <object>) }); lista.Add((T)ci.Invoke(new object[] { item })); } } return(lista); } }
/// <summary> /// Obtém um 'ComponentContext' do arquivo de descrição. Caso não exista /// será criado um 'DefaultComponetContext'. /// </summary> /// <param name="componentId">O id do componente.</param> /// <returns></returns> /// <exception cref="SCSException">Caso ocorra um erro na construção do /// componentContext</exception> private ComponentContext CreateComponentContext(ComponentId componentId) { XmlNode componentContextNode = xmlComponent.GetElementsByTagName(COMPONENT_CONTEXT_ELEMENT)[0]; if (componentContextNode == null) { logger.Debug("Criando o contexto utilizando a classe 'DefaultComponentContext'"); return(new DefaultComponentContext(componentId)); } XmlNode context = componentContextNode[COMPONENT_CONTEXT_TYPE]; String contextName = context.InnerText; String contextAssembly = context.Attributes[COMPONENT_CONTEXT_ASSEMBLY_ATTRIBUTE].InnerText; String contextTypeName = String.Format("{0}, {1}", contextName, contextAssembly); Type contextType = Type.GetType(contextTypeName); if (contextType == null) { throw new SCSException(String.Format( "Não foi possível encontrar a classe '{0}'", contextTypeName)); } System.Reflection.ConstructorInfo constructor = contextType.GetConstructor(new Type[] { typeof(ComponentId) }); if (constructor == null) { string errorMsg = "Implementação do componentContext deve possuir um construtor com um parâmetro do tipo 'ComponentId'"; throw new SCSException(errorMsg); } ComponentContext component = constructor.Invoke(new Object[] { componentId }) as ComponentContext; if (component == null) { string errorMsg = String.Format( "A classe {0} não é do tipo 'ComponentContext'", contextTypeName); throw new SCSException(errorMsg); } logger.DebugFormat("Contexto criado utilizando a classe '{0}'", contextTypeName); return(component); }
public static void Process_Assembly(Visual_Flow_Form form, System.Reflection.Assembly assembly) { System.Type[] Types = assembly.GetTypes(); int placement = 0; for (int k = 0; k < Types.Length; k++) { if (Types[k].GetInterface(typeof(generate_interface.typ).FullName) != null) { try { object obj; MethodInfo mi = Types[k].GetMethod("Get_Menu_Name"); System.Reflection.ConstructorInfo constructor = Types[k].GetConstructor( System.Type.EmptyTypes); obj = constructor.Invoke(null); string name = mi.Invoke(obj, null) as string; MenuItem menu_item = new MenuItem(name, new EventHandler( form.handle_click)); if (form.menuItemGenerate.MenuItems.Count > 1) { // add this in sorted order to the list // make sure to get rid of the "&", which messes up alpha order while ((placement < form.menuItemGenerate.MenuItems.Count) && (name.Replace("&", "").CompareTo( form.menuItemGenerate.MenuItems[placement].Text.Replace("&", "")) > 0)) { placement++; } } form.menuItemGenerate.MenuItems.Add(placement, menu_item); Generator_List.Add(name, Types[k]); } catch { } } } }
private static object Construct(DomainGenerator domaingenerator, ConstructorInfo constructor, int highestParameterCount) { var parameters = constructor.GetParameters(); var parameterValues = new object[highestParameterCount]; for (int i = 0; i < parameters.Length; i++) { var parmeterChoiceConvention = domaingenerator.choiceConventions.FirstOrDefault(c => c.Type == parameters[i].ParameterType); if (parmeterChoiceConvention != null) { var choice = parmeterChoiceConvention.Possibilities.PickOne(); parameterValues.SetValue(choice, i); continue; } var primitiveGenerator = primitiveGenerators.Get(parameters[i].ParameterType); if (primitiveGenerator != null) { parameterValues.SetValue(primitiveGenerator.RandomAsObject(), i); } } return constructor.Invoke(parameterValues); }
/// <summary> /// Deserializes the object from this stream /// </summary> /// <param name="reader">Input stream</param> /// <param name="readInternal">Optional delegate to create the object</param> public static T ReadRWObject <T>(this BinaryReader reader, BinaryRWObjectExtensions.ReadObjectFully readInternal = null) { if (readInternal == null) { // Try to find a constructor... System.Reflection.ConstructorInfo ctr = typeof(T).GetConstructor(new Type[0]); if (ctr == null) { throw new IOException("Can't read " + typeof(T).Name + " directly!\n"); } else { readInternal = (BinaryReader rdr) => { BinaryRWObject ro = (BinaryRWObject)ctr.Invoke(new object[0]); ro.ReadBinaryData(rdr); return(ro); }; } } return((T)readInternal(reader)); }
static void _cc3100_IPv4AddressChanged(object sender, uint ipAddress) { Type networkChangeListenerType = Type.GetType("Microsoft.SPOT.Net.NetworkInformation.NetworkChange+NetworkChangeListener, Microsoft.SPOT.Net"); if (networkChangeListenerType != null) { // create instance of NetworkChangeListener System.Reflection.ConstructorInfo networkChangeListenerConstructor = networkChangeListenerType.GetConstructor(new Type[] { }); object networkChangeListener = networkChangeListenerConstructor.Invoke(new object[] { }); // now call the ProcessEvent function to create a NetworkEvent class. System.Reflection.MethodInfo processEventMethodType = networkChangeListenerType.GetMethod("ProcessEvent"); object networkEvent = processEventMethodType.Invoke(networkChangeListener, new object[] { (UInt32)(((UInt32)2 /* AddressChanged*/)), (UInt32)0, DateTime.Now }); /* TODO: should this be DateTime.Now or DateTime.UtcNow? */ // and finally call the static NetworkChange.OnNetworkChangeCallback function to raise the event. Type networkChangeType = Type.GetType("Microsoft.SPOT.Net.NetworkInformation.NetworkChange, Microsoft.SPOT.Net"); if (networkChangeType != null) { System.Reflection.MethodInfo onNetworkChangeCallbackMethod = networkChangeType.GetMethod("OnNetworkChangeCallback", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); onNetworkChangeCallbackMethod.Invoke(networkChangeType, new object[] { networkEvent }); } } }
/// <summary> /// Creates a constructor delegate accepting specified arguments /// </summary> /// <param name="type">type to be created</param> /// <param name="args">constructor arguments type list</param> /// <returns>FactoryDelegate or null if constructor not found</returns> /// <remarks> /// Note: use with caution this method will expose private and protected constructors without safety checks. /// </remarks> public static FactoryDelegate GetTypeFactory(ConstructorInfo ctor) { if (ctor == null) { throw new ArgumentNullException("ctor"); } return delegate(object[] args) { return ctor.Invoke(args); }; }
public static BaseCreature Add( ConstructorInfo ct, float X, float Y, float Z, ushort MapId ) { BaseCreature bc = null; bc = (BaseCreature)ct.Invoke( null ); bc.X = X; bc.Y = Y; bc.Z = Z; bc.MapId = MapId; World.allMobiles.Add( bc, true ); return bc; }
private object CreateInstance(ConstructorInfo Constructor) { if (Constructor.IsNull() || MappingManager.IsNull()) return null; List<object> ParameterValues = new List<object>(); Constructor.GetParameters().ForEach<ParameterInfo>(x => ParameterValues.Add(CreateInstance(x))); return Constructor.Invoke(ParameterValues.ToArray()); }
/// Invoke a Factory constructor, supplying any arguments needed by the /// constructor from the current context. private object InvokeConstructor(ConstructorInfo ctor) { ParameterInfo[] pi = ctor.GetParameters(); object[] parms = new object[pi.Length]; var i = 0; foreach(var param in pi) { if(HasObject(param.ParameterType)) { parms[i++] = this[param.ParameterType]; } else { throw new ContextException(string.Format("No object of type {0} " + "can be obtained from the current context", param.ParameterType)); } } return ctor.Invoke(parms); }
/// <summary> /// If all arguments are constant expressions, evaluates <paramref name="constructorInfo"/> and returns created object wrapped in <see cref="ConstantExpression"/>. /// Otherwise, returns an expression that will run this constructor at run-time. /// </summary> public static Expression TryEvalConst(ParseTreeNode root, ConstructorInfo constructorInfo, params Expression[] args) { if (constructorInfo == null) { throw new ArgumentNullException("constructorInfo"); } if (args == null) { throw new ArgumentNullException("args"); } try { foreach (var arg in args) { if (!(arg is ConstantExpression)) { return Expression.New(constructorInfo, args); } } object value; try { value = constructorInfo.Invoke(args.Select(x => ((ConstantExpression) x).Value).ToArray()); } catch (TargetInvocationException e) { if (e.InnerException == null) throw; throw e.InnerException; } return Expression.Constant(value); } catch (InvalidOperationException e) { throw new CompilationException(e.Message, root); } }
public object InvokeConstructor(ConstructorInfo constructor, object[] arguments) { return UnwrapTargetInvocationException(() => constructor.Invoke(arguments)); }
private static Stream InvokeConstructor(ConstructorInfo constructorInfo, object[] args) { try { return (Stream)constructorInfo.Invoke(args); } catch (TargetInvocationException e) { ExceptionDispatchInfo.Capture(e.InnerException).Throw(); Debug.Assert(false, "Unreachable"); return null; } }
private BrailBase FastCreateInstance(Type type, ConstructorInfo constructor, TextWriter output, IEngineContext context, IController controller, IControllerContext controllerContext) { var self = (BrailBase)FormatterServices.GetUninitializedObject(type); constructor.Invoke(self, new object[] { this, output, context, controller, controllerContext }); return self; }
private static object ConvertCsvEntryToObject(string csv, ConstructorInfo ctor, ParameterInfo[] parameters, char sep =',') { string[] s_params = csv.Split(sep); int i; for (i = 0; i < s_params.Length; i++) s_params[i] = s_params[i].Trim(); i = 0; List<object> convertedParams = new List<object>(); int c_i; double c_d; bool c_b; float c_f; try { foreach (ParameterInfo p in parameters) { if (p.ParameterType == typeof(int) && int.TryParse(s_params[i], out c_i)) convertedParams.Add(c_i); else if (p.ParameterType == typeof(double) && double.TryParse(s_params[i], NumberStyles.Float, ifp, out c_d)) convertedParams.Add(c_d); else if (p.ParameterType == typeof(float) && float.TryParse(s_params[i], NumberStyles.Float, ifp, out c_f)) convertedParams.Add(c_f); else if (p.ParameterType == typeof(bool) && bool.TryParse(s_params[i], out c_b)) convertedParams.Add(c_b); else convertedParams.Add(s_params[i]); i++; } var obj = ctor.Invoke(convertedParams.ToArray()); return obj; } catch (Exception e) { Console.WriteLine("Error converting CSV line: " + e.ToString()); } return null; }
/// <summary> /// Gets or creates an injector for the specified constructor. /// </summary> /// <param name="constructor">The constructor.</param> /// <returns>The created injector.</returns> public ConstructorInjector Create(ConstructorInfo constructor) { return args => constructor.Invoke(args); }
private object CreateObjectFromNonDefaultConstructor(JsonReader reader, JsonObjectContract contract, JsonProperty containerProperty, ConstructorInfo constructorInfo, string id) { ValidationUtils.ArgumentNotNull(constructorInfo, "constructorInfo"); // only need to keep a track of properies presence if they are required or a value should be defaulted if missing Dictionary<JsonProperty, PropertyPresence> propertiesPresence = (contract.HasRequiredOrDefaultValueProperties || HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Populate)) ? contract.Properties.ToDictionary(m => m, m => PropertyPresence.None) : null; Type objectType = contract.UnderlyingType; if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Deserializing {0} using a non-default constructor '{1}'.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType, constructorInfo)), null); IDictionary<JsonProperty, object> propertyValues = ResolvePropertyAndConstructorValues(contract, containerProperty, reader, objectType); IDictionary<ParameterInfo, object> constructorParameters = constructorInfo.GetParameters().ToDictionary(p => p, p => (object) null); IDictionary<JsonProperty, object> remainingPropertyValues = new Dictionary<JsonProperty, object>(); foreach (KeyValuePair<JsonProperty, object> propertyValue in propertyValues) { ParameterInfo matchingConstructorParameter = constructorParameters.ForgivingCaseSensitiveFind(kv => kv.Key.Name, propertyValue.Key.UnderlyingName).Key; if (matchingConstructorParameter != null) constructorParameters[matchingConstructorParameter] = propertyValue.Value; else remainingPropertyValues.Add(propertyValue); if (propertiesPresence != null) { // map from constructor property to normal property var property = propertiesPresence.Keys.FirstOrDefault(p => p.PropertyName == propertyValue.Key.PropertyName); if (property != null) propertiesPresence[property] = (propertyValue.Value == null) ? PropertyPresence.Null : PropertyPresence.Value; } } object createdObject = constructorInfo.Invoke(constructorParameters.Values.ToArray()); if (id != null) AddReference(reader, id, createdObject); OnDeserializing(reader, contract, createdObject); // go through unused values and set the newly created object's properties foreach (KeyValuePair<JsonProperty, object> remainingPropertyValue in remainingPropertyValues) { JsonProperty property = remainingPropertyValue.Key; object value = remainingPropertyValue.Value; if (ShouldSetPropertyValue(remainingPropertyValue.Key, remainingPropertyValue.Value)) { property.ValueProvider.SetValue(createdObject, value); } else if (!property.Writable && value != null) { // handle readonly collection/dictionary properties JsonContract propertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType); if (propertyContract.ContractType == JsonContractType.Array) { JsonArrayContract propertyArrayContract = (JsonArrayContract)propertyContract; object createdObjectCollection = property.ValueProvider.GetValue(createdObject); if (createdObjectCollection != null) { IWrappedCollection createdObjectCollectionWrapper = propertyArrayContract.CreateWrapper(createdObjectCollection); IWrappedCollection newValues = propertyArrayContract.CreateWrapper(value); foreach (object newValue in newValues) { createdObjectCollectionWrapper.Add(newValue); } } } else if (propertyContract.ContractType == JsonContractType.Dictionary) { JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)propertyContract; object createdObjectDictionary = property.ValueProvider.GetValue(createdObject); if (createdObjectDictionary != null) { IDictionary targetDictionary = (dictionaryContract.ShouldCreateWrapper) ? dictionaryContract.CreateWrapper(createdObjectDictionary) : (IDictionary) createdObjectDictionary; IDictionary newValues = (dictionaryContract.ShouldCreateWrapper) ? dictionaryContract.CreateWrapper(value) : (IDictionary) value; foreach (DictionaryEntry newValue in newValues) { targetDictionary.Add(newValue.Key, newValue.Value); } } } } } EndObject(createdObject, reader, contract, reader.Depth, propertiesPresence); OnDeserialized(reader, contract, createdObject); return createdObject; }
static object InvokeConstructor (ConstructorInfo constructor, object [] arguments) { try { return constructor.Invoke (arguments); } catch (TargetInvocationException e) { throw e.InnerException; } }
/// <summary> /// Invokes the users Conflict Interceptor and returns back with a resolution. /// </summary> /// <param name="e">Actual event args</param> /// <param name="constructorInfo">ConstructorInfo object</param> /// <param name="entityType">Entity type of the conflict</param> private SyncConflictResolution? GetUserConflictResolution(DbApplyChangeFailedEventArgs e, ConstructorInfo constructorInfo, Type entityType) { // Create the Client and Server entities IOfflineEntity clientVersion = (IOfflineEntity)constructorInfo.Invoke(null); IOfflineEntity serverVersion = null; // Read RemoteChange as client version _converter.GetEntityFromDataRow(e.Conflict.RemoteChange.Columns, e.Conflict.RemoteChange.Rows[0], clientVersion); // Set tombstone based on DbSyncConflict as the DataRow is always marked unchanged clientVersion.ServiceMetadata.IsTombstone = e.Conflict.Type == DbConflictType.LocalDeleteRemoteDelete || e.Conflict.Type == DbConflictType.LocalUpdateRemoteDelete; if (e.Conflict.LocalChange != null && e.Conflict.LocalChange.Rows.Count > 0) { // Server row exists. Create memory for row. serverVersion = (IOfflineEntity)constructorInfo.Invoke(null); _converter.GetEntityFromDataRow(e.Conflict.LocalChange.Columns, e.Conflict.LocalChange.Rows[0], serverVersion); // Set tombstone based on DbSyncConflict as the DataRow is always marked unchanged serverVersion.ServiceMetadata.IsTombstone = e.Conflict.Type == DbConflictType.LocalDeleteRemoteDelete || e.Conflict.Type == DbConflictType.LocalDeleteRemoteUpdate; } IOfflineEntity mergedVersion = null; this._conflictContext.ClientChange = clientVersion; this._conflictContext.ServerChange = serverVersion; SyncConflictResolution? userResolution = this._configuration.InvokeConflictInterceptor( this._conflictContext, entityType, out mergedVersion); // Check to see the resolution. if (userResolution != null && userResolution == SyncConflictResolution.Merge) { // Check that mergedVersion is not null and is of the expected type if (mergedVersion == null) { throw new InvalidOperationException("User SyncConflictInterceptor returned a conflict resolution of 'Merge' but did not specify a merged version."); } if (mergedVersion.GetType() != clientVersion.GetType()) { throw new InvalidOperationException( string.Format(CultureInfo.InvariantCulture, "User SyncConflictInterceptor returned merged version entity type '{0} does not match required type '{1}'.", mergedVersion.GetType().Name, clientVersion.GetType().Name)); } // Merge is required // If merge is requested then the server version is always the losing version as changes are overwritten. In this case // set the policy to clientWins and copy the mergedVersion values in to the Args.Conflict.RemoteChange object[] rowValues = _converter.CopyEntityToDataRow(mergedVersion, e.Conflict.RemoteChange); // Now add this row back to the DataSet to we can retry applying this. _converter.MergeChangeInToDataSet(e.Context.DataSet.Tables[e.Conflict.RemoteChange.TableName], e.Conflict.RemoteChange.Rows[0], rowValues, mergedVersion.GetType()); } return userResolution; }
private object CreateObjectFromNonDefaultConstructor(JsonReader reader, JsonObjectContract contract, ConstructorInfo constructorInfo, string id) { ValidationUtils.ArgumentNotNull(constructorInfo, "constructorInfo"); Type objectType = contract.UnderlyingType; IDictionary<JsonProperty, object> propertyValues = ResolvePropertyAndConstructorValues(contract, reader, objectType); IDictionary<ParameterInfo, object> constructorParameters = constructorInfo.GetParameters().ToDictionary(p => p, p => (object) null); IDictionary<JsonProperty, object> remainingPropertyValues = new Dictionary<JsonProperty, object>(); foreach (KeyValuePair<JsonProperty, object> propertyValue in propertyValues) { ParameterInfo matchingConstructorParameter = constructorParameters.ForgivingCaseSensitiveFind(kv => kv.Key.Name, propertyValue.Key.UnderlyingName).Key; if (matchingConstructorParameter != null) constructorParameters[matchingConstructorParameter] = propertyValue.Value; else remainingPropertyValues.Add(propertyValue); } object createdObject = constructorInfo.Invoke(constructorParameters.Values.ToArray()); if (id != null) Serializer.ReferenceResolver.AddReference(this, id, createdObject); contract.InvokeOnDeserializing(createdObject, Serializer.Context); // go through unused values and set the newly created object's properties foreach (KeyValuePair<JsonProperty, object> remainingPropertyValue in remainingPropertyValues) { JsonProperty property = remainingPropertyValue.Key; object value = remainingPropertyValue.Value; if (ShouldSetPropertyValue(remainingPropertyValue.Key, remainingPropertyValue.Value)) { property.ValueProvider.SetValue(createdObject, value); } else if (!property.Writable && value != null) { // handle readonly collection/dictionary properties JsonContract propertyContract = Serializer.ContractResolver.ResolveContract(property.PropertyType); if (propertyContract.ContractType == JsonContractType.Array) { JsonArrayContract propertyArrayContract = propertyContract as JsonArrayContract; object createdObjectCollection = property.ValueProvider.GetValue(createdObject); if (createdObjectCollection != null) { IWrappedCollection createdObjectCollectionWrapper = propertyArrayContract.CreateWrapper(createdObjectCollection); IWrappedCollection newValues = propertyArrayContract.CreateWrapper(value); foreach (object newValue in newValues) { createdObjectCollectionWrapper.Add(newValue); } } } else if (propertyContract.ContractType == JsonContractType.Dictionary) { JsonDictionaryContract jsonDictionaryContract = propertyContract as JsonDictionaryContract; object createdObjectDictionary = property.ValueProvider.GetValue(createdObject); if (createdObjectDictionary != null) { IWrappedDictionary createdObjectDictionaryWrapper = jsonDictionaryContract.CreateWrapper(createdObjectDictionary); IWrappedDictionary newValues = jsonDictionaryContract.CreateWrapper(value); foreach (DictionaryEntry newValue in newValues) { createdObjectDictionaryWrapper.Add(newValue.Key, newValue.Value); } } } } } contract.InvokeOnDeserialized(createdObject, Serializer.Context); return createdObject; }
private object CreateObjectFromNonDefaultConstructor(JsonReader reader, JsonObjectContract contract, ConstructorInfo constructorInfo, string id) { ValidationUtils.ArgumentNotNull(constructorInfo, "constructorInfo"); Type objectType = contract.UnderlyingType; IDictionary<JsonProperty, object> propertyValues = new Dictionary<JsonProperty, object>(); bool exit = false; do { switch (reader.TokenType) { case JsonToken.PropertyName: string memberName = reader.Value.ToString(); // attempt exact case match first // then try match ignoring case JsonProperty property = contract.Properties.GetClosestMatchProperty(memberName); if (property != null) { if (!ReadForType(reader, property.PropertyType, property.Converter)) throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); if (!property.Ignored) propertyValues[property] = CreateValueProperty(reader, property, null, true, null); else reader.Skip(); } else { if (!reader.Read()) throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); if (Serializer.MissingMemberHandling == MissingMemberHandling.Error) throw new JsonSerializationException("Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, objectType.Name)); reader.Skip(); } break; case JsonToken.Comment: break; case JsonToken.EndObject: exit = true; break; default: throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType); } } while (!exit && reader.Read()); IDictionary<ParameterInfo, object> constructorParameters = constructorInfo.GetParameters().ToDictionary(p => p, p => (object)null); IDictionary<JsonProperty, object> remainingPropertyValues = new Dictionary<JsonProperty, object>(); foreach (KeyValuePair<JsonProperty, object> propertyValue in propertyValues) { ParameterInfo matchingConstructorParameter = constructorParameters.ForgivingCaseSensitiveFind(kv => kv.Key.Name, propertyValue.Key.PropertyName).Key; if (matchingConstructorParameter != null) constructorParameters[matchingConstructorParameter] = propertyValue.Value; else remainingPropertyValues.Add(propertyValue); } object createdObject = constructorInfo.Invoke(constructorParameters.Values.ToArray()); if (id != null) Serializer.ReferenceResolver.AddReference(this, id, createdObject); contract.InvokeOnDeserializing(createdObject, Serializer.Context); // go through unused values and set the newly created object's properties foreach (KeyValuePair<JsonProperty, object> remainingPropertyValue in remainingPropertyValues) { JsonProperty property = remainingPropertyValue.Key; object value = remainingPropertyValue.Value; if (ShouldSetPropertyValue(remainingPropertyValue.Key, remainingPropertyValue.Value)) property.ValueProvider.SetValue(createdObject, value); } contract.InvokeOnDeserialized(createdObject, Serializer.Context); return createdObject; }