dimanche 31 janvier 2016

JavaFX TreeView: Access list of TreeCells

I am trying to get a list of the currently existing TreeCells out of my TreeView. My current attempt looks like this:

private Set<MyTreeCell> getMyTreeCells(){
    try {
        @SuppressWarnings("unchecked")
        Field f = ((VirtualContainerBase<TreeView<myNode>, TreeViewBehavior<myNode>, MyTreeCell>) myTreeView.skinProperty().get()).getClass().getDeclaredField("flow");
        f.setAccessible(true);
        @SuppressWarnings("unchecked")
        Field g = ((VirtualFlow<MyTreeCell>) f.get(((VirtualContainerBase<TreeView<myNode>, TreeViewBehavior<myNode>, ProofTreeCell>) proofTreeView.skinProperty().get()))).getClass().getDeclaredField("cells");
        g.setAccessible(true);
        @SuppressWarnings("unchecked")
        ArrayLinkedList<MyTreeCell> l = (ArrayLinkedList<MyTreeCell>) g.get(((VirtualFlow<MyTreeCell>) f.get(((TreeViewSkin<myNode>) myTreeView.skinProperty().get()))));
        Set<myTreeCell> s = new HashSet<>();
        s.addAll(l);
        return s;
    }
    catch (NoSuchFieldException e) {
        e.printStackTrace();
    }
    catch (SecurityException e) {
        e.printStackTrace();
    }
    catch (IllegalArgumentException e) {
        e.printStackTrace();
    }
    catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return null;
}

Unfortunately it throws java.lang.NoSuchFieldException: flow. But why? Clearly the Field flow exists in the Class VirtualContainerBase.

Please note that I only wrote this for fun, and not to actually be used in productive code. I already have a cleaner solution for the problem.





android - performance impact of using Java proxy on network calls

I am making network calls using retrofit but i suppose it could be any networking api. I will filter out the calls by using a java proxy. What i am trying to do here is everytime developer makes a network call i want it to run through a java proxy so i can check authorization and if the correct info is present.
so it sort of mimics AOP in a way.

Now onto my question, realzing that java proxy utilizes reflection, and knowing that reflection slows down android, Do you all think it would be a large overhead to run the networking calls though a java proxy ? or is the performance impact minimal ?





Confused in Reflection API concepts in JAVA [duplicate]

This question already has an answer here:

I have just started learning Java. Sorry for asking silly doubts.

First of all, what is the use of Reflection API? I heard if we have same method and variable name then we use reflection API. I am confused.

Below program 1 and program 2 brings the same output. Then why do we use that. Kindly explain program 1 line 9 and 10. Thanks for the support friends.

Program 1:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Practice {

    public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        String x="SampleTest";
    //Explain below 2 lines please
        Method method=Practice.class.getMethod(x, String.class);
        method.invoke(method, "Hello");


    }

    public static void SampleTest(String x){
        System.out.println("In Sample Test--"+x);

    }

}

Program 2:

public class Practice {

    public static void main(String[] args){
        String x="SampleTest";

        SampleTest("Hello");


    }

    public static void SampleTest(String x){
        System.out.println("In Sample Test--"+x);

    }

}

Output for both the program is In Sample Test--Hello

Thanks once again





Swift reflection capabilities

Given a constructor such as:

required init (pTableName : String, pRecordKey : String, pStartAtRecord : Int){
    parameters.append(ChildElement(identifier: "pTableName", value: pTableName))
    parameters.append(ChildElement(identifier: "pRecordKey", value: pRecordKey))
    parameters.append(ChildElement(identifier: "pStartAtRecord", value: pStartAtRecord))
}

I want to extract the names of all argument variables such as pTableName, pRecordKey and so forth. Why exactly? First of all, I might have more then 30 different classes having different constructor arguments and passing those into the parameters array. Secondly, all of the constructors have a different signature, but mainly they do the same thing - create ChildElements and append them to the list of parameters - which afterwards constitutes a SOAP request for the web service.

By having the ability of getting the variable names (e.g. pTableName should produce "pTableName" : String), I would like to accomplish the following:

required init (pTableName : String, pRecordKey : String, pStartAtRecord : Int){
    appendToParameters([pTableName, pRecordKey, pStartAtRecord])
} 

which would then for each element of the array produce:

parameters.append(ChildElement(identifier: Reflection.getName(var), value : var))

However, in Swift there is no possibility of getting the variable name using reflection and macros such as the one used in Objective-C:

#define variableName(var) [NSString stringWithFormat:@"%s",#var]

If I try to use the macro via an Objective C method, and then applied in Swift:

-(NSString *)getVarName:(id)var {
    return variableName(var)
}

then of course the return NSString value will be equal to "var".

In general, how can I use reflection in Swift in order to obtain, as in this example the name of a argument variable? So far, I've checked numerous resources, starting from the Apple's documentation onto the runtime API and similar, but unfortunately, none of the pre-defined runtime methods seem to be applicable in Swift.

Any piece of advice?

Thanks in advance!





C# Reflection issue - second method call

I'm trying to dynamically wrap c++ function in c# using reflection. Everything works fine. But when I try to add another call after c++ function, it doesn't call it.

private static Delegate GetDebugDelegate(IntPtr ptr, Type delType)
{
    MethodInfo info = delType.GetMethod("Invoke");
    Type returnType = info.ReturnType;
    ParameterInfo[] parameters = info.GetParameters();
    Type[] parameterTypes = parameters.Select(i => i.ParameterType).ToArray();
    Type[] parameterTypesPointers = parameterTypes.Select(i => i.GetPointerType()).ToArray();

    var dm = new DynamicMethod($"{delType.Name}Calli", returnType, parameterTypes, delType, true);

    ILGenerator il = dm.GetILGenerator();

    for (int i = 0; i < parameterTypesPointers.Length; i++)
        il.Emit(OpCodes.Ldarg, i);

    if (IntPtr.Size == 4)
        il.Emit(OpCodes.Ldc_I4, ptr.ToInt32());
    else if (IntPtr.Size == 8)
        il.Emit(OpCodes.Ldc_I8, ptr.ToInt64());
    else
        throw new PlatformNotSupportedException();

    il.EmitCalli(OpCodes.Calli, CallingConvention.Cdecl, returnType.GetPointerType(), parameterTypesPointers);
    il.Emit(OpCodes.Ret);

    //This does not gets called
    Action action = () =>
    {
        Console.WriteLine("test");
    };
    il.Emit(OpCodes.Call, action.Method);
    il.Emit(OpCodes.Ret);

    return dm.CreateDelegate(delType);
}

Here's some decompiled il for delegate 'public delegate uint Temp(int type);'

    .method public static uint32 TempMethod(int32) cil managed
    {
        .maxstack 2
        L_0000: ldarg A_0
        L_0004: nop 
        L_0005: nop 
        L_0006: ldc.i4 0x5aa166c0
        L_000b: calli method unmanaged cdecl uint32 *(int32)
        L_0010: ret 
        L_0011: call instance void [Test]Test.TestClass/<>c::<TestSave>b__4896_0()
        L_0016: ret 
    }

My best guess is that i have to store return value, call second method and then return, but i dont know how.





samedi 30 janvier 2016

C# Type GetMethod() where parameter order is random

I am trying to get a method of an object, and it works fine if the parameters of the method match the order of the list of parameters I provide. I am trying to avoid this, so I do not have to worry about the order of parameter types in methods across different files. Here is what I have

MethodInfo mi = stateType.GetMethod("Entrance", typesToUse.ToArray());

In my test case, typesToUse only contains two instances of unique interfaces, IClass1 and IClass2 in that order.

If the Entrance method is : Entrance(IClass1 c1, IClass2 c2), it picks this method up. Although, if its Entrance(IClass2 c2, IClass1 c1), it will not and mi will then be null.

Is there a way around this? Perhaps a way to tell GetMethod to ignore parameter order?

Any help is appreciated and thank you.





Android: How to access android.webkit.HTML5VideoViewProxy in Android API level 19+

Starting from API level 19, Android introduced a new version of WebView that is based on Chromium. in lower APIs I'm able to have access to android.webkit.HTML5VideoView and android.webkit.HTML5VideoViewProxy classes using reflection, but now Chromium (http://ift.tt/1PpsQV8) doesn't contain any of them and I get java.lang.ClassNotFoundException. Or maybe I don't understand this new WebView upgrade correctly, please help me to know whether it is possible to access the aforementioned classes in API 19+.

If it is not possible to access the classes in API 19+, then is it possible somehow integrate the necessary framework (e.g. http://ift.tt/1QzuW3F) to an android project in order to be able to use them? Great thanks in advance. Looking forward to your replies.





How to access declaring type for static member in C#

I have a scenario in which i need to access declaring type of an static property.the scenario is as following :

public static class FOO{
     public static SomeType Bar{get;set;}
}

public static class BAZ{
   public static void SomeMethod(SomeType p){
       //here i wanna get type of container of 'p' which should be FOO
   }
}    

 BAZ.SomeMethod(FOO.Bar);

but when i call p.GetType().DeclaringType i get null value, any suggestions?





C# get generic parameter name using reflection

say that I have a C# class like this:

class MyClass<Tkey,Tvalue>{}

How do I get "Tkey" and "Tvalue" from given Type instance? I need the parameter name, not Type.





vendredi 29 janvier 2016

See if a type variable represents a superclass of a given Class

Given a class

class EnvironmentHolder<V> {
    protected Map<String,V> environment;

    // Get the Type of V using Google's Guava library; this part
    // works okay
    protected final Type VALUE_TYPE = new TypeToken<V>() {}.getType();

    ...

    public void importEnvironment(Class aClass) {

    }
}

where V is some reference type, I'm trying to collect all of the static members of aClass which are "assignable to" a class of type V — that is, those which are subclasses, implementations of, or the same class as V.

How do I do this? I'd like to use the following:

for (Field field : aClass.getFields()) {
    ((Class) V).isAssignableFrom(field.getType())
}

I see that Class is indeed an implementer of Type, but I'm not sure how to perform a cast safely. (Type also encompasses non-reference types, which are not Classes.)

NB: Please don't say, "Type erasure preludes doing this at runtime" until you have thought it through. A fair number of questions have that as a virtually automatic response, which would seem to imply that a reflection API is impossible to implement in Java.

Thanks!





Invoke Superclass method via reflection

I'm using an Eclipse based software which allows to create applications and automatically provides a default user interface. I'm trying to modify this interface (e.g. change buttons icon, foreground color etc...) but unfortunately I cannot modify the source code, so I'm trying to do it via java reflections. I can anyway take vision of the compiled jar files thanks to softwares like JD-GUI, but I'd prefer not to modify and recompile the jars. The problem is that this interface is built through customized classes which extends Swing components and, looking into the jar files, I found some annoying tricks implemented. Follows an example:

final class MyToggleButton extends JToggleButton{
    MyToggleButton (ImageIcon defaultIcon){
        super.setIcon(defaultIcon);
    }
    @Override
    public void setIcon(Icon icon){}
}

With classes built in this way, if I invoke the setIcon() method on an instance of MyToggleButton, it doesn't make effect, since the override method has no code inside (I think). So I cannot change the icon they set by default on the specific button.

Does anyone know a way to overcome this issue? Thanks in advance for any help.

P.S. I'm not a javer but I'm quite familiar with reflections.





Programatically fetching Singleton instances that implement a common interface

I'm working with some legacy ASP.NET MVC code that has a number of fairly detailed XML configuration files. Each file is loaded into an object representation defined as a Singleton class at runtime.

Rather than having to refer to each singleton specifically by class type I'd like a way of obtaining each of them programatically and then being able to access properties and methods common to them all based on an interface which they must all implement.

So for example, these singletons all have a string instance property called "Filename" that is the name of the config file they represent. I'd therefore like to automatically generate a list of these filenames without manually having to refer to each singleton to obtain the property and therefore I need to programatically fetch all singleton instances implementing the interface that specifies the Filename property and then fetch that property value by casting to that interface.

Is this possible?





Overriding values c#

I have a situation where in I have 3 classes like below:

public class A
{
    public int Id { get; set; }
    public int BranchId { get; set; }
    public int LocationId { get; set; }
    public int DepID { get; set; }
    public int Age { get; set; }
    public string Name { get; set; }
}

public class B
{
    public int LocationId { get; set; }
    public int DepID { get; set; }
    public int Age { get; set; }
    public string Name { get; set; }
}  

public class C
{
    public int Age { get; set; }
    public string Name { get; set; }
}

From the above classes we see that there are few common properties b/w 3 classes.

I have a situation where I have to create a final output by combining the values from 3 classes and overriding them when there and values in lower classes.

For ex:-

Consider property Age which is all 3 classes A, B and C but if the value of it in C is not null while merging the value in class C takes priority, and this will be the case for all the properties.

I have already achieved this using Reflection, by reading the values from the instance of all the 3 classes I have by using .GetType() and .GetProperties() methods which are part of System.Reflection library.

With the current Reflection based approach I will able to handle any addition of properties in any of the classes.

But I have read that the Reflection is bad on performance.

So is there a better way of doing this?





jeudi 28 janvier 2016

Get generic type of a class implementing a generic interface

I have an Interface

public interface IConfigDao<T> {}

I have a class which implements this interface,

public class ConfigDaoJedisImpl<T> implements IConfigDao<T> {}

I am instantiating the class a follows,

IConfigDao<UserLimitConfig> configDao = new ConfigDaoJedisImpl<>();

Now in the constructor of ConfigDaoJedisImpl I want to get the class object of UserLimitConfig (It is the generic type with which the interface was instantiated). Is this possible?





How to call the hidden Android method getTotalUss() using Java reflection?

I am using Android Studio 1.5.1 targeting Android API 18 (before Android KitKat 4.4, so I’m dealing with Dalvik, not ART runtime).

My questions are:

  1. How to call the hidden Android method getTotalUss() using Java reflection?
  2. If not possible, how to find the current process USS (Unique Set Size) memory programmatically?

I am trying to use the code below to do that but I am getting a compiler error "Unexpected token" at the statement labelled //ERROR! below in the code.

    ActivityManager activityManager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
    activityManager.getMemoryInfo(memoryInfo);

    List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();

    Map<Integer, String> pidMap = new TreeMap<Integer, String>();
    for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses)
    {
        pidMap.put(runningAppProcessInfo.pid, runningAppProcessInfo.processName);
    }

    Collection<Integer> keys = pidMap.keySet();
    int id= android.os.Process.myPid();
    for(int key : keys)
    {
        if (key != id) continue;
        int pids[] = new int[1];
        int Uss;
        pids[0] = key;
        android.os.Debug.MemoryInfo[] memoryInfoArray = activityManager.getProcessMemoryInfo(pids);
        for(android.os.Debug.MemoryInfo pidMemoryInfo: memoryInfoArray)
        {
            try {

                Class c;
                c = Class.forName("android.app.ActivityManager");
                Method m = c.getMethod("getTotalUss", null);
                Uss = m.invoke(null,int); //             << == ERROR!
            } catch (ClassNotFoundException e) {
            }
            catch (NoSuchMethodException e) {
            }
            catch (IllegalAccessException e) {
            }

            System.out.println("** Uss =  " +  Uss);





reflect: Is it possible to get the underlying typed type information?

I'm porting a program from go/ast to reflect. In order to pass the tests I need to get not only the top type information but also the underlying type if the underlying type is not built-in.

In the example below, is it possible for a program to know that the underlying type of main.T is main.TT?

package main

import "fmt"
import "reflect"

func main() {
    type TT int
    type T TT

    x := T(0)
    fmt.Println(reflect.TypeOf(x))
}

Output:

 main.T





Determine if a type is convertible to IDictionary

Let's say we have a type that implements IDictionary<string, string>. It's called MyStringDictionary.

I'm doing some property/field/method reflection and would like to know if the member is a type that I can convert to an IDictionary<string, object>.

I know that typeof(IDictionary<string, string>).IsAssignableFrom(typeof(MyStringDictionary)) will be true since both generic parameters match. However, I won't be doing direct assignment to <string, string> but instead will be converting to <string, object>, something like this:

public class MyStringDictionary : IDictionary<string, string> {
   // Notice that the class itself has no generic type arguments!
}

MyStringDictionary myStringDictionary = GetBigDictionary();
IDictionary<string, object> = myStringDictionary
   .ToDictionary(kvp => kvp.Key, kvp => (object) kvp.Value);

How can I determine that this conversion is possible?

I was thinking that I can look to see if it implements IEnumerable<KeyValuePair<,>>, but again I'm stymied by the fact that I don't know the type argument of the Value, and don't need to know it because it will just be boxed to object.





How to reflect dynamic method name of an object in Golang

example

router.Get(path, handler) // works fine

methodStr = "Get"    
router.methodStr(path, handler) // error

funcs := map[string]func(){"methodStr": "Get"}
router.funcs["methodStr"](path, handler) // error

reflect.ValueOf(router).MethodByName("Get").Call([]reflect.Value{}) // error

I am getting method names as strings. How to call the router object methods with string names





How to invoke Generic Method with Generic Parameter in C#?

I would like to know how to use reflection in C# to call the following method :

public static List<T> GetAllWithChildren<T>
    (this SQLiteConnection conn, Expression<Func<T, bool>> filter = null, bool recursive = false) 
    where T
    #if USING_MVVMCROSS: new() #else : class #endif
    {
    }

My current code is:

MethodInfo methodInfo = typeof(ReadOperations).GetMethod("GetWithChildren", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);
Type predicateType = predicate.GetType();
MethodInfo genericMethod = methodInfo.MakeGenericMethod(predicateType);
Type[] genericArgumentsType = genericMethod.GetGenericArguments();
Debug.WriteLine("Arguments Number:" + genericArgumentsType.Count());
int count = 0;
foreach (Type ga in genericArgumentsType)
{
    Console.WriteLine(count++ + " " + ga.GetType());
}
Object[] genericArguments = { conn, predicate, true };
genericMethod.Invoke(conn, genericArguments);

The number of arguments returned is 1 ... that it's wrong but I don't know why the system return to me this number.

The invoke method fail with a wrong number of arguments.

Any help will be welcome!





Dynamically load assembly from local file and run with restricted privileges

What I need to do is : Read a local C# text file, execute a method from that. This is what I'm doing.

  1. Read all text from the file
  2. Compile into a local x.dll with CSharpCodeProvider
  3. Load the dll with Assembly.LoadFrom()
  4. Then execute the method with GetType().GetMethod().Invoke()

It works fine. Now, I want to run this code securely, i.e. restrict this code from accessing the file system, network etc. Basically, I need to run this with minimal privileges.

I tried the code from Restrict plugin access to file system and network via appdomain (answer by @Babar), but still not working as expected. The code in the text file is still able to access file system.

What I'm missing here? Any other way to make it work?





Unable to detect class level custom annotation in Spring AOP

I am trying to intercept classes in Spring with following settings

Interceptor

@Aspect
@Component
public class MyInterceptor {

    @Around("execution(* com.example.services..*(..))")
    public Object intercept(ProceedingJoinPoint pjp) throws Throwable {
        if (pjp.getTarget() != null && pjp.getTarget().getClass().getAnnotation(MyAnnotation.class) != null) {
            System.out.println("Yes annotation present");
        } else {
            System.out.println("Annotation not present");
        }

        return = pjp.proceed();
    }   
}

and the class being intercepted is as follows

@Component
@MyAnnotation
public class MyAlert implements IAlert {

}

Every thing is working fine until and unless I make the following changes

@Configuration
@PropertySource(value = { "file:${catalina.home}/conf/my.properties" })
@Component
@MyAnnotation
public class MyAlert implements IAlert {
    @Autowired
    private Environment environment;
} 

I wanted to read properties located in conf folder of tomcat7, after making these changes my interceptor is unable to read my custom annotation @MyAnnotation. it says (custom message written in interceptor)

Annotation not present

and here is custom annotation

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

}

I really want the class should be intercepted and annotation must be detected on class if it is annotated. I also want to read properties from conf folder in that intercepted class.





how to implement interface through reflection in c#

My Code is like
Assembly assemblyX = Assembly.Load("xyz.abc.DataObjects"); Type t = assemblyX.GetType("xyz.abc.DataObjects." + ValueStr); Everything is good till this point. Now i want to implement interface on 't' which is 'xDataObject' and require a generic i.e "CurrentDataObject" in < > operators like xDataObject<CurrentDataObject>. This interface consists many member functions, which I want to use in reflection. According to my research on it, the problem is in this next line, which works fine until we don't need interface i.e
Object objClass = (Object)Activator.CreateInstance(t);
Help me. I'm new to Generics. Thank you.





How to reflectively invoke PrepareStatement.set

I'm trying to reflectively invoke the setXxx method of com.mysql.jdbc.PreparedStatement using the following code.

String type = getJavaTypeFromMySqlType(); // this is "String"
Class clazz = type.getClass(); // This is java.lang.String
Method method = com.mysql.jdbc.PreparedStatement.class.getDeclaredMethod("set"+type, int.class, clazz);
method.invoke(cnt, clazz.cast(pair.getValue())); 

The last line throws

java reflection object is not an instance of declaring class

What am I missing here?





mercredi 27 janvier 2016

Filter deep list fields using metadata

Situation

In my application I have a bunch of classes and some of them have translated versions.

Example:

There is a class News having a list of NewsTranslation. NewsTranslations' fields are language and title.

I also have an Event and EventTranslation (with language field) and News has a field of Event type.

Classes(fields) summary:

  • News(Event, NewsTranslations) implements Multilingual
  • Event(EventTranslations) implements Miltilingual
  • NewsTranslation(language, title) implements Translation
  • EventTranslation(language, titie) implements Translation

What i want to do is

create a method that will take News and language String as arguments and filter the News object deeply so that every translation list will be filtered for language.

I need a generic solution that will work for other scenarios by traversing the object deeply and filter all Translation list.

What i tried/thought of

I know how to do it the easy way, for example using reflection to recursively search all fields for appropriate type, but i don't think it's the optimal one.

I was thinking about using annotation on class to specify paths to translations, and then get the values with reflections. Example:

@TranslationPaths({
@TranslationPath("newsTranslations"),
@TranslationPath("event.eventTranslations")})
public class News {
...
}

But maybe you can suggest a better solution? Maybe a library that does that kind of stuff?





Is there an Annotation for member/method to be used by reflection?

I have a method that is invoked by the same class using reflection.

I'd like to make the method private, but get a warning by the IDE that the method is not being used.

Well, it is being used - using reflection.

What annotations are there to indicate that a member/method is being used by reflection?





How to integrate the reflection library into a Java Project

Regarding this Post: Can you find all classes in a package using reflection? In the answer section, someone said that loading all classes of a package can be done with the following reflection library: http://ift.tt/Ofz26b.

I downloaded and unzipped this library. But it only contains .java files and I do not know, how I can use the classes and the methods of this library. Normally, there is a .jar file which I can import... But in this folder there isn't!

So please can you tell me how I can import the library and make use of its classes and methods?

Thanks a lot

Alex





Pass object at runtime using a string

There is loads of stuff on here about reflection but I can't seem to get my head around my specific problem.

My Classes:

public class Box
{
   public string Name { get; set; }
   public int Size { get; set; }
}

public class Pallet
{
   public Box b1 = new Box();
   public Box b2 = new Box();
}

The Code for Creating the object:

Pallet p = new Pallet();
p.b1.Size = 5;
p.b2.Size = 10;

The code to display the size of a chosen box:

MessageBox.Show(p.b1.Size.ToString());

I would like to select the box at runtime using a string. i.e.

string boxid = "b1";
Object myObj = p. + boxid;          

MessageBox.Show(myObj.Size.ToString());

Obviously this code will not work. What would be the correct way to get the value of the chosen box in this case 5?





mardi 26 janvier 2016

C# Reflection: "Pointer" to a value-type

Short description

I want to know if there is a .NET feature letting me manipulate a value type obtained by reflection. So when calling PropertyInfo.getValue(...) on a value type property I want to not get a copy, but the original object and manipulate it.

I am NOT allowed to use unsafe pointers.

Long description

This requirement arose because I am implementing a webservice letting me manipulate a Unity3d scene graph.

The scene graph might have the following structure

  • GameObject 1
    • Vector 1.2
  • GameObject 2
    • Struct 2.1
    • Vector 2.2

A client can query the following URI:

GET http://.../GameObject2/StructProperty/someProperty

This works, as it is as simple as traversing the hierarchy via reflection, searching for the property by name (e.g. Struct or Vector) and calling getValue on the corresponding PropertyInfo, returning this to the client.

But a client can also query:

POST http://.../GameObject2/VectorProperty/xProperty with e.g. 5.4 as the entity body. The x property of the Vector should then be set to 5.4

What I am doing at the moment is traversing the graph forward (like with GET) till I find the Vector object. Then I am doing a recursive setValue UNTIL I am doing the setValue on a reference type e.g.

object2.setValue(Vector.setValue(5.4));

(for simplicity I am omitting the PropertyInfo part. Assume it is there)

So I must be able to query an arbitrary object hierarchy containing both value types and reference types. Is there a better way for what I am doing?





Create an object with method using c# reflection

I have a problem where I need to create a tfs version control server object using reflection after loading the dll in c#. I'm having trouble initializing it in reflection however as it has no constructors. Without reflection you normally create the object using the getService method in a team project collection object. Here is my code:

namespace SendFiletoTFS
{
    class Program
    {
        static void Main(string[] args)
        {

            String tfsuri = @"uri";
            NetworkCredential cred = new NetworkCredential("user", "password", "domain");

            // Load in the assemblies Microsoft.TeamFoundation.Client.dll and Microsoft.TeamFoundation.VersionControl.Client.dll
            Assembly tfsclient = Assembly.LoadFrom(@"C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.TeamFoundation.Client.dll");
            Assembly versioncontrol = Assembly.LoadFrom(@"C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.TeamFoundation.VersionControl.Client.dll");

            // Create Team Project Collection
            Type tpcclass = tfsclient.GetType(@"Microsoft.TeamFoundation.Client.TfsTeamProjectCollection");
            // The 'getService' method.
            MethodInfo getService = tpcclass.GetMethods()[32];
            object tpc = Activator.CreateInstance(tpcclass, new object[] { new Uri(tfsuri), cred });


            Type VersionControlServerClass = versioncontrol.GetType(@"Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer");

            // Code I'm trying to emulate in reflection, this is how I would normally do it without reflection.
            //VersionControlServer versionControl = tpc.GetService<VersionControlServer>();

            // Create VersionControlServer Class. This line will not work and give a no constructor found exception.
            object vcs = Activator.CreateInstance(VersionControlServerClass, new object[] { tpc });

           //How do I create the vcs object ?
        }
    }
}

Is there some way I can create this version control server object using the getService method in the team project collection class?

Any help would be greatly appreciated.





Attribute.GetCustomAttributes() not getting my custom attribute

This is my setup, I have three projects on the solution: Project A : class library for MVC Project B : MVC website (main) Project C : MVC website (area only)

C is deployed on B as an Area and that work really well. B has a reference to both A and C. C has a reference to A.

In class library A I defined the following attribute (error checking removed):

 [AttributeUsage(AttributeTargets.Method)]
 public class MyAttribute : Attribute {
     public string Name = "";
     public MyAttribute(string s)
     {
         Name = s;
     }
 }

Then in project C (same as in project B) I have some classes where SOME methods are decorated with my custom attribute:

 public class SomeController : Controller, ISomethingSpecial
 {
      [MyAttribute("test")]
      public ActionResult Index() {
          return View();
      }
 }

The custom attribute is applied to the action methods as indicated by the attribute usage constraint.

For the sake of testing I put this code in one of the action methods of the controller:

IEnumerable<System.Type> all =
        System.Web.Compilation.BuildManager.GetReferencedAssemblies().Cast<System.Reflection.Assembly>().SelectMany(a => a.GetTypes()).Where(type => typeof(ISomethingSpecial).IsAssignableFrom(type)).ToList();

foreach (Type t in all) {
    if (!t.Equals(typeof(ISomethingSpecial))) {
       MyAttribute[] sea = (MyAttribute[])Attribute.GetCustomAttributes(t, typeof(MyAttribute));
    }
}

When I debug the code I get to the iteration where the examined type t is SomeController which has some methods decorated with my custom attribute. But I see that the returned list of GetCustomAttributes has zero elements!

Before somebody asks what I basically want to achieve is obtain a list of assemblies of the web application that implement the ISomethingSpecial interface and from that list of candidates I want to extract the names of the methods (MVC action methods) that are decorated with my custom attribute MyAttribute.





Invoke Method using Reflection

I've got two classes. I want to invoke the "saveq" method in the QuestionPicker.class. This method saves some Strings into the SharedPreferences. I want to invoke that method from another class, that is called Questions. I want to invoke the method using reflection, but my code doesn't work.. I think the problem is somewhere at the reflection, but I can't see it. Can someone see the problem? Thanks

Here is the QuestionPicker.class

public class QuestionPicker {

    public void saveq() {

        // MyApplication Class calls Context
        Context context = MyApplication.getAppContext();

        // Values to save
        String Q1 = "SomeQuestion";
        String Q2 = "SomeOtherQuestion";
        String Q3 = "AndEvenMoreQuestions";

        // Save the Strings to SharedPreferences
        SharedPreferences.Editor editor = context.getSharedPreferences("QuestionsSaver", 0).edit();

        editor.putString("Q1", Q1);
        editor.putString("Q2", Q2);
        editor.putString("Q3", Q3);

        editor.apply();

    }
}

And here is the Questions.class

public class Questions extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_questions);

        // storing string resources into Array
        String[] subjects = getResources().getStringArray(R.array.subjects);
        ListView lv = (ListView) findViewById(R.id.listView);
        // Binding resources Array to ListAdapter
        ListAdapter adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, subjects);
        lv.setAdapter(adapter);


        // listening to single list item on click
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

          // Invoke the saving Method  
                try {
                    Class cls = Class.forName("com.test.QuestionsPicker");
                    Object obj = cls.newInstance();
                    Method method = cls.getMethod("saveq");
                    method.invoke(obj);

                } catch(Exception ex){
                    ex.printStackTrace();
                }



            }
        });
    }
}





Is it normal that TypeTag object takes more than a second to initialize?

TypeTag when first referenced in code takes more than a second on my computer to be loaded and initialized.

The time can be measured by invoking the following code:

import scala.reflect.runtime.universe.TypeTag

object Boot extends App {
  val start = System.currentTimeMillis()
  TypeTag
  println(System.currentTimeMillis() - start)
}

Is it normal? If yes, what is the best way to initialize this object, should I reference it in some startup initialization code of my application? I've already experienced some vague timeouts because of this object being referenced for the first time in the application inner code.

I'm using scala 2.11.7.





How do I get array item type in TypeScript using the Reflection API?

I have the following little class in TypeScript, with some public fields decorated:

class Company {
    @dataMember
    public name: string;

    @dataMember
    public people: Person[];
}

class Person {
    // ...
}

Using the experimental Reflection API, I can determine the types of Company properties name and people: they are String and Array, respectively.

How would I determine the type (reference to constructor function) of array items? Is it even possible? In this case, it should be Person.


Note: I need the type reference before instantiation, and because of this, it is impossible to dynamically determine the type using array items: there are no array items, there isn't even an Array instance.





C# Determine difference between DateTime and DateTime? (Nullable)

I am trying to determine the difference between a DateTime and a DateTime? using reflection. Please see my test code below:

    public class TestClass
    {
        public DateTime testDate1 { get; set; }
        public DateTime? testDate2 { get; set; }
    }

    public void Test()
    {
        TestClass testing = new TestClass();
        var props = typeof(TestClass).GetProperties();
        foreach (PropertyInfo p in props)
        {
            object o = p.GetValue(testing);
            if (typeof(DateTime?).IsInstanceOfType(o))
            {
                o = DateTime.Now;
            }
            if (typeof(DateTime).IsInstanceOfType(o))
            {
                if (((DateTime)o) == DateTime.MinValue)
                {
                    o = null;
                }
            }
            Console.WriteLine(string.Format("{0} = {1}", p.Name, (o ?? "NULL").ToString()));
        }

    }

The output of this code is the opposite to what i would expect. Currently the output is:

testDate1 = 26/01/2016 16:15:00

testDate2 = NULL

I am expecting testDate1 to be null and testDate2 to contain the value.

When debugging this code, it seems that the first pass using testDate1 passes both of the typeof if statements, the second fails both of the if statements. Can anybody help me understand and hopefully try and catch the specific nullable instance of the date time?

To note i have also tried switching to a definition and test on Nullable just in case, but it made no difference.

Many thanks!





Get a in a interface annotated method from class

I want to access Method via reflection. The Problem is that the Method is annotated in an Interface:

public interface MyRepository extends CrudRepository<MyClass, Long> {

    @CustomAnnotation
    MyClass findByName(String name);
}

As you see I use spring which provide a class that will implement this Repository. I want to create a Method, that will get a Repository and invoke all methods that are annotated with @CustomAnnotation.

public void do(Repository<?, ?> repository){
   Method[] methods=repository.getClass().getMethodThatAreAnnotatedInInterfaceWith(CustomAnnotation.class);
   ....
}

Because the implementation of an interface won’t have the annotations of the interface present, I do not know how to query these methods.





Reflection 4.6 vs Fasterflect

Is there any advantage in using Fasterflect on .NET 4.5.2/4.6?

On their website they show the comparison with 3.5 and 4.0 and the difference with 4.0 is minimal (apart from the caching).

I was wondering whether, with the new framework, it was just slower/increasing the memory usage to use Fasterflect.





lundi 25 janvier 2016

Increased allocations when invoking parameterless method using MethodInfo.Invoke

When invoking a method in C# using reflection, there seems to be an issue where a MethodInfo.invoke call will allocate ~32 bytes of memory, but only if the method being invoked has no parameters.This can lead to a huge amount of memory being allocated.
Example:

MethodInfo zeroParamMethod = target.GetType ().GetMethod ("ZeroParam");
MethodInfo oneParamMethod = target.GetType ().GetMethod ("OneParam");

object[] arguments = new object[] { 3 };

// Results in 30MB of allocated memory
// Same result when passing an empty object[] variable instead of null
for (int i = 0; i < 1000000; i++)
    zeroParamMethod.Invoke (target, null); 

// All good, no allocations
for (int i = 0; i < 1000000; i++)
    oneParamMethod.Invoke (target, arguments);


public void ZeroParam () {}
public void OneParam (int _arg0) {}

The culprit appears to be a MonoMethodInfo.GetParametersInfo() call.
Is there any simple way to get around these extra allocations?
As a workaround, I could probably just create a delegate from the MethodInfo for this specific case (no parameters), but I'm still stumped as to why there aren't any allocations when the method being called does have parameters.
This code is running in the Unity3D game engine which I believe uses Mono 2.6.5





Getting rid of objects after using reflection

I've been trying to call a method with a string, but one side-effect is that a new object is created everytime I press the button. How can I get rid of this? I've tried using null, but no luck.

First attempt:

string methodName = cboOriginal.Text + "To" + cboConverted.Text;
Type numeralType = typeof(NumeralSystemConversion);
            ConstructorInfo numeralConstructor = numeralType.GetConstructor(Type.EmptyTypes);
            object numeralObject = numeralConstructor.Invoke(new object[] { });

        MethodInfo numeralMethod = numeralType.GetMethod(methodName);
        object numeralValue = numeralMethod.Invoke(numeralObject, new object[] { txtOriginal.Text });

        txtConverted.Text = numeralValue.ToString();

        numeralType = null; numeralConstructor = null; numeralObject = null;
        numeralMethod = null; numeralValue = null;

Second attempt:

string methodName = cboOriginal.Text + "To" + cboConverted.Text;
    convert = typeof(NumeralSystemConversion).GetMethod(methodName).Invoke(typeof(NumeralSystemConversion).GetConstructor(Type.EmptyTypes).Invoke(new object[] { }), new object[] { txtOriginal.Text });
            txtConverted.Text = convert.ToString();
            convert = null;

The 'convert' object is created when the app starts.





refactor code using reflection

I am struggling on refactoring this (working) code:

MyDbContext db = new MyDbContext();

 List<SelectListItem> selectedItems = new List<SelectListItem>();
 if (type == null) return selectedItems;

if (type == typeof(class1))
             selectedItems = db.class1.ToList().Select(ii => new SelectListItem { Text = ii.Name, Value = ii.Id.ToString() }).OrderBy(si => si.Text).ToList();

if (type == typeof(class2))
             selectedItems = db.class2.ToList().Select(ii => new SelectListItem { Text = ii.Name, Value = ii.Id.ToString() }).ToList();

if (type == typeof(class3))
            selectedItems = db.class3.ToList().Select(ii => new SelectListItem { Text = ii.Name, Value = ii.Id.ToString() }).ToList();

if (type == typeof(class4))
            selectedItems = db.class4.ToList().Select(ii => new SelectListItem { Text = ii.Name, Value = ii.Id.ToString() }).ToList();

This code is inside an ASP.NET MVC controller. Class1 to Class 4 are Model classes.

SelectListItem is just a ModelView class I use to grab an Id and a Name from a Class1, 2, 3 or 4 object. I don't think it s worth posting its code. So below code just extracts all occurrences of Class1 or2 or 3 or 4 and converts them into options that will be passed to a View (for a DropDownBox). I only know the exact Model type at runtime of course (Class1...or 4).

I use Entity Framework with such a DbContext:

  public partial class MyDbContext: DbContext
    {
...

        public virtual DbSet<Class1> Class1{ get; set; }
        public virtual DbSet<Class2> Class2{ get; set; }
        public virtual DbSet<Class3> Class3{ get; set; }
        public virtual DbSet<Class4> Class4{ get; set; }
...
    }

I am pretty sure I can end up with a clean code with reflection instead of this horrible thing I wrote. But I did not manage to get anything clean that compiles.

Thx for your help.





Visual-Studio style code generation: Generating basic class implementation at runtime

I have a project that allows the users to write plugins. I include a small IDE that allows writing code in C# and VB.NET and compiling it using the CodeDom compilers. Each plugin inherits a specific base class.

To make life easier for the user, I included basic templates for the various plugin types. Basically when the user creates a new plugin of type XY he starts from a basic implementation similar to what you get when you write

Public Class Foo
    Inherits BaseFoo

and press enter in Visual Studio. The uncool thing is, that I just added some text files containing the premade code to the resources and display it from there. This works well enough until changes are made in the definitions of the base classes because the premade code needs to be adjusted accordingly.

In the framework there exist classes derived from CodeDomProvider like Microsoft.VisualBasic.VBCodeGenerator that seem to contain the necessary methods to create code based on type definitions. However the CodeDom methods seem to be designed to create new types from scratch for example for scripting purposes and don't interact very well with Reflection in the sense, that I can't feed MethodInfos and the like directly to CodeDom.

I could probably hack something together where I manually build the type to be generated, like

Dim v As New Microsoft.VisualBasic.VBCodeProvider
Dim t As New CodeDom.CodeTypeDeclaration("Foo")
t.Attributes = CodeDom.MemberAttributes.Public
Dim r As New CodeDom.CodeTypeReference(GetType(Foo))
t.BaseTypes.Add(r)
t.IsClass = True
t.Name = "TestClass"
Dim base = GetType(Foo)

For Each method In base.GetMethods
    If (method.Attributes And Reflection.MethodAttributes.Abstract) > 0 Then
        Dim m As New CodeDom.CodeMemberMethod()
        For Each p In method.GetParameters
            Dim newp As New CodeDom.CodeParameterDeclarationExpression(p.ParameterType, p.Name)
            newp.Direction = If(p.IsIn, CodeDom.FieldDirection.In, CodeDom.FieldDirection.Out)
            m.Parameters.Add(newp)
        Next
        m.Name = method.Name
        m.Attributes = CodeDom.MemberAttributes.Public Or CodeDom.MemberAttributes.Override
        t.Members.Add(m)
    End If
Next

Dim w As New IO.StringWriter
Dim opts As New CodeDom.Compiler.CodeGeneratorOptions
v.GenerateCodeFromType(t, w, opts)

For an example class

Public MustInherit Class Foo
    Public Property Foo1 As Double
    Public Function What() As Double
        Return Double.NaN
    End Function
    Public MustOverride Sub Test(ByRef Was As Double)
    Public MustOverride ReadOnly Property Something As Double
End Class

this creates the output

Public Class TestClass
    Inherits TypeGenerator.Foo

    Public Overrides Sub Test(ByRef Was As System.Double&)
    End Sub

    Public Overrides Sub get_Something()
    End Sub
End Class

This goes into the right direction, but it seems very prone to bugs and very fiddly. (On a side note, why does it implement the parameter as System.Double& which does not even compile. As a ByVal parameter it works).

Is there an easier way to achieve what I need?

  • Have a base class
  • Create a code template from the definitions therein at runtime




C# How to call FieldInfo.SetValue function without manual type conversion

I want to save data-class instance to database and load it from database. and I want to generate sql command automatically. so, I think that I need to use dictionary< string, string> so that solve it.

refer my old question : How to convert 2D string array to 2D [int, double, bool, ..] array?

working process like these.

  1. convert data-class instance to dictionary < string, string>.
  2. save/load dictionary to/from txt, database, etc.
  3. convert dictionary to data-class instance

I think I have solved the problem anyway. but I think converting 2D array method is still not a perfect one. I wonder, when I call FieldInfo.SetValue function, is there another way to solve type conversion without using switch/case state like my solution.

help me simplify my code.

Data class like this

        public class DCylinderData
    {
        public int ID;

        public int[] Solenoid = new int[2];
        public int[] UpSensor = new int[DEF_MAX_CYLINDER_SENSOR];
        public int[] DownSensor = new int[DEF_MAX_CYLINDER_SENSOR];

        public double MovingTime;

        public ECylinderType CylinderType;
        public ESolenoidType SolenoidType;

        public bool[] boolTest = new bool[3];
        public string[] nameTest = new string[2];
        public int[,] TwoDimension = new int[3,4];

        public DCylinderData()
        {
        }
    }

main code like this

            // 0. initialize
        DCylinderData cylData = new DCylinderData();
        cylData.ID = 99;
        cylData.MovingTime = 1.1;
        cylData.CylinderType = ECylinderType.UPSTREAM_DOWNSTREAM;
        cylData.Solenoid = new int[]{ 2, 3};
        for (int i = 0; i < 2 ; i++)
        {
            cylData.Solenoid[i] = i + 2;
            cylData.nameTest[i] = $"NameTest_{i}";
        }
        for (int i = 0; i < DEF_MAX_CYLINDER_SENSOR; i++)
        {
            cylData.UpSensor[i] = i * 1;
            cylData.DownSensor[i] = i * 4;
        }
        for (int i = 0; i < cylData.TwoDimension.GetLength(0) ; i++)
        {
            for (int j = 0; j < cylData.TwoDimension.GetLength(1) ; j++)
            {
                cylData.TwoDimension[i, j] = i * cylData.TwoDimension.GetLength(1) + j;
            }
        }
        cylData.boolTest[0] = true;
        cylData.boolTest[1] = false;
        cylData.boolTest[2] = true;

        // 1. Class -> Dictionary
        Dictionary<string, string> fieldBook = new Dictionary<string, string>();

        Type type = typeof(DCylinderData);
        FieldInfo[] fields = type.GetFields();
        foreach (FieldInfo field in fields)
        {
            // 1.1 element
            if (field.FieldType.IsValueType)
            {
                fieldBook.Add(field.Name, field.GetValue(cylData).ToString());
            }
            // 1.2 array
            else if (field.FieldType.IsArray)
            {
                Array array = (Array)field.GetValue(cylData);

                // 1.2.1 1-D array
                if (array.Rank == 1)
                {
                    for (int i = 0; i < array.GetLength(0); i++)
                    {
                        fieldBook.Add($"{field.Name}__{i}", array.GetValue(i).ToString());
                    }
                }
                // 1.2.2 2-D array
                else if (array.Rank == 2)
                {
                    for (int i = 0; i < array.GetLength(0); i++)
                    {
                        for (int j = 0; j < array.GetLength(1); j++)
                        {
                            fieldBook.Add($"{field.Name}__{i}__{j}", array.GetValue(i, j).ToString());
                        }
                    }
                }
                else
                {
                    WriteLine($"Not support {field.Name}'s array {array.Rank} dimension.");
                }
            }
            else
            {
                WriteLine($"Not support to handle {field.Name}'s {field.FieldType.ToString()}");
            }
        }

        // 2. print Dictionary
        foreach (KeyValuePair<string, string> item in fieldBook)
        {
            WriteLine($"FieldBook {item.Key} : {item.Value}");
        }

        // 3. Dictionary -> Class
        DCylinderData copyData = new DCylinderData();
        foreach (FieldInfo field in fields)
        {
            // 3.1 handle element
            if (field.FieldType.IsValueType && fieldBook.ContainsKey(field.Name))
            {
                SetFieldValue(copyData, field, fieldBook[field.Name]);
            }
            // 3.2 handle array
            else if (field.FieldType.IsArray)
            {
                Array array = (Array)field.GetValue(copyData);
                string key, value;

                // 3.2.1 1-D array
                if (array.Rank == 1)
                {
                    var arr_1d = new string[array.GetLength(0)];
                    for (int i = 0; i < array.GetLength(0); i++)
                    {
                        key = $"{field.Name}__{i}";
                        value = fieldBook.ContainsKey(key) ? fieldBook[key] : "";
                        arr_1d.SetValue(value, i);
                    }
                    SetFieldValue(copyData, field, arr_1d);
                }
                // 3.2.1 2-D array
                else if (array.Rank == 2)
                {
                    var arr_2d = new string[array.GetLength(0), array.GetLength(1)];
                    for (int i = 0; i < array.GetLength(0); i++)
                    {
                        for (int j = 0; j < array.GetLength(1); j++)
                        {
                            key = $"{field.Name}__{i}__{j}";
                            value = fieldBook.ContainsKey(key) ? fieldBook[key] : "";
                            arr_2d.SetValue(value, i, j);
                        }
                    }
                    SetFieldValue(copyData, field, arr_2d);
                }
                else
                {
                    WriteLine($"Not support {field.Name}'s array {array.Rank} dimension.");
                }
            }
            // 3.3 not support
            else
            {
                WriteLine($"Not support to handle {field.Name}'s {field.FieldType.ToString()}");
            }
        }

        WriteLine("Press any key to continue");
        ReadLine();

and, SetFieldValue Functions like these

        public static void SetFieldValue(Object target, FieldInfo fieldInfo, string value)
    {
        string fieldType = fieldInfo.FieldType.Name;
        fieldType = fieldType.ToLower();

        switch (fieldType)
        {
            case "boolean":
                bool b;
                fieldInfo.SetValue(target, bool.TryParse(value, out b) ? b : false);
                break;

            case "int32":
                int n;
                fieldInfo.SetValue(target, int.TryParse(value, out n) ? n : 0);
                break;

            case "double":
                double d;
                fieldInfo.SetValue(target, double.TryParse(value, out d) ? d : 0);
                break;

            case "string":
                fieldInfo.SetValue(target, value);
                break;
        }
    }

    public static void SetFieldValue(Object target, FieldInfo fieldInfo, string[] arr)
    {
        string fieldType = fieldInfo.FieldType.Name;
        fieldType = fieldType.ToLower();
        fieldType = fieldType.Replace("[]", "");

        switch (fieldType)
        {
            case "boolean":
                bool b;
                bool[] arr_b = Array.ConvertAll(arr, s => bool.TryParse(s, out b) ? b : false);
                fieldInfo.SetValue(target, arr_b);
                break;

            case "int32":
                int n;
                int[] arr_n = Array.ConvertAll(arr, s => int.TryParse(s, out n) ? n : 0);
                //int[] arr_n1 = Array.ConvertAll(arr, int.Parse);
                //int[] arr_n2 = arr.Select(s => int.TryParse(s, out n) ? n : 0).ToArray();
                fieldInfo.SetValue(target, arr_n);
                break;

            case "double":
                double d;
                double[] arr_d = Array.ConvertAll(arr, s => double.TryParse(s, out d) ? d : 0);
                fieldInfo.SetValue(target, arr_d);
                break;

            case "string":
                fieldInfo.SetValue(target, arr);
                break;
        }
    }

    public static void SetFieldValue(Object target, FieldInfo fieldInfo, string[,] arr)
    {
        string fieldType = fieldInfo.FieldType.Name;
        fieldType = fieldType.ToLower();
        fieldType = fieldType.Replace("[,]", "");

        // 0. string return
        switch (fieldType)
        {
            case "string":
                fieldInfo.SetValue(target, arr);
                return;
                break;
        }

        // 1. initialize
        int n;
        double d;
        bool b;

        //object[,] output = new object[arr.GetLength(0), arr.GetLength(1)];
        int[,] output_n = new int[arr.GetLength(0), arr.GetLength(1)];
        bool[,] output_b = new bool[arr.GetLength(0), arr.GetLength(1)];
        double[,] output_d = new double[arr.GetLength(0), arr.GetLength(1)];

        // 2. convert
        for (int i = 0; i < arr.GetLength(0); i++)
        {
            for (int j = 0; j < arr.GetLength(1); j++)
            {
                switch (fieldType)
                {
                    case "boolean":
                        output_b[i, j] = bool.TryParse(arr[i, j], out b) ? b : false;
                        break;

                    case "int32":
                        output_n[i, j] = int.TryParse(arr[i, j], out n) ? n : 0;
                        break;

                    case "double":
                        output_d[i, j] = double.TryParse(arr[i, j], out d) ? d : 0;
                        break;
                }
            }
        }

        // 2. setvalue
        //fieldInfo.SetValue(target, output);
        switch (fieldType)
        {
            case "boolean":
                fieldInfo.SetValue(target, output_b);
                break;

            case "int32":
                fieldInfo.SetValue(target, output_n);
                break;

            case "double":
                fieldInfo.SetValue(target, output_d);
                break;
        }
    }

this is all part of my code.





dimanche 24 janvier 2016

How to use complied type in another compile class using CodeDOM?

I'm use CodeDOM to compile class in run time.

First generate Invoice class

string code1 = @"using System;
                            namespace CodeDOM
                            {
                             public class Invoice
                             {
                              public string InvoiceNo{ get; set; }
                              public DateTime Date{ get; set; }
                              public double Value{ get; set; }
                             }
                            }"; 
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();          
parameters.GenerateInMemory = true;
parameters.GenerateExecutable = false;
CompilerResults results = provider.CompileAssemblyFromSource(parameters, code1);

After that compile another class.This calss use Invoice class.

string code2 = @"using System;
                             namespace CodeDOM
                            {
                             public class DataInjector
                             {
                              public void Insert( CodeDOM.Invoice obj ){ 

                              }
                             }
                            }";
CSharpCodeProvider provider1 = new CSharpCodeProvider();
CompilerParameters parameters1 = new CompilerParameters();
parameters1.GenerateInMemory = false;
parameters1.GenerateExecutable = false;
CompilerResults results1 = provider1.CompileAssemblyFromSource(parameters1, code2);

Final results1 show error "The type or namespace name 'Invoice' does not exist in the namespace 'CodeDOM' (are you missing an assembly reference?)"

Why we cant use Invoice class?





GetEntryAssembly doesn't appear to work when the entry assembly is ASP.NET

First, I do not believe this is a dupe of these:

GetEntryAssembly for web applications

Get entry assembly from ASP.NET application

I have an ASP.NET WebForms app that references a class library. When I call Assembly.GetEntryAssembly() from within the class library while it's referenced by the ASP.NET app, it returns null. However, when I call that same code while the class library is referenced by a console app, it returns the console app assembly.

This answer perhaps sheds light on why Assembly.GetEntryAssembly() behaves differently with ASP.NET:

Why do ASP.NET resolve assembly references differently?

Still, I'd like to be able to get the ASP.NET assembly as if it were a Windows application (console, WPF, WinForms, etc). Is there any way to allow my class library to know about the ASP.NET assembly without adding any ASP.NET references?





Cost of using Reflection by WPF Binding Engine

All of sudden, I got this point remembered. Using the Reflection is having the own cost.

But this Binding Engine depends on that one right?

Is there any specific reason, why WPF sticks with this reflections?

I have heard both the upside and the downside of this one. I have used the reflections in the code but somebody advised me, to do it carefully since it will end up in performance issue.

May I know, the solutions/suggestions/discussions on it.

Thanks in advance.





samedi 23 janvier 2016

Get function name in Swift

I am looking to get the name of function in swift.

I basically want something like

__FUNCTION__

but from a different function e.g.

func do () {
   code etc
}

func doStuff () {
   var funcName = do().name
}

the above would be perfect.

Any ideas?





Java (Android) library project - How to design optional modules?

I am creating an Android (Java) based library project (JAR) where there are -

  1. Core features
  2. Optional features

Now due to size constraints, I have to break this JAR into collection of JARs, where user of this library will have the flexibility to include optional JARs. At the same time, the requirement is to provide a single interface to the user, using which they should be able to call both core and optional APIs. To achieve this, I have two solutions in mind -

Solution-1 Have class implementation for the interface in core library, where APIs related to core feature are implemented here, but API for optional features will be invoked from here using reflection, so that if class found, indicates that optional library is included otherwise not.

APIInterface.java

public interface APIInterface {
    public void coreMethod();
    public void optionalMethod();
}

CoreClass.java

public class CoreClass implements APIInterface {
  public void coreMethod() {
    // implementation
  }
  public void optionalMethod() {
    // use reflection to access optional method from OptionalClass
  }
}

OptionalClass.java

public class OptionalClass {
  public void optionalMethod() {
    // implementation
  }
}

Pros - Here only optional includes core (for core services), core doesn't include optional. So no circular dependency.
Cons - Reflection is used

Solution-2 To avoid reflection mentioned in solution-1, create two versions of optional libraries. First with full implementation and second with empty implementation (only wrappers). Users will have to include mandatorily either one of them, depends on whether user needs optional features or not. With this, the dependency will be inversed. So, core will include the optional library by default, and will be able to call the API from optional library without reflection.

APIInterface.java

public interface APIInterface {
    public void coreMethod();
    public void optionalMethod();
}

CoreClass.java

public class CoreClass implements APIInterface {
  public void coreMethod() {
    // implementation
  }
  public void optionalMethod() {
    new OptionalClass().optionalMethod();
  }
}

OptionalClass.java // full implementation

public class OptionalClass {
  public void optionalMethod() {
    new CoreClass().utilityMethod(); // or super.utilityMethod();
    // optional implementation
  }
}

OptionalClass.java // empty implementation

public class OptionalClass {
  public void optionalMethod() {
    // do nothing
  }
}

Pros - No reflection
Cons - 1. There is a circular dependency on core and optional, since core includes optional to invoke optional API and optional includes core to use core utilities and services.
2. User will have to mandatorily include optional JARs (either full or empty implementation)

Which solution you recommend or any other better solution? Please suggest.





How to Pass empty C# parameter to VBA method expecting a ParamArray argument

I have a COM application object that has a VBA method signature like:

Function DoSomething(ActivityName As String, ParamArray ActivityParams() As Variant)

I'm trying to call the function from my C# code, but I'm unsure how to pass values to the 2nd argument ActivityParams(). I should be able to pass no ActivityParams, or one, or many, so I'm guessing an array at the C# end will be required.

For now, I don't need to pass any ActivityParams values at all, for the second argument, but I probably will need to soon enough.

Is this sufficient to call the DoSomething method, if I don't have any values to pass to ActivityParams?

public override void DoSomething(MyActivity myActivity)
    {
        Application.DoSomething(myActivity.ToString(), null);
    }

And, how would I vary it to be flexible enough to pass 0, 1 or more values?





vendredi 22 janvier 2016

Scala: Ordering[Int].lt invocation fails for reflective method call

I'm playing with Scala reflection and ScalaTest. I've a method defined as follows in an object Ch2: def isSorted[A](as: Array[A], ordered: (A, A) => Boolean): Boolean

The following test fails as described in the comment:

"Method isSorted" should "return true for a sorted array" in {
    val methods =
      Table(
        ("method"),
        ("isSorted")
      )

    val m = ru.runtimeMirror(getClass.getClassLoader)
    val mod = ru.typeOf[Ch2.type].termSymbol.asModule
    val mm = m.reflectModule(mod)
    val obj = mm.instance
    val im = m.reflect(obj)

    forAll(methods) { (m: String) =>
      val isSortedMethod = ru.typeOf[Ch2.type].decl(ru.TermName(m)).asMethod
      val isSorted = im.reflectMethod(isSortedMethod)

      // Fails at runtime with 'missing parameter type for expanded function'
      isSorted(Array(1, 2, 3, 4), Ordering[Int].lt(_, _))
    }
}





Cross-domain interaction without remoting (MarshalByRefObject, RealProxy)?

One of our company's applications features a plugin architecture which allows us to extend the capabilities of the application not with a fixed plugin contract, but in any imaginable way by extensive use of reflection, DI and in process service bus(ses?).

Basically, a plugin can look like this:

                                         |- auto handler registration via reflection
public class ArbitaryPlugin :            v
    IHandle<ImportantApplicationEvent>, IHandle<AnotherEvent>,
{
                              |- whoosh, injected if available
                              v
    public ArbitaryPlugin(IServiceOfHostSystem service) {

    }

    public void Handle(ImportantApplicationEvent message) {
        ...
    }

}

All plugins are bundled into packages with a custom manifest which allows us to resolve dependencies etc. prior to assembly loading. Neat.

However, now we'd like to open the API for the public and therefore we're required to isolate the plugins within sandboxed app domains in order to prevent them tearing down the whole application or to load/unload them on the fly (by just destroying the hosting app domain, not the whole application).

For the service bus and DI to work, we now need to be able to make unrestricted cross-domain calls, but every resource we found on this topic leads to complicated remoting, sponsors, weird lifecycle behaviors etc. Also, we would be required to make every single of our messages or dependencies deriving from MarshalByRefObject or annotated with [Serializable], which simply isn't possible since a lot of them are required to be PCLs, have already other base classes etc.

So, long story short: Is it possible to create suitable objects for cross-app domain communication without this whole remoting stuff? Or, in a more cynical manner, how to create a lightweight, extensible, but yet secure plugin architecture without turning a beautiful code/language environment into the sticks and stones of or anchestors, writing more code for the infrastructure than for the actual plugins?





Use LINQ aggregator dinamically

I'm trying to create a method that uses Linq aggregator functions, like Sum, Average and Count. I have the following code:

private double AgreggateDynamic<T>(IEnumerable<T> list, string propertyName, string func)
{       
    //Already tried this
    //IEnumerable<T> listEnum = list.ToList();     
    Type enumerableType = typeof(Enumerable);

    MethodInfo sumMethod = typeof(Enumerable).GetMethods().First(
        m => m.Name == func
            && m.IsGenericMethod);

    MethodInfo generic = sumMethod.MakeGenericMethod(enumerableType);
    Func<T, double> expression = x => Convert.ToDouble(x.GetType().GetProperty(propertyName).GetValue(x, null));
    object[] parametersArray = new object[] { list, expression };

    return Convert.ToDouble(generic.Invoke(null, parametersArray));
}

AgreggateDynamic(list, "FooValue", "Sum");

When I run this code, it throws an error on this line "return Convert.ToDouble(generic.Invoke(null, parametersArray));".

Error:

Object of type 'Manager.Business.Tests.Foo[]'cannot be converted to object of type 'System.Collections.Generic.IEnumerable`1[System.Linq.Enumerable]'.

What can I do?





Scala Reflection & TypeTag Mismatch

So I have a bunch of compiled case classes in a .jar. I want to load and iterate over all of them and for each case class generate an Avro schema using scalavro. The scalavro AvroType expects a TypeTag, so essentially my question is how to appropriately reflect TypeTags from external case classes in a jar.

import java.net.URL
import com.gensler.scalavro.types.AvroType
import org.clapper.classutil.ClassFinder
import java.io.File
import scala.reflect.internal.util.ScalaClassLoader.URLClassLoader
import scala.reflect.runtime.universe._
import scala.reflect.runtime.{ universe => ru }

object scalaAvroGen extends App {
  val jarLocation = "someCaseClasses.jar"
  val classpath = List(jarLocation).map(new File(_))
  val classLoader = new URLClassLoader(Array[URL](new File(jarLocation).toURI.toURL), this.getClass().getClassLoader())
  val finder = ClassFinder(classpath)
  val classes = finder.getClasses.filterNot(_.isFinal)
  classes.foreach {
    loadedClass => {
      val typeTag = typeToTypeTag(getType(classLoader.loadClass(loadedClass.name)))
      val avroSchema = AvroType.apply(typeTag).schema()
      println(avroSchema)
    }
  }

  def getType[T](clazz: Class[T])(implicit runtimeMirror: ru.Mirror) =
    runtimeMirror.classSymbol(clazz).toType

  def typeToTypeTag[T](tpe: Type): TypeTag[T] = TypeTag.synchronized {
    val mirror = scala.reflect.runtime.currentMirror
    TypeTag(mirror, new reflect.api.TypeCreator {
      def apply[U <: reflect.api.Universe with Singleton](m: reflect.api.Mirror[U]) = {
        assert(m eq mirror, s"TypeTag[$tpe] defined in $mirror cannot be migrated to $m.")
        tpe.asInstanceOf[U#Type]
      }
    })
  }
}

Example case class in the compiled .jar:

case class SimpleScalaAvroObject(version: Int, name: String)

Currently when I attempt to run this code I get the following error:

Error:(20, 39) type mismatch;  found   : reflect.runtime.universe.TypeTag[Nothing]  required: reflect.runtime.universe.TypeTag[T] Note: Nothing <: T, but trait TypeTag is invariant in type T. You may wish to investigate a wildcard type such as `_ <: T`. (SLS 3.2.10)
      val avroSchema = AvroType.apply(typeTag).schema()    
                              ^

Now I'm sure this is not my only issue, I've spent the last two days throwing everything at this. At one point I was getting class not found exceptions on SimpleScalaAvroObject so I'm probably not even reflecting correctly.

I'll eventually annotations to the case classes I actually care about but for now this is really just a PoC.

Please note up until a few months ago I was a C# dev so sorry for this mangled mess of Scala.

Thanks!





Method.Invoke failing with Parameter Count Mismatch

I am trying to invoke a generic method. The definition of the method is as follows:

public System.Collections.Generic.IList<T> Query<T>(string query, [string altUrl = ""])
where T : new()

This is from the SalesforceSharp library on github. I am trying to make an additional service layer over this call and am struggling to invoke it. See my code below.

public List<T> Query<T>()
    {
        //IList<Salesforce.Account> _returnList = null;
        IList<T> _returnList = null;
        Type _t = typeof(T);

        SqlBuilder _sb = new SqlBuilder();
        _sb.Table = _t.Name.ToString();
        foreach (PropertyInfo p in _t.GetProperties()) _sb.Fields.Add(p.Name.ToString());

        MethodInfo method = _Client.GetType().GetMethod("Query");
        method = method.MakeGenericMethod(_t);
        try
        {
            object[] _prms = new object[1];
            _prms[0] = _sb.SQL;
            _returnList = (IList<T>)method.Invoke(_Client, new object[] { _prms });
            //_returnList = _Client.Query<Salesforce.Account>(_sb.SQL);
        }
        catch { }
        return (List<T>)_returnList;
    }

If I run this i get a Parameter Count Mismatch exception on the method.invoke line, but i am confused because if i bring in the two uncommented lines and execute without the generic call it is working ok. I have tried many combinations of string arrays wrapped in object arrays, strings in strings, etc but can't get it to go. I thought maybe it was treating the second parameter as mandatory? but adding another object to my _prms array didnt work either.

Please help!

Thanks, Dom





Reference a collection from IL constructed method

I am building a dynamic method using reflection. Most tutorials and documentation (e.g. How to: Define and Execute Dynamic Methods or Creating method dynamically, and executing it) show a very simple example.

I trying to find a way to reference another assembly from the dynamic assembly.

For example, I would like to be able to construct the following function by using Reflection.Emit.

public static void f(int n)
{
    int[] arr = new arr[n];
    return arr.Max();
}

What would be the common way of doing this?





How to convert type known at runtime to a List of given type?

I have a type that I only get to know at a runtime:

Type givenType = FindOutTypeOf(someObject);

and I have following method:

public void SomeMethod(Type type);

that I need to call it with the List<givenType> type.

How to convert a given type (that I got to know at runtime) to a list of a given type?





Get all data members which have DateTime as datatype in an object [duplicate]

This question already has an answer here:

I have sucked while generalizing a part of code where I need to get the name of all the Data Members which have DateTime as DataType.

Assume this to be a class:

public class SurveyResponseRaw
{
    public string ID { get; set; }
    public bool IsFinished { get; set; }
    public DateTime TerminationDate { get; set; }//DateTime
    public DateTime AssignedDate { get; set; }//DateTime
    public DateTime TeamBTerminationDate { get; set; }//DateTime
}

Now, I want all the Datamembers with DateTime datatype.

Is it possible to get this?

I have heard that this could be done with Reflection. Please let me know how.





Reflection doesn't get the correct value (could it be a .NET framework bug?)

I have a very strange issue with a Reflection. When I try to get the value of a field, which contains list of objects, I get the list.Count == 0. When I check these values in the watch window during debugging, afterwards I get the list.Count > 0 with the same Reflection method. There are no multithreading between the checks (Thread ID is the same) and no operations being performed, which would clear and refill the list again. I could not reproduce the issue on the clean (testing) project. I use .NET framework 4.0 for compatibility reasons and the following logics in the code:

Type t = cmd.GetType();
FieldInfo[] fi = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
object[] o1 = null;
if (fi != null)
{
    o1 = new object[fi.Length];
    for (int i = 0; i < o1.Length; i++)
    {
        o1[i] = fi[i].GetValue(cmd);
    }
}

I would like to know if someone had similar issues and could share with ideas what could have gone wrong and maybe there are solutions how to workaround. To be honest there were few more cases where I could observe the inconsistencies between the debugging information and what the program actually does. For example, once I've encountered a situation where the debug tool had shown the result true but the if clause skipped the line as it would have been false result.





javascript : get a global variable from its name as string (reflection)

I saw a lot of answer to call a method from a given object using a string, but no one to get the object itself. I would like something like that

var a
var b
var c

function getObject(objectAsString)
{
return getMyObject(objectAsString);
}

then if I write

var obj=getObject("a")

my result is obj=a

Is there a function "getMyObject"? Thanks





Creating and overriding Java Enum Objects at Runtime [GregTech/minecraft]

I'm trying to work with this enum and add new materials. Anything not already removed has hard dependencies elsewhere, even still, this is nearly at the java byte limit according to the mods author so there isn't really a lot of room to work with anyway.

GregoriousT mentioned "There is one way. Overmind hacked the Enum using Reflection to add his own stuff. No Idea how he did that and also no idea how long he takes to reply to things if you ask him."

Enum we're talking about: http://ift.tt/1Vdg2kS

So I simply ask, how would I go about this?

This is my current attempt and I get thrown [20:46:38] [Client thread/WARN] [FML]: MiscUtils: Logging Value for Variable m:1|newInstance|public java.lang.Object sun.reflect.DelegatingConstructorAccessorImpl.newInstance(java.lang.Object[]) throws java.lang.InstantiationException,java.lang.IllegalArgumentException,java.lang.reflect.InvocationTargetException|false before the client crashes.

Current attempt:

public class MaterialsNew {

public static void getGregMaterials() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SecurityException{
Utils.LOG_WARNING("Stepping through the process of Greg's materials.");

    Constructor<?> con = Materials.class.getDeclaredConstructors()[0]; 
    Utils.LOG_WARNING("Logging Value for Variable "+"Constructor"+":"+con.getName());
java.lang.reflect.Method[] methods = con.getClass().getDeclaredMethods();
Utils.LOG_WARNING("Logging Value for Variable "+"methods"+":"+methods.toString());
for (java.lang.reflect.Method m1 : methods) { 
    Utils.LOG_WARNING("Logging Value for Variable "+"m1"+":"+m1.getName()+"| Accessible? "+m1.isAccessible());
    if (m1.getName().equals("acquireConstructorAccessor")) { 
        Utils.LOG_WARNING("Logging Value for Variable "+"m1"+":"+m1.getName()+"| Accessible? "+m1.isAccessible());
        m1.setAccessible(true);
        Utils.LOG_WARNING("Logging Value for Variable "+"m1"+":"+m1.toGenericString());
        m1.invoke(con, new Object[0]);}
} 
Field[] fields = con.getClass().getDeclaredFields(); 
Utils.LOG_WARNING("Logging Value for Variable "+"fields"+":"+fields.toString()+"|"+fields.getClass());
Object ca = null;
for (Field f : fields) { 
    Utils.LOG_WARNING("Logging Value for Variable "+"f"+":"+f.getName()+"|"+f.getModifiers()+"|"+f.isAccessible());
    if (f.getName().equals("constructorAccessor")) {
    Utils.LOG_WARNING("Logging Value for Variable "+"f"+":"+f.isAccessible());
    f.setAccessible(true); 
    ca = f.get(con); 
    Utils.LOG_WARNING("Logging Value for Variable "+"ca"+":"+ca.toString()+"|"+ca.getClass());
    } 
} 
Method m = ca.getClass().getMethod( "newInstance", new Class[] { Object[].class }); 
Utils.LOG_WARNING("Logging Value for Variable "+"m"+":"+m.getModifiers()+"|"+m.getName()+"|"+m.toGenericString()+"|"+m.isAccessible());
m.setAccessible(true);
Materials v = (Materials) m.invoke(ca, new Object[] { new Object[] { "NEWMATERIAL", Integer.MAX_VALUE } }); 
System.out.println(v.getClass() + ":" + v.name() + ":" + v.ordinal());}}

Any help or suggestions appreciated, they guys over at the Forge IRC weren't really sure either.





Java Reflection: Invoking Setter and Getter method for collection type Object

I have two different packages of User define Objects.

1) ws.lender.dto (all Objects exists in this package are source side).
2) copl.com.dto (all Objects exists in this package are destination side).

Objects hierarchy and Objects name different in both side. I wan to copy source side object to destination side object field by field or via getter and setter using Reflection.

For Example

Source side Objects

   package ws.lender.dto;

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "CustomerAddresses", propOrder = {
        "previousAddresses"
    })
    public class CustomerAddresses {

        protected PreviousAddresses previousAddresses;

        public PreviousAddresses getPreviousAddresses() {
            return previousAddresses;
        }

        public void setPreviousAddresses(PreviousAddresses value) {
            this.previousAddresses = value;
        }

    }


@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PreviousAddresses", propOrder = {
    "previousAddress"
})
public class PreviousAddresses {

    @XmlElement(name = "PreviousAddress", required = true)
    protected List<PreviousAddress> previousAddress;

    public List<PreviousAddress> getPreviousAddress() {
        if (previousAddress == null) {
            previousAddress = new ArrayList<PreviousAddress>();
        }
        return this.previousAddress;
    }
}


@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PreviousAddress", propOrder = {

    "streetNo",
    "streetName"
})
public class PreviousAddress {

    @XmlElement(name = "StreetNo", required = true)
    protected String streetNo;
    @XmlElement(name = "StreetName", required = true)
    protected String streetName;

    public String getStreetNo() {
        return streetNo;
    }
    public void setStreetNo(String value) {
        this.streetNo = value;
    }
    public String getStreetName() {
        return streetName;
    }
    public void setStreetName(String value) {
        this.streetName = value;
    }
}

Destination side Objects

package copl.com.dto;

@javax.persistence.Entity
public class Customer implements java.io.Serializable
{
private Set<CustomerAddress> customerAddresses;

   public Set<CustomerAddress> getCustomerAddresses()
    {
        return customerAddresses;
    }

        public void setCustomerAddresses(Set<CustomerAddress> customerAddresses)
    {
        this.customerAddresses = customerAddresses;
    }
}

@javax.persistence.Entity
public class CustomerAddress implements java.io.Serializable
{   
    private String unitNumber;
    private String streetName;
    private String streetNumber;

   public String getUnitNumber()
    {
        return unitNumber;
    }   
        public void setUnitNumber(String unitNumber)
    {
        this.unitNumber = unitNumber;
    }
        public String getStreetName()
    {
        return streetName;
    }
       public String getStreetNumber()
    {
        return streetNumber;
    }
        public void setStreetName(String streetName)
    {
        this.streetName = streetName;
    }

    public void setStreetNumber(String streetNumber)
    {
        this.streetNumber = streetNumber;
    }
}   





C# LINQ query fails when using IsAbstract property during derived class scan with reflection?

I am using reflection to scan for all the class types that derive (are assignable) from a particular base class. That part works fine. But when I try to filter the resulting list by the IsAbstract property to get a list of only the non-abstract classes, the LINQ query that does the filtering fails to work correctly. Instead, I had to resort to a foreach loop and do it "manually." I tried this query first:

       if (!bAcceptAbstract)
           retListFiltered = (from typeClass in retList where typeClass.GetType().IsAbstract == false select typeClass).ToList();

But that didn't filter out the class types marked as abstract.

I then tried:

retListFiltered = (from typeClass in retList where !typeClass.GetType().IsAbstract select typeClass).ToList();

But again, no filtering. Why doesn't the LINQ query seem to respect the value of the IsAbstract propery?

Below is the code I ended up having to use:

   public static List<System.Type> GetAllDerivedTypes<T>(Assembly primaryAssembly, bool bAcceptAbstract = true) where T : class
    {
        if (primaryAssembly == null)
            throw new ArgumentNullException("The primary assembly is unassigned.");

        List<System.Type> retList =
            primaryAssembly.GetTypes().Where(type =>
                typeof(T).IsAssignableFrom(type))
            .ToList();

        List<System.Type> retListFiltered = new List<System.Type>();


        foreach (System.Type typeClass in retList)
        {
            if (bAcceptAbstract || !typeClass.IsAbstract)
            {
                Debug.WriteLine(String.Format("INCLUDED {0} class, abstract value: {1}.", typeClass.Name, typeClass.IsAbstract.ToString()));

                retListFiltered.Add(typeClass);
            }
            else
                Debug.WriteLine(String.Format("IGNORED abstract class: {0}.", typeClass.Name));
        }
        return retListFiltered;
    }





Detecting Class object equivalence for classes loaded by different ClassLoaders

My Task is to write a unit test for a method findSubClassImplementation that returns an instance for a given Class object. The method signature looks like this:

public <T extends SuperClass> T findSubClassImplementation(Class<T> cls) throws Exception 

Internally the method checks wether the supplied Class object belongs to a set of known classes and then returns an instance of that class:

if (Subclass.class.equals(cls)) 
        return (T) new Subclass(args);

If the class is not known, an Exception is thrown.

I tried to load all Classes inheriting from SuperClass via Reflection, however when I pass them as argument to the method, an exception is thrown: The method does not recognize them.

I assume what happens is this: Class does not implement equals, thus equals of Object is used, that compares with "==". As reflection uses a different ClassLoader than is used in findSubClassImplementation the two class Objects are different.

Is it possible to get the other Class object for a class that I have loaded with Reflection? Do you have another idea how to deal with this problem?





jeudi 21 janvier 2016

Java - How to get annotations from Proxy class?

I'm not really familiar with proxy class and I have no idea how does this("annotation") became a proxy object. Can I retrieve annotations from Proxy object?

public static void test(Annotation annotation) {
    System.out.println("ValidBoolean annotation len:" + ValidBoolean.class.getAnnotations().length);
    System.out.println(annotation.getClass().getName() + ":" + annotation.getClass().getAnnotations().length);
    if (annotation instanceof ValidBoolean) {
        ValidBoolean validBoolean = (ValidBoolean) annotation;
        System.out.println("[BOOLEAN]" + validBoolean.getClass().getName() + ":" + validBoolean.getClass().getAnnotations().length);
    }
}

the result is:

ValidBoolean annotation len:3
com.sun.proxy.$Proxy28:0
[BOOLEAN]com.sun.proxy.$Proxy28:0





Create a copy of method from IL

I am trying to create a copy of a method during runtime using reflection.

I have the following code.

public static R CopyMethod<T, R>(Func<T, R> f, T t)
{
    AppDomain currentDom = Thread.GetDomain();
    AssemblyName asm = new AssemblyName();
    asm.Name = "DynamicAssembly";
    AssemblyBuilder abl = currentDom.DefineDynamicAssembly(asm, AssemblyBuilderAccess.Run);
    ModuleBuilder mbl = abl.DefineDynamicModule("Module");
    TypeBuilder tbl = mbl.DefineType("Type");
    var info = f.GetMethodInfo();
    MethodBuilder mtbl = tbl.DefineMethod(info.Name, info.Attributes, info.CallingConvention, info.ReturnType, info.GetParameters().Select(x => x.ParameterType).ToArray());

    byte[] il = f.Method.GetMethodBody().GetILAsByteArray();

    mtbl.CreateMethodBody(il, il.Length);
    Type type = tbl.CreateType();
    Func<T, R> method = type.GetMethod(info.Name).CreateDelegate(typeof(Func<T, R>)) as Func<T, R>;
    return method(t);
}

The last line throws an exception with message "Common Language Runtime detected an invalid program".

I am testing with a very simple method (one line: return 10;).

Is there another way of doing this? I would prefer being able to get the parse tree of the method instead of using IL directly.





Could not find or load assembly "tmpAssembly,

I am trying to use a dinamycally generated type as the source of one business rules editor called codeeffects (www.codeeffects.com), however I am getting this exception

Could not find or load assembly "tmpAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null". Error message: Could not load file or assembly 'tmpAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified. (Error S103)

The index action in the controller is:

[HttpGet]
        public ActionResult Index()
        {
            IMyInterface myObject = (IMyInterface)ObjectBuilder.CreateOurNewObject();
            Type t = myObject.GetType();
            ViewBag.Rule = RuleModel.Create(t);
            return View();
        }

and the method that creates the new object is.

public static object CreateOurNewObject()
        {
            string _xml = "<root>" +
                "<column name=\"Name\">Miron</column>" +
                "<column name=\"LastName\">Abramson</column>" +
                "<column name=\"Blog\">http://ift.tt/1Qf9CQU;" +
                "</root>";

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(_xml);

            // create a dynamic assembly and module 
            AssemblyName assemblyName = new AssemblyName();
            assemblyName.Name = "tmpAssembly";
            System.Reflection.Emit.AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
            ModuleBuilder module = assemblyBuilder.DefineDynamicModule("tmpModule");

            // create a new type builder
            TypeBuilder typeBuilder = module.DefineType("BindableRowCellCollection", TypeAttributes.Public | TypeAttributes.Class);

            typeBuilder.AddInterfaceImplementation(typeof(IMyInterface));

            // Loop over the attributes that will be used as the properties names in out new type
            foreach (XmlNode node in xmlDoc.SelectSingleNode("root").ChildNodes)
            {
                string propertyName = node.Attributes["name"].Value;

                // Generate a private field
                FieldBuilder field = typeBuilder.DefineField("_" + propertyName, typeof(string), FieldAttributes.Private);
                // Generate a public property
                PropertyBuilder property =
                    typeBuilder.DefineProperty(propertyName,
                                     PropertyAttributes.None,
                                     typeof(string),
                                     new Type[] { typeof(string) });

                // The property set and property get methods require a special set of attributes:

                MethodAttributes GetSetAttr =
                    MethodAttributes.Public |
                    MethodAttributes.HideBySig;

                // Define the "get" accessor method for current private field.
                MethodBuilder currGetPropMthdBldr =
                    typeBuilder.DefineMethod("get_value",
                                               GetSetAttr,
                                               typeof(string),
                                               Type.EmptyTypes);

                // Intermediate Language stuff...
                ILGenerator currGetIL = currGetPropMthdBldr.GetILGenerator();
                currGetIL.Emit(OpCodes.Ldarg_0);
                currGetIL.Emit(OpCodes.Ldfld, field);
                currGetIL.Emit(OpCodes.Ret);

                // Define the "set" accessor method for current private field.
                MethodBuilder currSetPropMthdBldr =
                    typeBuilder.DefineMethod("set_value",
                                               GetSetAttr,
                                               null,
                                               new Type[] { typeof(string) });

                // Again some Intermediate Language stuff...
                ILGenerator currSetIL = currSetPropMthdBldr.GetILGenerator();
                currSetIL.Emit(OpCodes.Ldarg_0);
                currSetIL.Emit(OpCodes.Ldarg_1);
                currSetIL.Emit(OpCodes.Stfld, field);
                currSetIL.Emit(OpCodes.Ret);

                // Last, we must map the two methods created above to our PropertyBuilder to 
                // their corresponding behaviors, "get" and "set" respectively. 
                property.SetGetMethod(currGetPropMthdBldr);
                property.SetSetMethod(currSetPropMthdBldr);
            }

            // Generate our type
            Type generetedType = typeBuilder.CreateType();

            // Now we have our type. Let's create an instance from it:
            object generetedObject = Activator.CreateInstance(generetedType);

            // Loop over all the generated properties, and assign the values from our XML:
            PropertyInfo[] properties = generetedType.GetProperties();

            int propertiesCounter = 0;

            // Loop over the values that we will assign to the properties
            foreach (XmlNode node in xmlDoc.SelectSingleNode("root").ChildNodes)
            {
                string value = node.InnerText;
                properties[propertiesCounter].SetValue(generetedObject, value, null);
                propertiesCounter++;
            }

            //Yoopy ! Return our new genereted object.
            return generetedObject;
        }