//[Test] public void PerformanceTests() { int n = 10000000; object x = null; // tesla.Name start = DateTime.Now; for (int i = 0; i < n; i++) { x = tesla.Name; } stop = DateTime.Now; PrintTest("tesla.Name (direct)", n, Elapsed); start = DateTime.Now; IDynamicField placeOfBirth = Create(typeof(Inventor).GetField("Name")); for (int i = 0; i < n; i++) { x = placeOfBirth.GetValue(tesla); } stop = DateTime.Now; PrintTest("tesla.Name (dynamic reflection)", n, Elapsed); start = DateTime.Now; FieldInfo placeOfBirthFi = typeof(Inventor).GetField("Name"); for (int i = 0; i < n; i++) { x = placeOfBirthFi.GetValue(tesla); } stop = DateTime.Now; PrintTest("tesla.Name (standard reflection)", n, Elapsed); }
public void TestAttemptingToSetFieldOfValueTypeInstance() { MyStruct myYearHolder = new MyStruct(); IDynamicField year = Create(typeof(MyStruct).GetField("year")); year.SetValue(myYearHolder, 2004); }
public void TestStaticFieldsOfStruct() { // static readonly IDynamicField maxValue = Create(typeof(DateTime).GetField("MaxValue")); Assert.AreEqual(DateTime.MaxValue, maxValue.GetValue(null)); try { maxValue.SetValue(null, DateTime.Now); } catch (InvalidOperationException) { } // const IDynamicField int64max = Create(typeof(Int64).GetField("MaxValue", BindingFlags.Public | BindingFlags.Static)); Assert.AreEqual(Int64.MaxValue, int64max.GetValue(null)); try { int64max.SetValue(null, 0); } catch (InvalidOperationException) { } // pure static IDynamicField myField = Create(typeof(MyStaticStruct).GetField("staticYear")); myField.SetValue(null, 2008); Assert.AreEqual(2008, myField.GetValue(null)); }
public void AddProperty(bool bStatic, string name, IDynamicField field) { var ctx = (JSContext)_context; var nameAtom = _register.GetAtom(name); var getterVal = JSApi.JS_UNDEFINED; var setterVal = JSApi.JS_UNDEFINED; var flags = JSPropFlags.JS_PROP_CONFIGURABLE | JSPropFlags.JS_PROP_ENUMERABLE | JSPropFlags.JS_PROP_HAS_GET | JSPropFlags.JS_PROP_HAS_SET | JSPropFlags.JS_PROP_WRITABLE; var db = _register.GetTypeDB(); db.NewDynamicFieldAccess(nameAtom, field, out getterVal, out setterVal); var rs = JSApi.JS_DefineProperty(ctx, bStatic ? _ctor : _proto, nameAtom, JSApi.JS_UNDEFINED, getterVal, setterVal, flags); if (rs != 1) { var logger = _register.GetLogger(); if (logger != null) { logger.Write(LogLevel.Error, "define property failed: {0}", ctx.GetExceptionString()); } } JSApi.JS_FreeValue(ctx, getterVal); JSApi.JS_FreeValue(ctx, setterVal); }
public void TestAttemptingToSetFieldOfValueTypeInstance() { MyStruct myYearHolder = new MyStruct(); IDynamicField year = Create(typeof(MyStruct).GetField("year")); Assert.Throws <InvalidOperationException>(() => year.SetValue(myYearHolder, 2004)); }
public void NewDynamicFieldAccess(JSAtom name, IDynamicField field, out JSValue getter, out JSValue setter) { var magic = _dynamicFields.Count; getter = JSApi.JSB_NewCFunction(_context, JSApi._DynamicFieldGetter, name, magic); setter = JSApi.JSB_NewCFunction(_context, JSApi._DynamicFieldSetter, name, magic); _dynamicFields.Add(field); }
public void CannotSetStaticReadOnlyField() { IDynamicField myReadonlyField = Create(typeof(MyStaticClass).GetField("myReadonlyField")); try { myReadonlyField.SetValue(null, "some other string"); Assert.Fail(); } catch (InvalidOperationException) { } }
public void CanReadPrivateReadOnlyField() { IDynamicField myPrivateReadonlyField2 = null; FieldInfo fieldInfo = typeof(MyStaticClass).GetField("myPrivateReadonlyField", BindingFlags.Static | BindingFlags.NonPublic); myPrivateReadonlyField2 = Create(fieldInfo); string u2 = (string)myPrivateReadonlyField2.GetValue(null); string u1 = "hahaha"; Assert.AreEqual(u1, u2); }
/// <summary> /// Returns dynamic field if one exists. /// </summary> /// <param name="field">Field to look up.</param> /// <param name="createCallback">callback function that will be called to create the dynamic field</param> /// <returns>An <see cref="IDynamicField"/> for the given field info.</returns> internal static IDynamicField GetDynamicField(FieldInfo field, CreateFieldCallback createCallback) { lock (fieldCache.SyncRoot) { IDynamicField dynamicField = (IDynamicField)fieldCache[field]; if (dynamicField == null) { dynamicField = createCallback(field); fieldCache[field] = dynamicField; } return(dynamicField); } }
static ControlCollectionAccessor() { IDynamicField owner = null; SecurityCritical.ExecutePrivileged( new PermissionSet(PermissionState.Unrestricted), delegate { #if MONO_2_0 owner = new SafeField(typeof (ControlCollection).GetField("owner", BindingFlags.Instance | BindingFlags.NonPublic)); #else owner = new SafeField(typeof (ControlCollection).GetField("_owner", BindingFlags.Instance | BindingFlags.NonPublic)); #endif }); _owner = owner; }
static ControlCollectionAccessor() { IDynamicField owner = null; SecurityCritical.ExecutePrivileged(new PermissionSet(PermissionState.Unrestricted), delegate { #if MONO_2_0 owner = new SafeField(typeof(ControlCollection).GetField("owner", BindingFlags.Instance | BindingFlags.NonPublic)); #else owner = new SafeField(typeof(ControlCollection).GetField("_owner", BindingFlags.Instance | BindingFlags.NonPublic)); #endif }); _owner = owner; }
public void TestSetIncompatibleType() { IDynamicField inventorPlace = Create(typeof(Inventor).GetField("pob", BINDANY)); try { inventorPlace.SetValue(new Inventor(), new object()); Assert.Fail(); } catch (InvalidCastException) { } try { inventorPlace.SetValue(new Inventor(), new DateTime()); Assert.Fail(); } catch (InvalidCastException) { } IDynamicField inventorDOB = Create(typeof(Inventor).GetField("dob", BINDANY)); try { inventorDOB.SetValue(new Inventor(), 2); Assert.Fail(); } catch (InvalidCastException) { } try { inventorDOB.SetValue(new Inventor(), new Place()); Assert.Fail(); } catch (InvalidCastException) { } }
/// <summary> /// Creates a new instance of the safe field wrapper. /// </summary> /// <param name="field">Field to wrap.</param> public SafeField(FieldInfo field) { AssertUtils.ArgumentNotNull(field, "You cannot create a dynamic field for a null value."); this.fieldInfo = field; this.canSet = (!fieldInfo.IsLiteral && !fieldInfo.IsInitOnly && !(fieldInfo.DeclaringType.IsValueType && !fieldInfo.IsStatic)); if (fieldInfo.IsPublic && ReflectionUtils.IsTypeVisible(fieldInfo.DeclaringType, DynamicReflectionManager.ASSEMBLY_NAME)) { dynamicField = DynamicField.Create(fieldInfo); isOptimizedGet = isOptimizedSet = true; } }
public void TestInstanceFields() { IDynamicField name = Create(typeof(Inventor).GetField("Name")); Assert.AreEqual(tesla.Name, name.GetValue(tesla)); name.SetValue(tesla, "Tesla, Nikola"); Assert.AreEqual("Tesla, Nikola", tesla.Name); Assert.AreEqual("Tesla, Nikola", name.GetValue(tesla)); MyStruct myYearHolder = new MyStruct(); myYearHolder.Year = 2004; IDynamicField year = Create(typeof(MyStruct).GetField("year", BINDANY)); Assert.AreEqual(2004, year.GetValue(myYearHolder)); }
public void CannotReadPrivateReadOnlyFieldIfNoReflectionPermission() { FieldInfo fieldInfo = typeof(MyStaticClass).GetField("myPrivateReadonlyField", BindingFlags.Static | BindingFlags.NonPublic); try { SecurityTemplate.MediumTrustInvoke(delegate { IDynamicField myPrivateReadonlyField2 = Create(fieldInfo); }); Assert.Fail("private field must not be accessible in medium trust: " + fieldInfo); } catch (SecurityException sex) { Assert.IsTrue(sex.Message.IndexOf("ReflectionPermission") > -1); } }
protected static object GetVisualBasicTestObject() { if (s__visualBasicTestObjectType == null) { // compile vb test class string vbSourceCode = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(typeof(BasePropertyTests), "SafePropertyTests_TestObject.vb")).ReadToEnd(); CompilerParameters args = new CompilerParameters(); args.OutputAssembly = "VbTestObject.dll"; args.GenerateInMemory = true; args.GenerateExecutable = false; args.IncludeDebugInformation = true; #if NET_2_0 CodeDomProvider provider = CodeDomProvider.CreateProvider("VisualBasic"); CompilerResults results = provider.CompileAssemblyFromSource(args, vbSourceCode); #else CodeDomProvider provider = new VBCodeProvider(); ICodeCompiler compiler = provider.CreateCompiler(); CompilerResults results = compiler.CompileAssemblyFromSource(args, vbSourceCode); #endif if (results.Errors.HasErrors) { StringBuilder sb = new StringBuilder(); foreach (CompilerError error in results.Errors) { sb.Append(error.ToString()).Append("\n\r"); } throw new TypeLoadException("failed compiling test class: " + sb); } s__visualBasicTestObjectType = results.CompiledAssembly.GetType("VbTestObject"); ThisLastPropertyValue = DynamicField.Create(s__visualBasicTestObjectType.GetField("ThisLastPropertyValue")); ThisArg1 = DynamicField.Create(s__visualBasicTestObjectType.GetField("ThisArg1")); ThisArg2 = DynamicField.Create(s__visualBasicTestObjectType.GetField("ThisArg2")); ThisOptionalArg = DynamicField.Create(s__visualBasicTestObjectType.GetField("ThisOptionalArg")); ThisParamsArg = DynamicField.Create(s__visualBasicTestObjectType.GetField("ThisParamsArgs")); } object s__visualBasicTestObject = Activator.CreateInstance(s__visualBasicTestObjectType); return(s__visualBasicTestObject); }
public void TestStaticFieldsOfClass() { IDynamicField myField = Create(typeof(MyStaticClass).GetField("myField")); myField.SetValue(null, "here we go..."); IDynamicField myConst = Create(typeof(MyStaticClass).GetField("MyConst")); Assert.AreEqual(3456, myConst.GetValue(null)); try { myConst.SetValue(null, 7890); } catch (InvalidOperationException) { } IDynamicField myReadonlyField = Create(typeof(MyStaticClass).GetField("myReadonlyField")); string s2 = (string)myReadonlyField.GetValue(null); string s1 = MyStaticClass.myReadonlyField; Assert.AreEqual(s1, s2); }
static void Main() { Program.UsingCodeDOM(); String assemblyName = "RVJ.Core.Person"; IDynamicBuilder personBuilder = new DynamicBuilder(assemblyName); /* * * Defines a dynamic .NET Assembly. * The method automatically defines a dynamic .NET Module with the same name. * */ IDynamicAssembly personDynamicAssembly = personBuilder.DefineDynamicAssembly(); /* * * Defines a dynamic .NET Module. * */ IDynamicModule personDynamicModule = personDynamicAssembly.DefineDynamicModule(); /* * * Defines a dynamic .NET Type. * */ IDynamicType personDynamicType = personDynamicModule.DefineDynamicType(assemblyName, ClassTypeFlags.Public, typeof(System.Object)); IDynamicField _id_DynamicField = personDynamicType.DefineDynamicField("_id", typeof(System.UInt32), FieldFlags.Private); IDynamicField _name_DynamicField = personDynamicType.DefineDynamicField("_name", typeof(System.String), FieldFlags.Private); IDynamicField _age_DynamicField = personDynamicType.DefineDynamicField("_age", typeof(System.UInt32), FieldFlags.Private); /* * * A dynamic .NET Property is associated with a dynamic .NET Field. * By default, the implementation of IDynamicField.DefineDynamicProperty method defines both, get and set accessor methods. * We should use RVJ.Core.PropertyFlags enum option to indicates if characteristics of a dynamic .NET Property. * */ _id_DynamicField.DefineDynamicProperty("Id", typeof(System.UInt32), PropertyFlags.Public | PropertyFlags.ReadAndWrite); _name_DynamicField.DefineDynamicProperty("Name", typeof(System.String), PropertyFlags.Public | PropertyFlags.ReadAndWrite); _age_DynamicField.DefineDynamicProperty("Age", typeof(System.UInt32), PropertyFlags.Public | PropertyFlags.ReadAndWrite); /* * * Creates an instance of the RVJ.Core.Person dynamic .NET Type. * */ Object person = personDynamicType.CreateAnInstance("RVJ.Core.Person"); /* * * Gets an instance of a dynamic .NET Field. * The search that the System.Type.GetField() instance method does, is case-sensitive. * */ Type personType = person.GetType(); FieldInfo personFieldId = personType.GetField("_id", (BindingFlags.NonPublic | BindingFlags.Instance)); FieldInfo personFieldName = personType.GetField("_name", (BindingFlags.NonPublic | BindingFlags.Instance)); FieldInfo personFieldAge = personType.GetField("_age", (BindingFlags.NonPublic | BindingFlags.Instance)); /* * * Shows the dynamic .NET Field values before assigning new values. * */ UInt32 newId = ( UInt32 )personFieldId.GetValue(person); String newName = ( String )personFieldName.GetValue(person); UInt32 newAge = ( UInt32 )personFieldAge.GetValue(person); if (newName == null) { newName = String.Empty; } Console.WriteLine("Before new values...\nperson._id: {0}\nperson._name: {1}\nperson._age: {2}\n", newId.ToString(), newName, newAge.ToString()); newId = 100; newName = "New Name!!!"; newAge = 25; personFieldId.SetValue(person, newId); personFieldName.SetValue(person, newName); personFieldAge.SetValue(person, newAge); newId = ( UInt32 )personFieldId.GetValue(person); newName = ( String )personFieldName.GetValue(person); newAge = ( UInt32 )personFieldAge.GetValue(person); Console.WriteLine("After new values assigned...\nperson._id: {0}\nperson._name: {1}\nperson._age: {2}\n", newId.ToString(), newName, newAge.ToString()); Program.Pause(); /* * * Now, we are using the dynamic .NET Properties defined for each dynamic .NET Field, to do the same operations of "get" and "set" values. * */ newId = ( UInt32 )personType.InvokeMember("Id", BindingFlags.GetProperty, null, person, null); newName = ( String )personType.InvokeMember("Name", BindingFlags.GetProperty, null, person, null); newAge = ( UInt32 )personType.InvokeMember("Age", BindingFlags.GetProperty, null, person, null); Console.WriteLine("Before new values assigned...\nperson._id: {0}\nperson._name: {1}\nperson._age: {2}\n", newId.ToString(), newName, newAge.ToString()); newId = 200; newName = "New Name using a dynamic .NET Property!!!"; newAge = 35; personType.InvokeMember("Id", BindingFlags.SetProperty, null, person, new Object[] { newId }); personType.InvokeMember("Name", BindingFlags.SetProperty, null, person, new Object[] { newName }); personType.InvokeMember("Age", BindingFlags.SetProperty, null, person, new Object[] { newAge }); Console.WriteLine("After new values...\nperson._id: {0}\nperson._name: {1}\nperson._age: {2}\n", newId.ToString(), newName, newAge.ToString()); Program.Pause(true); }
protected static object GetVisualBasicTestObject() { if (s__visualBasicTestObjectType == null) { // compile vb test class string vbSourceCode = new StreamReader( Assembly.GetExecutingAssembly().GetManifestResourceStream( typeof( BasePropertyTests ), "SafePropertyTests_TestObject.vb" ) ).ReadToEnd(); CompilerParameters args = new CompilerParameters(); args.OutputAssembly = "VbTestObject.dll"; args.GenerateInMemory = true; args.GenerateExecutable = false; args.IncludeDebugInformation = true; CodeDomProvider provider = CodeDomProvider.CreateProvider( "VisualBasic" ); CompilerResults results = provider.CompileAssemblyFromSource( args, vbSourceCode ); if (results.Errors.HasErrors) { StringBuilder sb = new StringBuilder(); foreach (CompilerError error in results.Errors) { sb.Append( error.ToString() ).Append( "\n\r" ); } throw new TypeLoadException( "failed compiling test class: " + sb ); } s__visualBasicTestObjectType = results.CompiledAssembly.GetType( "VbTestObject" ); ThisLastPropertyValue = DynamicField.Create( s__visualBasicTestObjectType.GetField("ThisLastPropertyValue") ); ThisArg1 = DynamicField.Create( s__visualBasicTestObjectType.GetField("ThisArg1") ); ThisArg2 = DynamicField.Create( s__visualBasicTestObjectType.GetField("ThisArg2") ); ThisOptionalArg = DynamicField.Create( s__visualBasicTestObjectType.GetField("ThisOptionalArg") ); ThisParamsArg = DynamicField.Create( s__visualBasicTestObjectType.GetField("ThisParamsArgs") ); } object s__visualBasicTestObject = Activator.CreateInstance(s__visualBasicTestObjectType); return s__visualBasicTestObject; }
public void AddField(bool bStatic, string name, IDynamicField field) { AddProperty(bStatic, name, field); }