public void GetMethodProxy_NullInput_ThrowsArgumentNullException() { ArgumentNullException ex = Assert.Throws <ArgumentNullException>( delegate() { ProxyDelegate setter = DynamicMethodGenerator.GetMethodProxy(null); }); Assert.Equal("methodInfo", ex.ParamName); }
public void GetMethodProxy_MethodNoArgsOneReturn_BuildsProxyAndInvokes() { var input = new Example(); ProxyDelegate proxy = DynamicMethodGenerator.GetMethodProxy(typeof(Example).GetMethod("GetMi")); Assert.NotNull(proxy); var actual = (string)proxy(input); Assert.Equal("me", actual); }
public void GetMethodProxy_ArgsTypeMismatchWhenCalling_ThrowsArgumentNullException() { ProxyDelegate proxy = DynamicMethodGenerator.GetMethodProxy(typeof(Example).GetMethod("Reset")); Assert.NotNull(proxy); InvalidCastException ex = Assert.Throws <InvalidCastException>( delegate() { proxy(new Example(), 1, 2, 3, 4, 5, 6, 7, 8, 9); }); }
public void GetMethodProxy_ArgsMissingWhenCalling_ThrowsArgumentNullException() { ProxyDelegate proxy = DynamicMethodGenerator.GetMethodProxy(typeof(Example).GetMethod("Reset")); Assert.NotNull(proxy); ArgumentException ex = Assert.Throws <ArgumentException>( delegate() { var actual = proxy(new Example(), "alpha", "bravo", "charlie", -1, -2, -3); }); }
public void GetMethodProxy_MethodOneArgOneReturn_BuildsProxyAndInvokes() { var input = new Example(); ProxyDelegate proxy = DynamicMethodGenerator.GetMethodProxy(typeof(Example).GetMethod("Swap")); Assert.NotNull(proxy); var actual = (string)proxy(input, "foo"); Assert.Equal("aye", actual); Assert.Equal("foo", input.A); }
public void GetMethodProxy_1MillionMethodCalls_PerformsInAround50ms() { Example instance = new Example(); MethodInfo methodInfo = typeof(Example).GetMethod("GetMi", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); ProxyDelegate proxy = DynamicMethodGenerator.GetMethodProxy(methodInfo); string value = null; for (long i = 0; i < MaxCount; i++) { value = (string)proxy(instance); } }
public void GetMethodProxy_MethodExtraArgs_IgnoresExtraBuildsProxyAndInvokes() { var input = new Example(); var expected = new Example("alpha", "bravo", "charlie", -1, -2, -3, "deer", "sun", "myself"); ProxyDelegate proxy = DynamicMethodGenerator.GetMethodProxy(typeof(Example).GetMethod("Reset")); Assert.NotNull(proxy); proxy(input, "alpha", "bravo", "charlie", -1, -2, -3, "deer", "sun", "myself", 4, 5, 6, "extra", false); var getters = from m in typeof(Example).GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy) let g = DynamicMethodGenerator.GetGetter(m) where (g != null) select g; foreach (GetterDelegate getter in getters) { // assert all of the fields and properties are equal Assert.Equal(getter(expected), getter(input)); } }
/// <summary> /// Gets a delegate which determines if the property or field should not be serialized based upon its value. /// </summary> /// <param name="member"></param> /// <returns>if has a value equivalent to the DefaultValueAttribute or has a property named XXXSpecified which determines visibility</returns> /// <remarks> /// This is useful when default values need not be serialized. /// Under these situations XmlSerializer ignores properties based upon value: /// - DefaultValue: http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx /// - Specified Properies: http://msdn.microsoft.com/en-us/library/bb402199.aspx /// - ShouldSerialize Methods: http://msdn.microsoft.com/en-us/library/53b8022e.aspx /// </remarks> public override ValueIgnoredDelegate GetValueIgnoredCallback(MemberInfo member) { Type objType = member.ReflectedType ?? member.DeclaringType; // look up specified property to see if exists GetterDelegate specifiedPropertyGetter = null; PropertyInfo specProp = objType.GetProperty(member.Name + SpecifiedSuffix, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); // ensure is correct return type if (specProp != null && specProp.PropertyType == typeof(bool)) { specifiedPropertyGetter = DynamicMethodGenerator.GetPropertyGetter(specProp); } // look up specified property to see if exists ProxyDelegate shouldSerializeProxy = null; MethodInfo shouldSerialize = objType.GetMethod(ShouldSerializePrefix + member.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); // ensure is correct return type if (shouldSerialize != null && shouldSerialize.ReturnType == typeof(bool) && shouldSerialize.GetParameters().Length == 0) { shouldSerializeProxy = DynamicMethodGenerator.GetMethodProxy(shouldSerialize); } // to be most efficient must create a different delegate for each of 8 combinations so not performing extra work DefaultValueAttribute defaultAttr = TypeCoercionUtility.GetAttribute <DefaultValueAttribute>(member); if (defaultAttr == null) { if (specifiedPropertyGetter == null) { if (shouldSerializeProxy == null) { // situation 1: only need to check if equal to null return(delegate(object target, object value) { return (value == null); }); } // situation 2: create a delegate which simply calls the should serialize method return(delegate(object target, object value) { return (value == null) || Object.Equals(false, shouldSerializeProxy(target)); }); } if (shouldSerializeProxy == null) { // situation 3: create a delegate which simply calls the specified property return(delegate(object target, object value) { return (value == null) || Object.Equals(false, specifiedPropertyGetter(target)); }); } // situation 4: create a delegate which calls both the specified property and the should serialize method return(delegate(object target, object value) { return (value == null) || Object.Equals(false, shouldSerializeProxy(target)) || Object.Equals(false, specifiedPropertyGetter(target)); }); } // extract default value since cannot change (is constant in attribute) object defaultValue = defaultAttr.Value; if (specifiedPropertyGetter == null) { if (shouldSerializeProxy == null) { // situation 5: create a specific delegate which only has to compare the default value to the current value return(delegate(object target, object value) { return (value == null) || Object.Equals(defaultValue, value); }); } // situation 6: create a specific delegate which both compares to default value and calls should serialize method return(delegate(object target, object value) { return (value == null) || Object.Equals(defaultValue, value) || Object.Equals(false, shouldSerializeProxy(target)); }); } if (shouldSerializeProxy == null) { // situation 7: create a specific delegate which both compares to default value and checks specified property return(delegate(object target, object value) { return (value == null) || Object.Equals(defaultValue, value) || Object.Equals(false, specifiedPropertyGetter(target)); }); } // situation 8: create a combined delegate which checks all states return(delegate(object target, object value) { return (value == null) || Object.Equals(defaultValue, value) || Object.Equals(false, shouldSerializeProxy(target)) || Object.Equals(false, specifiedPropertyGetter(target)); }); }
public void NetworkStreamA() { TestRfcommPort t1; BluetoothClient cli; Stream t3; NetworkStream strm; int readLen; // Create_ConnectedBluetoothClient(out t1, out cli, out t3); strm = cli.GetStream(); // Cause a second NetworkStream to be created, to test SocketPair stuff! Create_ConnectedBluetoothClient(out t1, out cli, out t3); strm = cli.GetStream(); // Assert.IsTrue(cli.Connected, "isConnected 1"); Assert.IsTrue(strm.CanRead, "CanRead 1"); Assert.IsTrue(strm.CanWrite, "CanWrite 1"); Assert.IsFalse(strm.CanSeek, "CanSeek 1"); Assert_StreamIsNonSeekable(strm); Assert_StreamIsTimeoutable(strm); // Ignored strm.Flush(); // // Write strm.Write(dataA, 0, dataA.Length); // // Read byte[] buf10 = new byte[10]; t1.NewReceive(dataB9); readLen = strm.Read(buf10, 0, buf10.Length); Assert.AreEqual(dataB9.Length, readLen, "readLen 1"); // // Read+DataAvailable byte[] buf5 = new byte[5]; Assert.IsFalse(strm.DataAvailable, "DataAvailable 1a"); t1.NewReceive(dataB9); Assert.IsTrue(strm.DataAvailable, "DataAvailable 1b"); readLen = strm.Read(buf5, 0, buf5.Length); Assert.AreEqual(5, readLen, "readLen 1"); Assert.IsTrue(strm.DataAvailable, "DataAvailable 1c"); readLen = strm.Read(buf5, 0, buf5.Length); Assert.AreEqual(4, readLen, "readLen 1"); Assert.IsFalse(strm.DataAvailable, "DataAvailable 1d"); // // BeginRead byte[] buf5a = new byte[5]; byte[] buf5b = new byte[5]; IAsyncResult arRa, arRb; int signalledA = 0, signalledB = 0; object stateA = new object(), stateB = new object(); bool? correctStateA = null, correctStateB = null; arRa = strm.BeginRead(buf5, 0, buf5.Length, delegate(IAsyncResult arCB) { ++signalledA; correctStateA = (arCB.AsyncState == stateA); }, stateA); arRb = strm.BeginRead(buf5, 0, buf5.Length, delegate(IAsyncResult arCB) { ++signalledB; correctStateB = (arCB.AsyncState == stateB); }, stateB); Assert.AreEqual(0, signalledA, "signalledA before data"); Assert.AreEqual(0, signalledB, "signalledB before data"); t1.NewReceive(dataB9); System.Threading.Thread.Sleep(20); // Give time for the callbacks to run. Assert.AreEqual(1, signalledA, "signalledA after data"); Assert.AreEqual(1, signalledB, "signalledB after data"); Assert.AreEqual(true, correctStateA, "correctStateA"); Assert.AreEqual(true, correctStateB, "correctStateB"); readLen = strm.EndRead(arRa); Assert.AreEqual(5, readLen, "readLen A"); readLen = strm.EndRead(arRb); Assert.AreEqual(4, readLen, "readLen B"); Assert.IsFalse(strm.DataAvailable, "DataAvailable 1d"); // // BeginWrite IAsyncResult arWa; signalledA = 0; correctStateA = null; System.Threading.ManualResetEvent go = new System.Threading.ManualResetEvent(false); ProxyDelegate <IAsyncResult> proxy = new ProxyDelegate <IAsyncResult>( delegate(IAsyncResult arCB) { try { strm.EndWrite(arCB); ++signalledA; correctStateA = (arCB.AsyncState == stateA); } finally { Assert.IsTrue(go.Set(), "go.Set()"); } }); arWa = strm.BeginWrite(dataA, 0, dataA.Length, proxy.CallbackMethod, stateA); Assert.IsTrue(go.WaitOne(1000, false), "go Event"); Assert.AreEqual(1, signalledA, "signalledA BeginWrite"); Assert.AreEqual(true, correctStateA, "correctStateA BeginWrite"); // strm.Close(); }
/// <summary> /// Ctor /// </summary> public FactoryMap(Type type) { if (type == null) { throw new ArgumentNullException("type"); } if (FactoryMap.IsInvalidType(type)) { throw new TypeLoadException(String.Format( FactoryMap.ErrorCannotInstantiate, type.FullName)); } this.Ctor = DynamicMethodGenerator.GetTypeFactory(type); ConstructorInfo[] ctors; if (!typeof(IEnumerable).IsAssignableFrom(type)) { if (this.Ctor != null) { return; } ctors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy); if (ctors.Length == 1) { ConstructorInfo ctor = ctors[0]; this.Ctor = DynamicMethodGenerator.GetTypeFactory(ctor); this.CtorArgs = ctor.GetParameters(); } return; } // many ICollection types take an IEnumerable or ICollection // as a constructor argument. look through constructors for // a compatible match. ctors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy); this.CollectionCtors = new Dictionary <Type, FactoryDelegate>(ctors.Length); foreach (ConstructorInfo ctor in ctors) { ParameterInfo[] paramList = ctor.GetParameters(); if (paramList.Length != 1) { continue; } Type argType = paramList[0].ParameterType; if ((argType == typeof(string)) || ( #if !NETCF (argType.GetInterface(TypeCoercionUtility.TypeGenericIEnumerable, false) == null) && #endif (typeof(IEnumerable).IsAssignableFrom(argType)))) { continue; } // save all constructors that can take an enumerable of objects this.CollectionCtors[argType] = DynamicMethodGenerator.GetTypeFactory(ctor); } if (this.Ctor == null) { // try to grab a private ctor if exists this.Ctor = DynamicMethodGenerator.GetTypeFactory(type); } // many collection types have an AddRange method // which adds a collection of items at once MethodInfo methodInfo = type.GetMethod("AddRange"); if (methodInfo != null) { ParameterInfo[] parameters = methodInfo.GetParameters(); if (parameters.Length == 1) { this.AddRange = DynamicMethodGenerator.GetMethodProxy(methodInfo); this.AddRangeType = parameters[0].ParameterType; } } // many collection types have an Add method // which adds items one at a time Type collectionType = null; #if !NETCF collectionType = type.GetInterface(TypeCoercionUtility.TypeGenericICollection, false); #endif if (collectionType != null) { methodInfo = collectionType.GetMethod("Add"); } else { methodInfo = type.GetMethod("Add"); } if (methodInfo != null) { ParameterInfo[] parameters = methodInfo.GetParameters(); if (parameters.Length == 1) { this.Add = DynamicMethodGenerator.GetMethodProxy(methodInfo); this.AddType = parameters[0].ParameterType; } } }