Search Results

Search found 1575 results on 63 pages for 'reflection'.

Page 6/63 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • IL short-form instructions aren't short?

    - by Alix
    Hi. I was looking at the IL code of a valid method with Reflector and I've run into this: L_00a5: leave.s L_0103 Instructions with the suffix .s are supposed to take an int8 operand, and sure enough this is should be the case with Leave_S as well. However, 0x0103 is 259, which exceeds the capacity of an int8. The method somehow works, but when I read the instructions with method Mono.Reflection.Disassembler.GetInstructions it retrieves L_00a5: leave.s L_0003 that is, 3 instead of 259, because it's supposed to be an int8. So, my question: how is the original instruction (leave.s L_0103) possible? I have looked at the ECMA documentation for that (Partition III: CIL Instruction Set) and I can't find anything that explains it. Any ideas? Thanks.

    Read the article

  • Getting the constructor of an Interface Type through reflection, is there a better approach than loo

    - by Will Marcouiller
    I have written a generic type: IDirectorySource<T> where T : IDirectoryEntry, which I'm using to manage Active Directory entries through my interfaces objects: IGroup, IOrganizationalUnit, IUser. So that I can write the following: IDirectorySource<IGroup> groups = new DirectorySource<IGroup>(); // Where IGroup implements `IDirectoryEntry`, of course.` foreach (IGroup g in groups.ToList()) { listView1.Items.Add(g.Name).SubItems.Add(g.Description); } From the IDirectorySource<T>.ToList() methods, I use reflection to find out the appropriate constructor for the type parameter T. However, since T is given an interface type, it cannot find any constructor at all! Of course, I have an internal class Group : IGroup which implements the IGroup interface. No matter how hard I have tried, I can't figure out how to get the constructor out of my interface through my implementing class. [DirectorySchemaAttribute("group")] public interface IGroup { } internal class Group : IGroup { internal Group(DirectoryEntry entry) { NativeEntry = entry; Domain = NativeEntry.Path; } // Implementing IGroup interface... } Within the ToList() method of my IDirectorySource<T> interface implementation, I look for the constructor of T as follows: internal class DirectorySource<T> : IDirectorySource<T> { // Implementing properties... // Methods implementations... public IList<T> ToList() { Type t = typeof(T) // Let's assume we're always working with the IGroup interface as T here to keep it simple. // So, my `DirectorySchema` property is already set to "group". // My `DirectorySearcher` is already instantiated here, as I do it within the DirectorySource<T> constructor. Searcher.Filter = string.Format("(&(objectClass={0}))", DirectorySchema) ConstructorInfo ctor = null; ParameterInfo[] params = null; // This is where I get stuck for now... Please see the helper method. GetConstructor(out ctor, out params, new Type() { DirectoryEntry }); SearchResultCollection results = null; try { results = Searcher.FindAll(); } catch (DirectoryServicesCOMException ex) { // Handling exception here... } foreach (SearchResult entry in results) entities.Add(ctor.Invoke(new object() { entry.GetDirectoryEntry() })); return entities; } } private void GetConstructor(out ConstructorInfo constructor, out ParameterInfo[] parameters, Type paramsTypes) { Type t = typeof(T); ConstructorInfo[] ctors = t.GetConstructors(BindingFlags.CreateInstance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.InvokeMethod); bool found = true; foreach (ContructorInfo c in ctors) { parameters = c.GetParameters(); if (parameters.GetLength(0) == paramsTypes.GetLength(0)) { for (int index = 0; index < parameters.GetLength(0); ++index) { if (!(parameters[index].GetType() is paramsTypes[index].GetType())) found = false; } if (found) { constructor = c; return; } } } // Processing constructor not found message here... } My problem is that T will always be an interface, so it never finds a constructor. Is there a better way than looping through all of my assembly types for implementations of my interface? I don't care about rewriting a piece of my code, I want to do it right on the first place so that I won't need to come back again and again and again. EDIT #1 Following Sam's advice, I will for now go with the IName and Name convention. However, is it me or there's some way to improve my code? Thanks! =)

    Read the article

  • actionscript3: reflect-class applied on rotationY

    - by algro
    Hi, I'm using a class which applies a visual reflection-effect to defined movieclips. I use a reflection-class from here: link to source. It works like a charm except when I apply a rotation to the movieclip. In my case the reflection is still visible but only a part of it. What am I doing wrong? How could I pass/include the rotation to the Reflection-Class ? Thanks in advance! This is how you apply the Reflection Class to your movieclip: var ref_mc:MovieClip = new MoviClip(); addChild(ref_mc); var r1:Reflect = new Reflect({mc:ref_mc, alpha:50, ratio:50,distance:0, updateTime:0,reflectionDropoff:1}); Now I apply a rotation to my movieclip: ref_mc.rotationY = 30; And Here the Reflect-Class: package com.pixelfumes.reflect{ import flash.display.MovieClip; import flash.display.DisplayObject; import flash.display.BitmapData; import flash.display.Bitmap; import flash.geom.Matrix; import flash.display.GradientType; import flash.display.SpreadMethod; import flash.utils.setInterval; import flash.utils.clearInterval; public class Reflect extends MovieClip{ //Created By Ben Pritchard of Pixelfumes 2007 //Thanks to Mim, Jasper, Jason Merrill and all the others who //have contributed to the improvement of this class //static var for the version of this class private static var VERSION:String = "4.0"; //reference to the movie clip we are reflecting private var mc:MovieClip; //the BitmapData object that will hold a visual copy of the mc private var mcBMP:BitmapData; //the BitmapData object that will hold the reflected image private var reflectionBMP:Bitmap; //the clip that will act as out gradient mask private var gradientMask_mc:MovieClip; //how often the reflection should update (if it is video or animated) private var updateInt:Number; //the size the reflection is allowed to reflect within private var bounds:Object; //the distance the reflection is vertically from the mc private var distance:Number = 0; function Reflect(args:Object){ /*the args object passes in the following variables /we set the values of our internal vars to math the args*/ //the clip being reflected mc = args.mc; //the alpha level of the reflection clip var alpha:Number = args.alpha/100; //the ratio opaque color used in the gradient mask var ratio:Number = args.ratio; //update time interval var updateTime:Number = args.updateTime; //the distance at which the reflection visually drops off at var reflectionDropoff:Number = args.reflectionDropoff; //the distance the reflection starts from the bottom of the mc var distance:Number = args.distance; //store width and height of the clip var mcHeight = mc.height; var mcWidth = mc.width; //store the bounds of the reflection bounds = new Object(); bounds.width = mcWidth; bounds.height = mcHeight; //create the BitmapData that will hold a snapshot of the movie clip mcBMP = new BitmapData(bounds.width, bounds.height, true, 0xFFFFFF); mcBMP.draw(mc); //create the BitmapData the will hold the reflection reflectionBMP = new Bitmap(mcBMP); //flip the reflection upside down reflectionBMP.scaleY = -1; //move the reflection to the bottom of the movie clip reflectionBMP.y = (bounds.height*2) + distance; //add the reflection to the movie clip's Display Stack var reflectionBMPRef:DisplayObject = mc.addChild(reflectionBMP); reflectionBMPRef.name = "reflectionBMP"; //add a blank movie clip to hold our gradient mask var gradientMaskRef:DisplayObject = mc.addChild(new MovieClip()); gradientMaskRef.name = "gradientMask_mc"; //get a reference to the movie clip - cast the DisplayObject that is returned as a MovieClip gradientMask_mc = mc.getChildByName("gradientMask_mc") as MovieClip; //set the values for the gradient fill var fillType:String = GradientType.LINEAR; var colors:Array = [0xFFFFFF, 0xFFFFFF]; var alphas:Array = [alpha, 0]; var ratios:Array = [0, ratio]; var spreadMethod:String = SpreadMethod.PAD; //create the Matrix and create the gradient box var matr:Matrix = new Matrix(); //set the height of the Matrix used for the gradient mask var matrixHeight:Number; if (reflectionDropoff<=0) { matrixHeight = bounds.height; } else { matrixHeight = bounds.height/reflectionDropoff; } matr.createGradientBox(bounds.width, matrixHeight, (90/180)*Math.PI, 0, 0); //create the gradient fill gradientMask_mc.graphics.beginGradientFill(fillType, colors, alphas, ratios, matr, spreadMethod); gradientMask_mc.graphics.drawRect(0,0,bounds.width,bounds.height); //position the mask over the reflection clip gradientMask_mc.y = mc.getChildByName("reflectionBMP").y - mc.getChildByName("reflectionBMP").height; //cache clip as a bitmap so that the gradient mask will function gradientMask_mc.cacheAsBitmap = true; mc.getChildByName("reflectionBMP").cacheAsBitmap = true; //set the mask for the reflection as the gradient mask mc.getChildByName("reflectionBMP").mask = gradientMask_mc; //if we are updating the reflection for a video or animation do so here if(updateTime > -1){ updateInt = setInterval(update, updateTime, mc); } } public function setBounds(w:Number,h:Number):void{ //allows the user to set the area that the reflection is allowed //this is useful for clips that move within themselves bounds.width = w; bounds.height = h; gradientMask_mc.width = bounds.width; redrawBMP(mc); } public function redrawBMP(mc:MovieClip):void { // redraws the bitmap reflection - Mim Gamiet [2006] mcBMP.dispose(); mcBMP = new BitmapData(bounds.width, bounds.height, true, 0xFFFFFF); mcBMP.draw(mc); } private function update(mc):void { //updates the reflection to visually match the movie clip mcBMP = new BitmapData(bounds.width, bounds.height, true, 0xFFFFFF); mcBMP.draw(mc); reflectionBMP.bitmapData = mcBMP; } public function destroy():void{ //provides a method to remove the reflection mc.removeChild(mc.getChildByName("reflectionBMP")); reflectionBMP = null; mcBMP.dispose(); clearInterval(updateInt); mc.removeChild(mc.getChildByName("gradientMask_mc")); } } }

    Read the article

  • Is it bad practice to use Reflection in Unit testing?

    - by Sebi
    During the last years I always thought that in Java, Reflection is widely used during Unit testing. Since some of the variables/methods which have to be checked are private, it is somehow necessary to read the values of them. I always thought that the Reflection API is also used for this purpose. Last week i had to test some packages and therefore write some JUnit tests. As always i used Reflection to access private fields and methods. But my supervisor who checked the code wasn't really happy with that and told me that the Reflection API wasn't meant to use for such "hacking". Instead he suggested to modifiy the visibility in the production code. Is it really bad practice to use Reflection? I can't really believe that

    Read the article

  • determine complex type from a primitive type using reflection

    - by Nilotpal Das
    I am writing a tool where I need to reflect upon methods and if the parameters of the methods are complex type, then I need to certain type of actions such as instantiating them etc. Now I saw the IsPrimitive property in the Type variable. However, it shows string and decimal as complex types, which technically isn't incorrect. However what I really want is to be able to distinguish developer created class types from system defined data types. Is there any way that I can do this?

    Read the article

  • C# - Recursive / Reflection Property Values

    - by tyndall
    What is the best way to go about this in C#? string propPath = "ShippingInfo.Address.Street"; I'll have a property path like the one above read from a mapping file. I need to be able to ask the Order object what the value of the code below will be. this.ShippingInfo.Address.Street Balancing performance with elegance. All object graph relationships should be one-to-one. Part 2: how hard would it be to add in the capability for it to grab the first one if its a List< or something like it.

    Read the article

  • IEnumerable<T> and reflection

    - by Aren B
    Background Working in .NET 2.0 Here, reflecting lists in general. I was originally using t.IsAssignableFrom(typeof(IEnumerable)) to detect if a Property I was traversing supported the IEnumerable Interface. (And thus I could cast the object to it safely) However this code was not evaluating to True when the object is a BindingList<T>. Next I tried to use t.IsSubclassOf(typeof(IEnumerable)) and didn't have any luck either. Code /// <summary> /// Reflects an enumerable (not a list, bad name should be fixed later maybe?) /// </summary> /// <param name="o">The Object the property resides on.</param> /// <param name="p">The Property We're reflecting on</param> /// <param name="rla">The Attribute tagged to this property</param> public void ReflectList(object o, PropertyInfo p, ReflectedListAttribute rla) { Type t = p.PropertyType; //if (t.IsAssignableFrom(typeof(IEnumerable))) if (t.IsSubclassOf(typeof(IEnumerable))) { IEnumerable e = p.GetValue(o, null) as IEnumerable; int count = 0; if (e != null) { foreach (object lo in e) { if (count >= rla.MaxRows) break; ReflectObject(lo, count); count++; } } } } The Intent I want to basically tag lists i want to reflect through with the ReflectedListAttribute and call this function on the properties that has it. (Already Working) Once inside this function, given the object the property resides on, and the PropertyInfo related, get the value of the property, cast it to an IEnumerable (assuming it's possible) and then iterate through each child and call ReflectObject(...) on the child with the count variable.

    Read the article

  • System.Reflection and InvokeMember, storing type, assembly, and object in a class

    - by Cyclone
    I have tested code to call a method inside of a compiled DLL, and it works. I created a class to store the object, type, and loaded assembly, but something is lost in translation because it is unable to find the member I wish to invoke. If I create a type, object, and assembly, and properly load everything into these and perform InvokeMember on the type, it works just fine. However, when I use the things inside of my class, it throws a MissingMemberException and does not invoke the member, obviously. What am I doing wrong? The member in question is a subroutine which takes one argument, a string. This is quite frustrating. Code being called: Dim MyLoadedAssembly As New LoadedAssembly() MyLoadedAssembly.MyAssembly = Assembly.LoadFrom("display.dll") MyLoadedAssembly.MyObject = MyLoadedAssembly.MyAssembly.CreateInstance("Display.UI.Window") MyLoadedAssembly.MyType = MyLoadedAssembly.MyAssembly.GetType("Display.UI.Window") Dim args() As Object = {"test"} MyLoadedAssembly.InvokeMember("Show", args) Private Class LoadedAssembly Public MyType As Type Public MyObject As Object Public MyAssembly As Assembly Public Function InvokeMember(ByVal name As String, ByVal args() As Object) Return MyType.InvokeMember(name, BindingFlags.Default Or BindingFlags.InvokeMethod Or BindingFlags.GetProperty Or BindingFlags.Instance, Nothing, MyObject, args) End Function End Class Code inside of display.dll: Namespace UI Public Class Window Private wind As New System.Windows.Forms.Form Public FullScreen As Boolean = False Public Overloads Sub Show(ByVal text As String) wind.Show() wind.Text = text End Sub Public Overloads Sub Show() wind.Show() End Sub End Class End Namespace The root namespace for display.dll is Display. Why is my code only working when not within this class? System.MissingMethodException was unhandled Message="Method 'Display.UI.Window.Show' not found." Source="mscorlib" StackTrace: at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams) at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args) at IDE.IDE.LoadedAssembly.InvokeMember(String name, Object[] args) in C:\Documents and Settings\Davey\Desktop\RaptorScript\RaptorScript\RaptorScript\IDE.vb:line 69 at IDE.IDE.IDE_Load(Object sender, EventArgs e) in C:\Documents and Settings\Davey\Desktop\RaptorScript\RaptorScript\RaptorScript\IDE.vb:line 50 at System.EventHandler.Invoke(Object sender, EventArgs e) at System.Windows.Forms.Form.OnLoad(EventArgs e) at System.Windows.Forms.Form.OnCreateControl() at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible) at System.Windows.Forms.Control.CreateControl() at System.Windows.Forms.Control.WmShowWindow(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ScrollableControl.WndProc(Message& m) at System.Windows.Forms.ContainerControl.WndProc(Message& m) at System.Windows.Forms.Form.WmShowWindow(Message& m) at System.Windows.Forms.Form.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.SafeNativeMethods.ShowWindow(HandleRef hWnd, Int32 nCmdShow) at System.Windows.Forms.Control.SetVisibleCore(Boolean value) at System.Windows.Forms.Form.SetVisibleCore(Boolean value) at System.Windows.Forms.Control.set_Visible(Boolean value) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(ApplicationContext context) at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun() at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel() at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine) at IDE.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException:

    Read the article

  • Objective-C runtime reflection (objc_msgSend): does it violate the iPhone Developer License Agreemen

    - by GamingHorror
    Does code like this (potentially) violate the iPhone Developer License Agreement? Class clazz = NSClassFromString(@"WNEntity"); id entity = [clazz entityWithImage:@"Icon.png"]; SEL setPositionSelector = NSSelectorFromString(@"setPosition:"); objc_msgSend(entity, setPositionSelector, CGPointMake(200, 100)); I'm working on code that dynamically allocates classes from XML and calls methods on them via objc_msgSend. It's just very convenient constructing my objects that way but it worries me because i have no idea whether this is ok or violates the License by dynamically executing code or maybe even calling private (?) API functions. They wouldn't be documented if they were private, right? Can someone shed some light on this? Have you had an App approved or rejected using code similar to the above? I'm pretty sure that this is ok but i wan't to hear it from someone else! :)

    Read the article

  • Getting Nested Object Property Value Using Reflection

    - by Kumar
    I have the following two classes: public class Address { public string AddressLine1 { get; set; } public string AddressLine2 { get; set; } public string City { get; set; } public string State { get; set; } public string Zip { get; set; } } public class Employee { public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public Address EmployeeAddress { get; set; } } I have an instance of the employee class as follows: var emp1Address = new Address(); emp1Address.AddressLine1 = "Microsoft Corporation"; emp1Address.AddressLine2 = "One Microsoft Way"; emp1Address.City = "Redmond"; emp1Address.State = "WA"; emp1Address.Zip = "98052-6399"; var emp1 = new Employee(); emp1.FirstName = "Bill"; emp1.LastName = "Gates"; emp1.EmployeeAddress = emp1Address; I have a method which gets the property value based on the property name as follows: public object GetPropertyValue(object obj ,string propertyName) { var objType = obj.GetType(); var prop = objType.GetProperty(propertyName); return prop.GetValue(obj, null); } The above method works fine for calls like GetPropertyValue(emp1, "FirstName") but if I try GetPropertyValue(emp1, "Address.AddressLine1") it throws an exception because objType.GetProperty(propertyName); is not able to locate the nested object property value. Is there a way to fix this?

    Read the article

  • Using reflection to retrieve constructor used to instantiate attribute

    - by summatix
    How can I retrieve information about how an attribute was instantiated? Consider I have the following class definitions: [AttributeUsage(AttributeTargets.Class)] public class ExampleAttribute : Attribute { public ExampleAttribute(string value) { Value = value; } public string Value { get; private set; } } [ExampleAttribute("test")] public class Test { } The new .NET 4.0 MemberInfo.GetCustomAttributesData method: foreach (var attribute in typeof(Test).GetCustomAttributesData()) { Console.WriteLine(attribute); } outputs [Example.ExampleAttribute("test")]. Is there another way to retrieve this same information, preferably using the MemberInfo.GetCustomAttributes method?

    Read the article

  • Using Reflection.Emit to match existing constructor

    - by yodaj007
    First, here is the C# code and the disassembled IL: public class Program<T> { private List<T> _items; public Program(T x, [Microsoft.Scripting.ParamDictionary] Microsoft.Scripting.IAttributesCollection col) { _items = new List<T>(); _items.Add(x); } } Here is the IL of that constructor: .method public hidebysig specialname rtspecialname instance void .ctor(!T x, class [Microsoft.Scripting]Microsoft.Scripting.IAttributesCollection col) cil managed { .param [2] .custom instance void [Microsoft.Scripting]Microsoft.Scripting.ParamDictionaryAttribute::.ctor() = ( 01 00 00 00 ) // Code size 34 (0x22) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: nop IL_0008: ldarg.0 IL_0009: newobj instance void class [mscorlib]System.Collections.Generic.List`1<!T>::.ctor() IL_000e: stfld class [mscorlib]System.Collections.Generic.List`1<!0> class Foo.Program`1<!T>::_items IL_0013: ldarg.0 IL_0014: ldfld class [mscorlib]System.Collections.Generic.List`1<!0> class Foo.Program`1<!T>::_items IL_0019: ldarg.1 IL_001a: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<!T>::Add(!0) IL_001f: nop IL_0020: nop IL_0021: ret } // end of method Program`1::.ctor I am trying to understand the IL code by emitting it myself. This is what I have managed to emit: .method public hidebysig specialname rtspecialname instance void .ctor(!T A_1, class [Microsoft.Scripting]Microsoft.Scripting.IAttributesCollection A_2) cil managed { // Code size 34 (0x22) .maxstack 4 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: newobj instance void class [mscorlib]System.Collections.Generic.List`1<!T>::.ctor() IL_000c: stfld class [mscorlib]System.Collections.Generic.List`1<!0> class MyType<!T>::_items IL_0011: ldarg.0 IL_0012: ldfld class [mscorlib]System.Collections.Generic.List`1<!0> class MyType<!T>::_items IL_0017: ldarg.s A_1 IL_0019: nop IL_001a: nop IL_001b: nop IL_001c: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<!T>::Add(!0) IL_0021: ret } // end of method MyType::.ctor There are a few differences that I just can't figure out. I'm really close... How do I take care of the parameter attribute (ParamDictionaryAttribute)? I can't find a 'custom' opcode. Is the .param [2] important? How do I emit that? Why is the C# code stack size 8, while my emitted version is 4? Is this important?

    Read the article

  • Reflection, get DataAnnotation attributes from buddy class.

    - by Feryt
    Hi. I need to check if property has specific attribute defined in its buddy class: [MetadataType(typeof(Metadata))] public sealed partial class Address { private sealed class Metadata { [Required] public string Address1 { get; set; } [Required] public string Zip { get; set; } } } How to check what properties has defined Required attribute? Thank you.

    Read the article

  • How to work with varargs and reflection

    - by PeterMmm
    Simple question, how make this code working ? public class T { public static void main(String[] args) throws Exception { new T().m(); } public // as mentioned by Bozho void foo(String... s) { System.err.println(s[0]); } void m() throws Exception { String[] a = new String[]{"hello", "kitty"}; System.err.println(a.getClass()); Method m = getClass().getMethod("foo", a.getClass()); m.invoke(this, (Object[]) a); } } Output: class [Ljava.lang.String; Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597)

    Read the article

  • Determining if a .NET type is dynamic (created using Reflection.Emit)

    - by Diego Mijelshon
    While the .NET 4 framework provides the Assembly.IsDynamic method, that's not the case with .NET 2.0/3.5. The use case is simple: for logging purposes, I want to determine the underlying type name of an entity that might be wrapped by a dynamic proxy without having any references to NHibernate or Castle (which know about the proxy) For example, I might have a CatProxYadaYada, but I'm interested in Cat. What's the easiest way to get that type? I was thinking of this skeleton: var type = obj.GetType(); while (IsProxy_Dynamic_Whatever(obj)) type = type.BaseType; return type;

    Read the article

  • Reflection and changing a variables type at runtime?

    - by james-west
    Hi I'm trying to create an object Of a specific type. I've got the following code, but it fails because it can't cast the new table object to the one that is already defined. I need table to start of an IEnumerable type so I can't declare is an object. Public sub getTable(ByVal t as Type) Dim table As Table(Of Object) Dim tableType As Type = GetType(Table(Of )).MakeGenericType(t) table = FormatterServices.GetUninitializedObject(tableType) End sub So in short - is there a way of changing a variable type at runtime? (or a better way of doing what I'm doing) Thanks in advance. James

    Read the article

  • Extension method using Reflection to Sort

    - by Xavier
    I implemented an extension "MyExtensionSortMethod" to sort collections (IEnumerate). This allows me to replace code such as 'entities.OrderBy( ... ).ThenByDescending( ...)' by 'entities.MyExtensionSortMethod()' (no parameter as well). Here is a sample of implementation: //test function function Test(IEnumerable<ClassA> entitiesA,IEnumerable<ClassB> entitiesB ) { //Sort entitiesA , based on ClassA MySort method var aSorted = entitiesA.MyExtensionSortMethod(); //Sort entitiesB , based on ClassB MySort method var bSorted = entitiesB.MyExtensionSortMethod(); } //Class A definition public classA: IMySort<classA> { .... public IEnumerable<classA> MySort(IEnumerable<classA> entities) { return entities.OrderBy( ... ).ThenBy( ...); } } public classB: IMySort<classB> { .... public IEnumerable<classB> MySort(IEnumerable<classB> entities) { return entities.OrderByDescending( ... ).ThenBy( ...).ThenBy( ... ); } } //extension method public static IEnumerable<T> MyExtensionSortMethod<T>(this IEnumerable<T> e) where T : IMySort<T>, new() { //the extension should call MySort of T Type t = typeof(T); var methodInfo = t.GetMethod("MySort"); //invoke MySort var result = methodInfo.Invoke(new T(), new object[] {e}); //Return return (IEnumerable < T >)result; } public interface IMySort<TEntity> where TEntity : class { IEnumerable<TEntity> MySort(IEnumerable<TEntity> entities); } However, it seems a bit complicated compared to what it does so I was wondering if they were another way of doing it?

    Read the article

  • Casting Error with Reflection

    - by Mitchel Sellers
    I have an application that uses plugins that are managed via an interface I then dynamically load the plugin classes and cast them to the interface to work with them. I have the following line of code, assume that IPlugin is my interface. IPlugin _plugin = (IPlugin)Activator.CreateInstance(oInfo.Assembly, oInfo.FullyQualifiedName) This should be pretty simple, create the instance and cast it to the interface. I know that the assembly and fully qualified name values are correct, but I am getting the following exception. Exception= System.InvalidCastException: Unable to cast object of type ‘System.Runtime.Remoting.ObjectHandle’ to type ‘MyNamespace.Components.Integration.IPlugin’. at MyNamespace.Components.Integration.PluginProxy..ctor(Int32 instanceId) Any ideas what could cause this?

    Read the article

  • System.Security.Permissions.SecurityPermission and Reflection on Godaddy

    - by David Murdoch
    I have the following method: public static UserControl LoadControl(string UserControlPath, params object[] constructorParameters) { var p = new Page(); var ctl = p.LoadControl(UserControlPath) as UserControl; // Find the relevant constructor if (ctl != null) { ConstructorInfo constructor = ctl.GetType().BaseType.GetConstructor(constructorParameters.Select(constParam => constParam == null ? "".GetType() : constParam.GetType()).ToArray()); //And then call the relevant constructor if (constructor == null) { throw new MemberAccessException("The requested constructor was not found on : " + ctl.GetType().BaseType.ToString()); } constructor.Invoke(ctl, constructorParameters); } // Finally return the fully initialized UC return ctl; } Which when executed on a Godaddy shared host gives me System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

    Read the article

  • access exception when invoking method of an anonymous class using java reflection

    - by Asaf David
    Hello I'm trying to use an event dispatcher to allow a model to notify subscribed listeners when it changes. the event dispatcher receives a handler class and a method name to call during dispatch. the presenter subscribes to the model changes and provide a Handler implementation to be called on changes. Here's the code (I'm sorry it's a bit long). EventDispacther: package utils; public class EventDispatcher<T> { List<T> listeners; private String methodName; public EventDispatcher(String methodName) { listeners = new ArrayList<T>(); this.methodName = methodName; } public void add(T listener) { listeners.add(listener); } public void dispatch() { for (T listener : listeners) { try { Method method = listener.getClass().getMethod(methodName); method.invoke(listener); } catch (Exception e) { System.out.println(e.getMessage()); } } } } Model: package model; public class Model { private EventDispatcher<ModelChangedHandler> dispatcher; public Model() { dispatcher = new EventDispatcher<ModelChangedHandler>("modelChanged"); } public void whenModelChange(ModelChangedHandler handler) { dispatcher.add(handler); } public void change() { dispatcher.dispatch(); } } ModelChangedHandler: package model; public interface ModelChangedHandler { void modelChanged(); } Presenter: package presenter; public class Presenter { private final Model model; public Presenter(Model model) { this.model = model; this.model.whenModelChange(new ModelChangedHandler() { @Override public void modelChanged() { System.out.println("model changed"); } }); } } Main: package main; public class Main { public static void main(String[] args) { Model model = new Model(); Presenter presenter = new Presenter(model); model.change(); } } Now, I except to get the "model changed" message. However, I'm getting an java.lang.IllegalAccessException: Class utils.EventDispatcher can not access a member of class presenter.Presenter$1 with modifiers "public". I understand that the class to blame is the anonymous class i created inside the presenter, however I don't know how to make it any more 'public' than it currently is. If i replace it with a named nested class it seem to work. It also works if the Presenter and the EventDispatcher are in the same package, but I can't allow that (several presenters in different packages should use the EventDispatcher) any ideas?

    Read the article

  • Trouble Emitting Object Array using Reflection.Emit

    - by JoeGeeky
    I am trying to Emit what I thought would be a simple object array that would result in code similar to the below example object[] parameters = new object[] { a, b, }; When I write the above code in C# using VS, I get the following IL. As expected this works. .locals init ( [0] object[] parameters, [1] object[] CS$0$0000) However, when I try and Emit IL directly, I only ever get a one index init array. Can someone help tell me where I've gone wrong here? Here is the Emit code I'm using: int arraySize = 2; LocalBuilder paramValues = ilGenerator.DeclareLocal(typeof(object[])); paramValues.SetLocalSymInfo("parameters"); ilGenerator.Emit(OpCodes.Ldc_I4_S, arraySize); ilGenerator.Emit(OpCodes.Newarr, typeof(object)); ilGenerator.Emit(OpCodes.Stloc, paramValues); Here is the resulting IL: .locals init ( [0] object[] objArray) The rest of the resulting IL is identical between the two solutions, but for some reason the .locals init is different.

    Read the article

  • BindingList<T> and reflection!

    - by Aren B
    Background Working in .NET 2.0 Here, reflecting lists in general. I was originally using t.IsAssignableFrom(typeof(IEnumerable)) to detect if a Property I was traversing supported the IEnumerable Interface. (And thus I could cast the object to it safely) However this code was not evaluating to True when the object is a BindingList<T>. Next I tried to use t.IsSubclassOf(typeof(IEnumerable)) and didn't have any luck either. Code /// <summary> /// Reflects an enumerable (not a list, bad name should be fixed later maybe?) /// </summary> /// <param name="o">The Object the property resides on.</param> /// <param name="p">The Property We're reflecting on</param> /// <param name="rla">The Attribute tagged to this property</param> public void ReflectList(object o, PropertyInfo p, ReflectedListAttribute rla) { Type t = p.PropertyType; //if (t.IsAssignableFrom(typeof(IEnumerable))) if (t.IsSubclassOf(typeof(IEnumerable))) { IEnumerable e = p.GetValue(o, null) as IEnumerable; int count = 0; if (e != null) { foreach (object lo in e) { if (count >= rla.MaxRows) break; ReflectObject(lo, count); count++; } } } } The Intent I want to basically tag lists i want to reflect through with the ReflectedListAttribute and call this function on the properties that has it. (Already Working) Once inside this function, given the object the property resides on, and the PropertyInfo related, get the value of the property, cast it to an IEnumerable (assuming it's possible) and then iterate through each child and call ReflectObject(...) on the child with the count variable.

    Read the article

  • Loading remote assembly from the webservice with reflection

    - by Myat Htut
    I am using Assembly.LoadFrom within a web service to load assemblies from a web site. but the problem is it is in the virutal directory and the server.mappath parses the url like \share\mydll.dll and loadform method failed. Is there anyway to reference dll from the remote location? I've tried passing the url (http:\localhost\downloadable\mydll.dll) and again it got "Could not load file or assembly 'http:\localhost\downloadable\mydll.dll' or one of its dependencies. HTTP download of assemblies has been disabled for this appdomain. (Exception from HRESULT: 0x80131048)"

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >