lundi 29 février 2016

JAVA REFLECTION : java.lang.IllegalArgumentException: argument type mismatch

Am using java reflection, Here am using object org.openqa.selenium.remote.RemoteWebElement, to call method called sendKeys. This method will accept characterSequence Array as a parameter type, so am passing characterSequence[] as parameter . Using classname.getMethod(sendKeys, characterSequence[]) I can get the methodname. But when this method is innvoked in runtime passing array of characterSequences[] as argument it throws

java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.thbs.manager.Reflections.callSeleniumCommand(Reflections.java:115)
at com.google.manager.Testing.doTestExecution(Testing.java:105)
at com.google.manager.Testing.main(Testing.java:22)

Could not post the entire code,but posted the code which throws error

objToCallWith = org.openqa.selenium.remote.RemoteWebElement
cls = objToCallWith.getClass();

methodName = sendKeys
params = CharSequence[].class
// send keys method accept only CharSequence[]
myMethod = cls.getMethod(methodName, params);

// able to getMethod

args = new CharSequence[]{'a','b'}
// Here Exception java.lang.IllegalArgumentException: argument type mismatch
myMethod.invoke(objToCallWith,args);





still invoked toString in invoke methode

I have problem with use of CGLib. I have defined a MethodInterceptor, but when I call method.getName() in the intercept method I get only the result from the toString() method ... Why? I don't understand that, because I never call the toString() method directly

public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
      ....
      method.getName();
      return something;
}

when i call method on proxy object i get toString but i call different method. Thx for every idea.





Reflecting C# types in F#

I've loaded a C# dll in a Fsi session. Running C# methods returns some C# types. I've written a helper function to explore the Properties for a given C# type.

The program is failing with an error:

stdin(95,21): error FS0039: The type 'RuntimePropertyInfo' is not defined

Is this possible to do? Or am I beating a dead horse?

let getPropertyNames (s : System.Type)=
    Seq.map (fun (t:System.Reflection.RuntimePropertyInfo) -> t.Name) (typeof<s>.GetProperties())

typeof<TypeName>.GetProperties() //seems to work.

I'm just aiming for a pretty print of C# fields.





Converting a Cucumber scenario DataTable (HashMap) to method calls

I am creating an acceptance test framework for an application that accepts XML files (with up to hundreds of fields) using Cucumber(-JVM), Junit, Java 8. I have created a library that serializes POJOs to XML with a lot of classes using the Builder interfaces (to avoid having dozens of constructors and to have a declarative API of sorts), i.e.:

new Form.Builder
    .setThisField(withThis)
    .setThatField(withThat)
    .build();

I want my cucumber scenarios to read like English, so I decided to use data tables instead of writing something like:

Given I have a form with x field
and with y field
and with z field
and ...

With 50 different 'and' lines. So they look like this:

Given that I have Form B101 with the following fields:
  | X Field        | X Value         |
  | Y Field        | Y Value         |
  | Z Field        | Z Value         |

The Problem:

I want the keys in the cucumber data table (which is turned into a HashMap) to map to method names for my builder pattern. At first I thought using lambdas and method references may let me accomplish this, but I have yet to find a way.

So my next thought was reflection. I decided to store a mapping from a Cucumber Data table key to a method name in a properties file like:

//mapping.properties
X\ Field = setXField 
// the \ after X is to escape the space

I have run into a problem though: some of the fields in the cucumber data table map to deeply nested fields (due to the XML schema) in my XML Data binding library. So for example:

"X Field" is nested within A Field. So in my test method I need to do:

AField aField = new AField(new XField());

But with reflection in java, you need to know the parameter data types before the fact (or so I think). For example, if I want to find out what parameter types are associated with a method:

Class[] paramString = new Class[1];
paramString[0] = AField.class;
// So I need to know before the fact that methodName (below) has a parameter
// of type AField in order to .... get the parameter types of methodName.


// this is legal because a method with methodName exists and it takes
// one parameter with type AField.
Class[] parameterTypes = 
  formB.getClass().getMethod(methodName, paramString).getParameterTypes();

// this is not legal. no method named methodName which doesn't 
// take parameters exists
Class[] parameterTypes = 
  formB.getClass().getMethod(methodName).getParameterTypes();

I'm sure I could find a workaround for this, but ultimately it seems like I'm going down a 'hacky' path. Is there a better way to approach this problem? Or am I on the 'correct' path?





VB.NET How to convert List(of T) with multi-fields to two-dimensional array of String

The List(of T) has n rows with m columns: FirstName, Lastname, Age, .....

I want to convert the List(of T) to an 2-dimensional array of String with size m*n





C# GetType weirdness

We have a very simple program invoking Type.GetType static method. Both should return a valid type instance. Only the second one actually is. Looks like something odd is happening with the stack crawl used by GetType, but what exactly is the issue here? Is it bug or some obscure feature?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GetTypeBeingWeird
{
    public class TestClass { }

    class Program
    {
        static void Main(string[] args)
        {
            var fullName = typeof(TestClass).FullName;
            Console.WriteLine("Full name: {0}", fullName);

            new[] { fullName }.Select(Type.GetType).ToList().ForEach(t => Console.WriteLine("Method group: '{0}'", t));
            new[] { fullName }.Select(t => Type.GetType(t)).ToList().ForEach(t => Console.WriteLine("Closure: '{0}'", t));

            return;
        }
    }
}

Running:

Full name: GetTypeBeingWeird.TestClass
Method group: ''
Closure: 'GetTypeBeingWeird.TestClass'





IllegealArgumentException on invokation of specific method

Ineed to implement a script that calsl a method from a jar-file at runtime. My Code so far looks like this:

package com;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class MyJarImport {

    public static void main(String[] args) throws Exception{

        // C:\\KnimeIntegrationProjekt\\Knime\\pmmlj
        // C:\\Users\\marcel.hoffmann\\JavaWorkspace\\HelloWorld\\bin\\Hello
        //C:\\Knime\\ClusterJar

    File file  = new File("C:\\Knime\\ClusterJar");
    try{
    URL url = file.toURI().toURL();
    URL[] urls = new URL[]{url};
    URLClassLoader cl = new URLClassLoader(urls);

    //loading the jar file from directory
    Class<?> cls = cl.loadClass("MainModel");

    Constructor<?> constructor = cls.getConstructor();
    //instantiate the classfile
    Object MainModelObj = constructor.newInstance();
    /* searching the methods in order to get an instance*/
    Method mGetInput = cls.getMethod("getInputFields");
    Method mNumInputs = cls.getMethod("getNumInputs");
    int dim = (int) mNumInputs.invoke(MainModelObj);

    Method mMining = cls.getMethod("getMiningFunction");
    String miningFunction = "";
    /*returns either Classification, Regression or Clustering
    not used yet, but maybe later to figure out what miningfunction has been used
    that effects the content of evalOutputs[]*/
    miningFunction = (String)mMining.invoke(MainModelObj);
    String[] inputFieldUnsorted = new String[dim];
    inputFieldUnsorted = (String[]) mGetInput.invoke(MainModelObj);
    Object[] sortedInputs = new Object[dim];

    int index = 0;
    /*sorting the inputs from getInputFields respecting the getInputFieldIndex returns*/
    for(int i= 0; i<inputFieldUnsorted.length;i++){
        Method mInputIndex = cls.getMethod("getInputFieldIndex",String.class);
        index = (int) mInputIndex.invoke(MainModelObj, inputFieldUnsorted[i]);
        sortedInputs[index] = inputFieldUnsorted[i];
    }
    /* sortedInputs[] contains the column names of the iris.csv table
invoking the evaluate method. concerning the documentation the method u need to call
in order to use the model inside the jarfile*/
    Method mEvaluate= cls.getMethod("evaluate", Object[].class);
   /* allocating an array for the outputs of the evaluate method*/
    Object[] evalOutputs = new Object[dim];
    evalOutputs = (Object[]) mEvaluate.invoke(MainModelObj, sortedInputs, inputFieldUnsorted);
   /* closing the opened classloader*/
    cl.close();
    } catch(IOException e) {
        System.out.println("File not found!");
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        System.out.println("Class not found!");
    }
    }
}

This Code as it is throws a IllegalArgumentException:wrong number of arguments.

Exception in thread "main" java.lang.IllegalArgumentException: 
wrong number of arguments
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.MyJarImport.main(MyJarImport.java:58)

I got a documentation about the jar file I need to load and it says, that the method signature is something like

Object[] MainModel.evaluate(Object[] inputs);

I debugged the code and I think everthing works, in terms of the values of the variables. just this call semms the problem. I just read something about invokation, that says the VM tries to invoke the mainmethod of the jar file and the main methods requires its String[] args parameter, but why would it do that, if I want to invoke an explizit method?

I hope someone can help me with this little problem.

Thanks in advance.

cheers





Change static element value through reflection with string as element name

I'm getting data from a DB and access through the field names of the class DBUserValues and want to save the results in a DBUserValues object. There is always only one result. How to I access these static variables with a string? Is there a better way to do this?

public class DBUserValues {
    public static String username;
    public static String firstname;
}

Go through results and save them

for (Field field : user.getClass().getDeclaredFields()) {
    // Result should get saved in DBUserValues object
    // DBUserValues.username = result.getString(field.getName();
    // DBUserValues.(field.getName()) = result.getString(field.getName());
}





dimanche 28 février 2016

What is the benefit of using Class?> instead of Class as a method parameter type?

I've written a utility method that accepts a parameter 'cl' of type Class and performs logic by using cl.isInstance(objectInstance) method.

However I've seen example code that declares parameters using the generic wildcard Class<?>.

Why not just use Class without the generic wildcard? Can't Class represent all possible class types including generics? What is the benefit, if any of using Class<?> in my situation?

The accepted answer in an existing related question (see below) does not actually provide a useful answer.

What does Class<?> mean in Java?





How to hook into an auto-generated Java method?

I'm working with auto-generated Java code that produces a method called onChange(). I'd like to call my own method when onChange() is called. Is there any way to "hook into" onChange() via reflection or other standard Java mechanism?





Loading library dynamically

I have the following project structure:

  1. Web API
  2. Class Library A
  3. Class Library B
  4. Class Library C

These are the references between the projects

  • Web API directly references A and B
  • B directly references C

C has a method which needs to ensure that A is loaded to use, by reflection, a type defined in it.

My code actually is like the following

public class C {
    public void MethodCallingBType( string fullClassName ) {
        //e.g. MyNamespace.MyType, MyNamespace
        string[] parts = m.FullClassName.Split( ',' );
        var className = parts[0].Trim();
        var assemblyName = parts[1].Trim();
        if ( !string.IsNullOrEmpty( assemblyName ) && !string.IsNullOrEmpty( className ) ) {
            string assemblyFolder = Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location );
            string assemblyPath = Path.Combine( assemblyFolder, assemblyName + ".dll" );
            if ( File.Exists( assemblyPath ) ) {
                Assembly assembly = Assembly.LoadFrom( assemblyPath );
                Type type = assembly.GetType( className );
                result = Activator.CreateInstance( type ) as IMechanicRunner;
            }
        }
    }
}

This code actually does not work as the Path.GetDirectoryName function does not return a valid path. Apart from this I would like to create a better way t ensure that B module is loaded in memory before looking for its type.

Any suggestion?





Java get an existing list of objects knowing the class name(dynamically)

I have a class containing 2 lists, of different object types.

List<Student> students;
List<Lecturer> lecturers;

Each of these classes have a method that returns a String. I want to find something from that String and the method that I would create would be the same for both lists,the class name(Student/Lecturer), the list name(students/lecturers) and the method name(studentMethod/lecturerMethod) being the only ones that differ.

Knowing the className, listName and the methodName, how can I get the proper list(called listName) so I can then call the desired method(called methodName) from each object in the list.

P.S. : I know it would be easier to just create 2 separate methods for each list but I want my code to be DRY and also to learn more about OOP principles.

Example: If I want to get the students list and then invoke the studentMethod for each student I should have something like this:

void dryMethod(String className, String listName, String methodName) {
    Class<?> desiredClass = Class.forName(className);
    List<desiredClass> desiredList = getListByName(listName);
    Method desiredMethod = getMethodByName(methodName);
    for(desiredClass object : desiredList){
        manipulateString(object.desiredMethod());
    }
}
dryMethod("Student","students","studentMethod");

Is it possible?





Scala Generics & Reflection Issue

I noticed some gap around reflection and generics and I wonder is anybody can help here.

Let say I have the following abstract class:

abstract class Animal[T : Eatable: ClassTag] {

     def eat(food: T) : Unit
}

And here is one implementation of it:

class Dog[DogFood] {

    def eat (food: DogFood) : Unit = ???
}

class DogFood extends Eatable

And here i had some method that given an animal, feeds it

def feed[T <: Eatable](animal: Animal[T]) : Unit = {
    val isAvailable = Storage.isAvailable[T]
    ???
}

Now let say I want to instantiate the implementation class using reflection as it is part of my system configuration:

val config = ....
val animalCls = config.getString("animal.type")
val animalInstance = animalCls = Class.forName(animalCls).newInstance

// Issue is here - I can't call this method as it uses classTags!
feed(animalInstance)

A solution might be :

 val animalCls = config.getString("animal.type").asIsntanceOf[Animal[_]]

But then the following call inside feed will fail as it doesn't bind the right type:

Storage.isAvailable[T]

Any ideas here?

Thanks!





samedi 27 février 2016

Get Method from Groovy method closure

In groovy the .& operator converts a method in a closure. In java from the reflection Method object, one can get the method name, parameters names and types... Is there a way to get all the method reflection information from the closure?





Invoke an static delegate from Reflection?

I have the folow line:

public static class Foo
{
    public static Func<object,string> Bar = myObject => myObject.ToString();
}

There is no way to perform something like Bar(someObject); using reflection in C#. As I can see Bar is not a Method, is a Field, of course, and I can't use MethodInfo.Invoke();





Java - Convert String values from properties file to generic type Objects

I need to get the values from a properties file. I am doing it like this:

for (String key : propsFile.stringPropertyNames()) {
    String value = propsFile.getProperty(key);

    //Now I want to get value as its appropiated generic type object,
    //since later I will map the properties file into a TreeMap<Key, Object>,
    //where Object should be the value as a proper generic type object,
    //or a custom one based on developer opinion.

}

(value might be sometimes "asf", other times "949", other times "true"...)

How could I convert the string value to a new generic type object based on the kind of data retrieved? Or some way or library to do this directly when getting the properties by the key, with the option of defining custom types?





Reflexion: How to deal with

This question already has an answer here:

I'have a class that's 57 or so properties. I'd like to loop through all the properties and set the value through reflextion.

public class Employee
{
  public Emmployee(DataRow row)
  {
    foreach (PropertyInfo pInfo in this.GetType().GetProperties())
    {
      Type t = pInfo.PropertyType;
      pInfo.SetValue(this, row.Field<t>(pInfo.Name));
    }
  }

  //over 57 properties...
}

I'm getting the following error: t is a variable but is used like a type.





Method invoked with methodInfo.Invoke returns yield return

I was using 3rd-party package to a .Net cms, kind of ORM from internal data representation to a POCO. To get it worked I needed to take it's source code from GitHub to debug and see what is wrong. I've found that there is reflection MethodInfo.Invoke call to a method that uses yield return. The return from this method is supposed to be assigned to a POCO's property with property.SetValue(). And this very call returned null that, being set to a property, caused invalid result of mapping.

I changed method's logic a bit to compose IEnumerable<> first and then return it as it is with ordinary return, no yield - then everything started working properly.

My question is - since this package was downloaded and used by other people so it is considered to be working, putting aside my source code change - perhaps there is some approach to deal with Invoked methods that return with yield? I know that yield returns an ienumerator (state machine) that is to be used in foreach-like loops over some IEnumerable but it is for direct IEnumerable generator method call, it was the first time when I saw reflection-call of such method. Thanks.





How to get class from field?

I am trying to receive class field value via reflection. But when I call my code I receive exception: IllegalArgumentException: Can not set class field field to java.lang.Class.

My code:

Field f = clz.getDeclaredField("classLoader");
f.setAccessible(true);
Class cls = f.get(clz).getClass();

Code from class with field:

public class SomeClass{
    public RelaunchClassLoader classLoader;

    //Other code

}

RelaunchClassLoader extends URLClassLoader

What's wrong?





Alternatives to reflection when accessing an arbitrary field

I was using this code to create some sort of a universal changer class:

    //constructor method
    public Change(Object affdObj, String affdField, float modifier) {
        obj = affdObj;
        //...
        affectedField = affdObj.getClass().getField(affdField);
        //...
        affectedField.setFloat(obj, affectedField.getFloat(obj) + modifier);
    }

But then I was advised to avoid reflection whenever possible since it's very slow. I was suggested to pay attention to interfaces. Unfortunately I can't see how to fit interfaces to my code.

Hence my question: if one needs to access a field which name he doesn't know in advance are there any options other than using reflection?





vendredi 26 février 2016

Deducing Class Type from String

As described in This Answer, you can determine a derived object from a string, as long as you know the base type. I wanted to make the code more flexible by making the BaseFactory a template, which results in the following compilable code.

#include <iostream>
#include <string>
#include <map>


///Reflect and Register
#define MyType(BASE, TYPE) \
    static Registerer<BASE, TYPE> reg

#define Register(BASE, TYPE) \
    Registerer<BASE, TYPE> TYPE::reg(#TYPE)

template<class B>
class Factory
{
public:
    static B* from(const std::string& name)
    {
        return mapping[name];//should check if its a member
    }
    static void add(const std::string& name, B* instance)
    {
        mapping[name] = instance;
    }
    static std::map<std::string, B*> mapping;
};
template<class B>
std::map<std::string, B*> Factory<B>::mapping = std::map<std::string, B*>();


template<class B, class D>
class Registerer
{
public:
    Registerer(const std::string& name)
    {
        Factory<Base>::add(name, new D);//actually add
    }
};
///Deduce and Register


///Class examples implementing Registration
class Base
{
public:
    Base()
    {
        name = "Base Class";
    }
    const std::string& getName()
    {
        return name;
    }
protected:
    std::string name;
};
class Derived1 : public Base
{
public:
    Derived1()
    {
        name = "I am type 1.\n";
    }
    MyType(Base, Derived1);
};
Register(Base, Derived1);
class Derived2 : public Base
{
public:
    Derived2()
    {
        name = "I am type 2.\n";
    }
    MyType(Base, Derived2);
};
Register(Base, Derived2);
///Class examples implementing Registration


int main()
{
    std::string typeString1 = "Derived1";
    std::string typeString2 = "Derived2";

    std::cout << Factory<Base>::from(typeString1)->getName();
    std::cout << Factory<Base>::from(typeString2)->getName();

    return 0;
}

However, this code crashes, apparently because Factory::mapping does not get instantiated in time for when Registerer calls add. As described in This Answer, there is a solution, which is to add the line

template class Factory<Base>;

which does not fix the problem in Visual Studio, which is what I'm using. The other possibility is to explicitly make a new class, but the whole point was to use a template in the first place. So I came up with this:

template<class B>
class Factory
{
public:
    static B* from(const std::string& name, B* instance = NULL)
    {
        static std::map<std::string, B*> mapping;
        if(instance != NULL)
        {
            mapping[name] = instance;
            return NULL;
        }
        else//should check if name is in map first
            return mapping[name];
    }
};

Which works since the mapping variable is initialized the first time the function is called. The unfortunate part is the if check.

I'm trying to find a solutions that:

  1. Does not use a single function in Factory to simulate two.

  2. A way to register a class with a single line instead of two.

  3. The ability to force a child class of Base to register itself, to prevent a user accidentally not registering it.





Elegant solution for proxy mess

In Java 8, I wanted to write a class that, given one or more listeners, would return a proxied List (using implementation of List of my choosing by passing in its class) that triggers the listener whenever something is added or removed. The code (bear with me) is below:

public final class EventedList {
    private EventedList() {
    }

    protected static class ListInvocationHandler<T> implements InvocationHandler {
        private List<T> theList;
        private ListChangeHandler<T>[] listeners;

        public ListInvocationHandler(Class<? extends List<T>> listClass, ListChangeHandler<T>[] listeners) throws InstantiationException, IllegalAccessException {
            this.listeners = listeners;
            theList = listClass.newInstance();
        }

        public Object invoke(Object self, Method method, Object[] args)
                throws Throwable {
            Object ret = method.invoke(theList, args);
            switch(method.getName()) {
            case "add": 
                trigger((T)args[0], true);
                break;
            case "remove":
                if(args[0] instanceof Integer) {
                    trigger((T)ret, false);
                } else {
                    trigger((T)args[0], false);
                }
                break;
            }
            return ret;
        }

        public void trigger(T obj, boolean added) {
            Arrays.stream(listeners).forEachOrdered(l -> l.onChange(obj, added));
        }
    }

    public static <T, U extends List<T>> List<T> newList(Class<U> listClass, ListChangeHandler<T> ... listeners) throws IllegalArgumentException, InstantiationException, IllegalAccessException {
        @SuppressWarnings("unchecked")
        List<T> obj = (List<T>)Proxy.newProxyInstance(listClass.getClassLoader(), new Class<?>[]{List.class}, new ListInvocationHandler<T>(listClass, listeners));
        return obj;
    }

    public static <T, U extends List<T>> List<T> newListSafe(Class<U> listClass, ListChangeHandler<T> ... listeners) {
        List<T> obj = null;
        try {
            obj = newList(listClass, listeners);
        } catch (IllegalArgumentException | InstantiationException
                | IllegalAccessException e) {
        }
        return obj;
    }   
}

It works, but it is certainly not without its issues.

  1. I initially only had one type T, but I was getting errors using Class<? extends List<T>> so I use U to represent ? extends List<T> instead.
  2. In invoke method of ListInvocationHandler, I'm having to forcively cast Object to T. I think that is unavoidable, but I welcome any alternatives.
  3. newProxyInstance is returning Object that I'm having to cast to List. Also this I believe is unavoidable but I welcome any alternatives.
  4. I'm receiving a "Potential heap pollution via varargs parameter listeners" warning on listeners parameters presumably because they are variable parameter arguments, however I don't see the obvious risk of doing it this way.

The main that I'm using is the following:

public static void main(String[] args) {
    List<String> list = EventedList.newListSafe(ArrayList.class, new ListChangeHandler<String>() {

        @Override
        public void onChange(String value, boolean added) {
            System.out.println(value + ", " + (added ? "added" : "removed"));
        }

    });

    list.add("Badger");                                  // Badger, added
    list.add("Badger");                                  // Badger, added
    list.add("Badger");                                  // Badger, added
    list.add("Badger");                                  // Badger, added
    list.remove("Badger");                               // Badger, removed
    list.add("Mushroom");                                // Mushroom, added
    list.remove("Mushroom");                             // Mushroom, removed

    // [Badger, Badger, Badger]
    System.out.println(Arrays.toString(list.toArray()));  
}

  1. The main itself calling the method has a nice type safety warning, even if the parameters should be implicit.

I apologize for the wall of text. I appreciate any input.





Get me object property using a string

I have seen several examples of reflection on here but cant seem to get them to work for my exact issue...

example of a solution I looked at

My 3 classes...

 public class Row
    {
        public string Cell1  = "cat";//{ get; set; }
        public string Cell2 = "fish"; //{ get; set; }
        public string Cell3 = "dog";  //{ get; set; }


    }

    public class Grid
    {
        public Row Row1 = new Row();
        public Row Row2 = new Row();
        public Row Row3 = new Row();

    }

    public class SetOfGrids
    {
        public Grid g1 = new Grid();
        public Grid g2 = new Grid();
    }

How I can get the value...

SetOfGrids sog = new SetOfGrids();
 MessageBox.Show(sog.g1.Row1.Cell1);

The getproperty function for the link i thought might work...

public Object GetPropValue(String name, Object obj) {
    foreach (String part in name.Split('.')) {
        if (obj == null) { return null; }

        Type type = obj.GetType();
        PropertyInfo info = type.GetProperty(part);
        if (info == null) { return null; }

        obj = info.GetValue(obj, null);
    }
    return obj;
}

How I would like to get the value... (I get a null exception error.)

 string PathToProperty = "sog.g1.Row1.Cell1";
 string s = GetPropValue("sog.g1.Row1.Cell1", sog).ToString;
 MessageBox.Show(s);

Result should be "cat2"





Reflection API to choose between instantiation of a base class or its extended version from a different project

Let's say I have a class named Human in ProjectA. It is instantiated in the CreatureBuilder class of the same project.

Now I want to create a new class called Cyborg in a different project, i.e. in ProjectB. ProjectB has ProjectA in its imports, but ProjectA knows nothing about ProjectB.

Cyborg extends Human, and must also be instantiated by CreatureBuilder of ProjectA (so, Cyborg is located in ProjectB, I call CreatureBuilder from ProjectB to instantiate Cyborg, but CreatureBuilder is located in ProjectA, as well as my Human class).

I need a logic to create a Human when CreatureBuilder is instantiated from ProjectA, and to create a Cyborg when CreatureBuilder is instantiated from ProjectB.

I know that it can be done by creating an interface with a getCreature() method (that will be overridden in ProjectB) and a factory class. But can I use Reflection API instead? From its description, looks like it was designed to do something related (please correct me if I'm wrong). I know that reflections are slow though, and I normally avoid them. But it would be great to see a proof-of-concept, just out of curiosity.





how to return an object after setting its property using reflection

I am using java reflection to create object and then using BeanUtils to set the property of object. I want to ask, how can I return the same object on which I have used BeanUtils to set property.

My code:

public Object createBOFromJSON(JSONObject jsonData,String strBeanName,String[] strParametrNames)
 {
  Object object = null;
  try {
      Class classDefinition = Class.forName(strBeanName);
      object = classDefinition.newInstance();
  } catch (InstantiationException e) {
      System.out.println(e);
  } catch (IllegalAccessException e) {
      System.out.println(e);
  } catch (ClassNotFoundException e) {
      System.out.println(e);
  }
  try {
        for(int j=0;j<strParametrNames.length;j++){
            String value=jsonData.getString(strParametrNames[j]);
            BeanUtils.setProperty(object, strParametrNames[j], value);      
        }

} catch (IllegalAccessException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (InvocationTargetException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
  catch(Exception ex){

  }
  return object;
 }

I am using this method like below code:

RWReportCustomerDB objRWReportCustomerDB=(RWReportCustomerDB) rwUtils.createBOFromJSON(requestedJSONObject, strBeanName, strBeanFields);


System.out.println(objRWReportCustomerDB.getDbLogin()+"   ***********");

in system.out.println I am getting null. why is it so. is it not the same object. how can i resolve to get same object.





jeudi 25 février 2016

Paging API calls using Linq to Sql OrderBy with string parameter and reflection

I am trying to generalize paging calls for an API. If I have a filter passed from the web page, I want to be able to return a range of items based off from the page number and page size. This is pretty simple to do if the OrderBy uses a set parameter or possibly using an ugly switch statement for every single call.

Currently I am trying to extend IQueryable using expressions and reflection (of which I am not experienced in) I found a couple examples to start from and it works if I use a property that is a simple type in the root class (passing the string "FixValidatedCount"). I can not get it to work if I try to order by a nested class property like the Island.Name example below.

Is there any way to updated my expression to accept nested class / properties? Or is there a better way to do this?

    [Route("api/issues/paged")]
    [HttpPost]
    public HttpResponseMessage GetIssuesPage(EntityPageFilter filter)
    {
        //THE BELOW COMMENTED OUT OBJECT IS THE PARAMETER 
        //var filter = new EntityPageFilter
        //{
        //    PageSize = 5,
        //    PageNumber = 1,
        //    OrderBy = "Island.Name",
        //    OrderByAscending = true
        //};

        var query = _issueService.GetIssues()
            .OrderByField(filter.OrderBy, filter.OrderByAscending)
            //.OrderBy(i => i.Island.Name)  THIS WORKS, BUT HOW DO I DO THIS WITH A STRING
            .Skip(filter.Skip).Take(filter.PageSize);

        return Request.CreateResponse(HttpStatusCode.OK, new PagedEntity<IssueSummary>
        {
            PageNumber = filter.PageNumber,
            PageSize = filter.PageSize,
            ItemCount = _issueService.GetIssues().Count(),
            Data = query
        });
    }

The IssueSummary is the return type of the query.

public class Issue
{
    public int Id { get; set; }
    public Island Island { get; set; }
    public Type Type { get; set; }
    public DateTime CreatedAt { get; set; }
    public DateTime? FixedAt { get; set; }
}

public class IssueSummary: Issue
{
    public int FixCount { get; set; }
    public int FixValidatedCount { get; set; }
}

public class Island
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

The extension method for IQueryable

    public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string sortField, bool ascending)
    {
        var properties = sortField.Split('.').ToList();

        var xType = typeof(T);

        for (var i = 0; i < properties.Count - 1; i++)
        {
            xType = xType.GetProperty(properties[i]).PropertyType;
        }

        var param = Expression.Parameter(xType, String.Empty);
        var prop = Expression.Property(param, properties.Last());

        var exp = Expression.Lambda(prop, param);
        var method = ascending ? "OrderBy" : "OrderByDescending";
        //var types = new[] { q.ElementType, exp.Body.Type };
        var types = new[] { xType, exp.Body.Type };
        var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
        return q.Provider.CreateQuery<T>(mce);
    }





How to Get the Value of a List Type Property using propertyInfo

            Type objType = Model.GetType();
            PropertyInfo[] properties = objType.GetProperties();
            foreach (PropertyInfo property in properties)
            {
                object propValue;
                //Checking if property is indexed                 
                if(property.GetIndexParameters().Length ==0)
               propValue  = property.GetValue(Model,null);
                else
                {  
                 // want to retrieve collection stored in property index not passing 0 index returning element at 0 location ,how can i get whole list  
                 propValue = property.GetValue(objectModel,new Object[]{0});                       
                 }
                var elems = propValue as IList;

How can i get the Property Value of List Type, my property in the Model is a List Type for Example my Model contains a List Property

List<User>





Dynamic cast vs reflection invoke: which poison to pick?

I'm facing a little dilemma.

I need to repetitively call a given method on many instances of a type, that may or may not exist. Because the method's result will never change for any given instance, I'm caching its return value for future use so as to reduce the overhead and return early on subsequent calls, but still the part that actually does the work needs to call that method-that-may-not-exist:

var method = Context.Parent.GetType().GetMethod("typeHint");
if (method == null)
{
    token = null;
    _hasTypeHint = false;
    return false;
}

var hint = ((dynamic)Context.Parent).typeHint() as VBAParser.TypeHintContext;

Catching/handling a RuntimeBinderException was a major performance bottleneck, so I decided to reflect on the type in question to go and discover whether the method exists or not before calling it.

The specific type of Context.Parent is unknown at compile-time, and the possible runtime types don't share a common interface that would have the typeHint() method I'm looking for: I need to either invoke the reflected member, or cast to dynamic and invoke it directly.

My commit message goes like this:

removed the possibility for RuntimeBinderException by reflecting on the context type to locate the method to use. Kept (dynamic) cast because deemed less expensive than reflection invoke.. could be wrong though.

Which one incurs the least overhead, and more importantly, why?





Testing two object with operator <, <=, etc

Long story short, i have, in C#, a function that posses two "object" (yes the class !) representing potentially a primitive type (excluding bool) and i want to test them. Here is a code to explain it better :

public void Compare(object value1, object value2) {
    if(value1 < value2)
        //do something
    if(value1 > value2)
        // do something else...
 }

But as you may know it's not possible... Is there a way to do it ?





use reflection to print its own method name, class library (portable)

I would like to use reflection for a method to print its own name. I have found similar question on different thread but their method does not seem to be applicable to my scenario. It was suggested to use

MethodBase.GetCurrentMethod().Name 

The complier error I got was "MethodBase" does not contain a definition for "GetCurrentMethod"

to get the current method own name but GetCurrentMethod does not exist in the portable class library in VS2015. Below is my code for your reference. Please note: some portable class library in version of VS earlier than 2015 may work, I have vs2015 and got the error.

namespace ClassLibrary1
{
    public sealed class Class1
    {
        public delegate int myFunction(object o);
        public Dictionary<string, myFunction> list = new Dictionary<string, myFunction>();
        private static readonly Class1 _instance = new Class1();
        static Class1()
        {
        }
        public Class1()
        {
            string[] n = { "f1", "f2" };
            MethodInfo mInfo;
            foreach (var i in n)
            {
                mInfo = typeof(Class1).GetTypeInfo().GetDeclaredMethod(i);
                ParameterExpression objExpr = Expression.Parameter(typeof(object));
                Expression<myFunction> expr = Expression.Lambda<myFunction>(Expression.Call(null, mInfo, objExpr), objExpr);
                list.Add(i, expr.Compile());
            }

            list.Add("f11", f1);
            list.Add("f21", f2);
        }
        public static Class1 Instance
        {
            get
            {
                return _instance;
            }
        }
        public static int f1(object o)
        {
            string n = MethodBase.GetCurrentMethod().Name;
            System.Diagnostics.Debug.WriteLine("current function is {0} ", n);
            return 0;
        }
        public static int f2(object o)
        {
            string n = MethodBase.GetCurrentMethod().Name;
            System.Diagnostics.Debug.WriteLine("current function is {0} ", n);
            return 0;
        }
    }

}

Any thought?





get and set object property using Expression trees instead of Reflection

I would like to dynamically get and set an objects properties as follows:

public class Person
{
    public string Name {get; set; }
}

public class Testing
{
    public void Run()
    {
        var p = new Person();

        SetValue(p, "Name", "Henry");

        var name = GetValue(p, "Name");
    }
}

Please could I get help creating the GetValue and SetValue methods using dynamic method (or expression trees)?

I am intending to save compiled expressions in a dictionary, to speed up future get/set calls.





How can I change the behavior of a static method at runtime?

Is there a way to modify the behavior of a static method at runtime?

for example:

Say I have this class

public class Utility {

    public static void DoSomething(string data){
        //...
    }
}

Is there a way to do something like this:

typeof(Utility).SetMethod("DoSomething", (data) => { /*Do something else...*/ });

Such that if you call Utility.DoSomething it executes the new code?





Is any way to enable Data roaming in android Kitkat silently

I want to enable the mobile data and Data roaming in android tablet. I can enable the mobile data with telephony APIs but for Data roaming i could not get any way.

Another option,i identify with activity launch of Mobile data page.

Is any way to enable Data roaming ?





How can I avoid semi-repeating groups of methods in java?

Let's say I have written the following methods:

public void submitForm1() {
        open();
        setField(1, "blah");
        setField(3, "bla");
        setField(4, "blah blah");
        submit();
    }

public void submitForm2() {
        open();
        setField(1, "blah");
        checkBox(1 , true);
        submit();
}

....

public void submitForm100() {
        open();
        setField(1, "bla");
        setField(2, "bla bla");
        setField(3, "blah");
        setArea(1, "blah blah");
        submit();
}

These methods make me feel I'm constantly repeating myself. I feel like it should be written like this:

public void submitForm1() {
        MyMethods.submitForm(
            {SET_FIELD, 1, "blah"},
            {SET_FIELD, 3, "bla"},
            {SET_FIELD, 4, "blah blah"}
        );
    }

public void submitForm2() {
        MyMethods.submitForm(
            {SET_FIELD, 1, "blah"},
            {CHECKBOX, 1, true}
        );
}

....

public void submitForm100() {
        MyMethods.submitForm(
            {SET_FIELD, 1, "bla"},
            {SET_FIELD, 2, "bla bla"},
            {SET_FIELD, 3, "blah"},
            {SET_AREA, 1, "blah blah"},
        );
}

This way I won't have to repeat all of those open and submit methods over and over again.

Is there a way to do this?





mercredi 24 février 2016

Reflection to load an object of a class and run the object as a new thread from another class

I have been studying Reflection in Java for a few days now.

I have 2 classes, SimulatorInstance and SimulatorInstanceThread. I am trying to load an instance of SimulatorInstance using reflection and run that object as a new thread using Runnable interface from SimulatorInstanceThread.

I have tried to load the SimulatorInstance class using Classloader:

ClassLoader simInstance = SimulatorInstance.class.getClassLoader();

and tried running it as a new thread. But it doesn't work. I know this is probably very basic. But can someone point out what is the mistake here?





How can I find the JSON key of a field (jackson)

I have the following promlem. I export my user object as usualwith the jackson.databind.ObjectMapper and that works fine ({"address":{"village":"NY"},"prename":"Joe"}).

Now I have to get the key (address and prename) with java reflection. If the field has the annotation @JsonPropertie there is no problem to get this key. But this annotation isn't pressent on all fields (for example the m_address field).

At How does the Jackson mapper know what field in each Json object to assign to a class object? I read that the ObjectMapper try to call the getter or so.

But I have no clue how I can find the right getter to my field.

I know that this isn't probably the most beautifull way to solve my problem but I haven't found any method on the ObjectMapper like "mapper.getJSONKeyByName(field)". If something like that exist even better. :)

So my question is is there a way to find the right getter to a field and does something like "mapper.getJSONKeyByName(field)" exist on the ObjectMapper?

Thanks for your answer.

Main.java

public static void main(String[] args) throws Exception {
    ObjectMapper mapper = new ObjectMapper();   

    // Object to JSON as usual
    mapper.writeValue(System.out, new User("Joe", new Address("NY"))); // {"address":{"village":"NY"},"prename":"Joe"}


    // Lookup with reflection
    for (Field field : User.class.getDeclaredFields()) {
        field.setAccessible(true);
        try {
            if (field.isAnnotationPresent(JsonProperty.class)) {
                System.out.println("JSON-Key with annotation: " + field.getAnnotation(JsonProperty.class).value()); // JSON-Key with annotation: prename
            } else {
                //TODO do something to get "JSON-Key without annotation: address
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

User.java

public class User implements Serializable{

@JsonProperty(value="prename")
private String m_name;

private Address m_address;

public User(String name, Address a) {
    m_name = name;
    m_address = a;
}

@JsonIgnore
public String getName() {
    return m_name;
}

public void setName(String name) {
    m_name = name;
}

public Address getAddress() {
    return m_address;
}

public void setAddress(Address address) {
    m_address = address;
}
}





How to get values of nested class attribute using reflection?

Currently I have classes with several nested classes inside is, like:

public class Foo {

  private Bar bar;

  //getter & setter

  public class Bar {

    private Abc abc;

    //getter & setter

    public class Abc {
      @RequiredParam
      private String property;

      //getter & setter
    }
  }

}

I am trying to get the value of the fields but I am having a hard time how to achieve this.

So far I have:

  public static boolean isValid(Object paramClazz) throws Exception {
    List<Class> classes = new ArrayList<>();
    getClasses(classes, paramClazz.getClass());

    for (Class clazz : classes) {
      for (Field field : clazz.getDeclaredFields()) {
        if (field.isAnnotationPresent(RequiredParam.class)) {
          field.setAccessible(true);
          //how to get the value? field.get(paramClazz) doesn't work
        }
      }
    }
    return true;
  }

  private static void getClasses(List<Class> classes, Class<?> clazz) {
    if (clazz.getDeclaredClasses().length > 0) {
      for (Class<?> c : clazz.getDeclaredClasses()) {
        getClasses(classes, c);
      }
    }
    classes.add(clazz);
  }

My goal is to the able to check if the field annotated with @RequiredParam is not null, so I have the method isValid() which will received a class and should be able to check all fields (even the ones inside nested classes) and see if any is missing.

The problem is when I try to call field.get() and I don't know which object I am supposed to pass to this method. Passing the highest level object won't work, because I need somehow to pass only the Abc object to the method.

How can I get the correct object to pass to the field.get() call, considering I can have more or less nested levels in my classes?





How to use Reflection to insert data with mysqli by bind_param method? what is difference of these two arrays?

As bind_param($types, $var1, $var2, $var3,..) method of mysqli_stmt class it gets just a series of $variables after second parameter (I want to pass array there), and the number of $variables is unknown in my case, I want to use Reflection in my insert($data) function. http://ift.tt/1TFBnWJ

I do not show the unnecessary part of my function, to avoid confusion...

public function insert($data)
{
    $types = 'sss';
    $values = array_values($data);

Removed unrelated code

    $ref    = new ReflectionClass($this->stmt);
    $method = $ref->getMethod("bind_param");

    //array_unshift($values,$types);                             1-option
    $values = array($types,'alex','alex@code.com','cats');       2-option

    $method->invokeArgs($this->stmt, $values);
    $done = $this->stmt->execute();

    $this->stmt->close();
    return $done;

}

As shown in

$method = $ref->getMethod("bind_param");

$method->invokeArgs($this->stmt, $values); 

In this part I use Reflection to pass array to second parameter of bind_param() method of $this->$stmt object.

$method->invokeArgs($this->stmt, $values); 

It doesn`t make mysqli insert into table with 1-option.

But mysqli inserts data when I use 2-option. Why? I have to use with 1-option as number of parameters is unknown.

How can I benefit from Reflection and mysqli it?

What is the difference between those two options(arrays)?





How to find out which property is used as a Foreign Key between two entities in code first approach

I'm using Entity Framework 5, code first approach. As there's no built in support for updating child entities in disconnected scenario, I'm building my own mechanism to do that. At some point I need to get the property of an entity with which it has a Foreign Key relationship with another (principal) entity. I've tried to get access to CSpace through

((IObjectContextAdapter)dbContext).ObjectContext.MetadataWorkspace.GetItems<MyEntity>(System.Data.Entity.Core.Metadata.Edm.DataSpace.CSpace)

but here I got a warning that said there's no implicit conversion between MyEntity and System.Data.Entity.Core.Metadata.Edm.GlobalItem.

I can't look for a property that has Foreign Key attribute because in most of my entities I use EF convention to get foreign keys automatically. So how one would go about finding which property is used for foreign key relationship.





Get JSON key of Field via Java Reflection

I have the folllowing problem. I want to get the "json-name" ("adr" if the @JsonProperty exist; "address" if the annotation is not here) of a field via java reflection.

User.java

public class User implements Serializable{
  @JsonProperty(value="adr")
  private Address m_address;

  public User(Address a) {
    m_address = a;
  }

  public Address getAddress() {
    return m_address;
  }

  public void setAddress(Address address) {
    m_address = address;
  }
}

The reflection

dObjectMapper mapper = new ObjectMapper();
for (Field field : User.class.getDeclaredFields(){
  field.setAccessible(true);
  // Convert object to JSON string
  try {
    //TODO
    String jsonName = mapper.foobar(field);
  } catch (JsonMappingException e) {
    e.printStackTrace();
  }
}

I hope the question is understandable.

Thanks for your answer.





Kotlin: Generics, reflection and the difference between type T and T:Any

If I try to access the javaClass of a generic type T the Kotlin compiler complains that T is not a subtype of kotlin.Any

class Foo<T> (val t: T ){
    val cls = t.javaClass // Error, T is not a subtype of kotlin.Any
}

If define T as a subtype of Any everything works ok.

class Bar<T:Any> (val t: T ){
    val cls = t.javaClass // OK
}

Q1) If type ´T´ is not a subtype of ´Any´ which class/classes can it be a subtype of ?

Q2) Do a javaClass exist for all instances of T and if so how do I access it ?





How to use reflection to check if a parameter is prefixed with keyword "this"? [duplicate]

This question already has an answer here:

public static class TEST_THIS
{
    public class TEST
    {
    }
    public static void Foo(this TEST t) { }
}

How to know parameter t was prefixed with "this" via ParameterInfo of t?





Get method name of property setter in c#

I am using FakeItEasy to check that a call to the public setter method of a property has been called.

The property is called Description, and at the moment I am testing it like this:

A.CallTo(model)
    .Where(x => x.Method.Name.Equals("set_Description"))
    .WithAnyArguments()
    .MustHaveHappened();

This works functionally, however the downside of using a magic string for the method name is that if I refactor the name of the property, the test will fail and I will have to manually change the strings in all of the tests.

Ideally, I would like to know of a way to do it like in this piece of pseudocode:

var setterName = model.GetType()
                         .SelectProperty(x => x.Description)
                         .GetSetterName();

A.CallTo(model)
    .Where(x => x.Method.Name.Equals(setterName))
    .WithAnyArguments()
    .MustHaveHappened();

This way, if I right-click refactor the Description property, the tests won't need to be updated. How can I do this?





Method YYY can not be reflected

I have a console application on .net framework 2.0. I added a link to the service(VS2010->Solution Explorer->Open context menu of project->Add web reference) by selecting it wsdl file that I've got (to access to the service, I do not have).

When you try to create a service object(SSDService ssd = new SSDService();), I get the error

"Method SSDService.SearchCaseInFirstInstanceCourt can not be reflected." Inner exception: "An operation can have only one in or out header of a given type. SSDService.Sender conflicts with another header field of the same type and direction."

How do I fix this error?

Link to files - http://ift.tt/1VDQTQX 1)Reference.cs 2)Link to wsdl file 3)Link to SSDService.xsd 4)Link to CommonTypes.xsd





mardi 23 février 2016

How to use reflection to go from array to a data structure in php

I read on php.net that the SplFixedArray has "The advantage is that it allows a faster array implementation" over regular arrays. Some how I also want to understand reflection. I cannot seem to get it to work:

$refDLL = new ReflectionClass( 'SplDoublyLinkedList' );
$method = $refDLL->getMethod( 'add' );
$keys = array_keys( $_GET );
$count = count( $keys );
$oIndex = 0;
while( $oIndex < $count )
{
    $method( // <-- this seems to be the point of failure
        $oIndex, 
        $_GET[$keys[$oIndex]] 
    );
    $oIndex++;
}

error:

PHP Fatal error:  Uncaught Error: Function name must be a string in 
C:\inetpub\wwwroot\objstr.php:26
Stack trace:
#0 {main}
  thrown in C:\inetpub\wwwroot\objstr.php on line 26





Getting values from object in java

How I can get those values from this object? I was trying to getFields, getDeclaredFields etc. but everything is empty.

enter image description here





why is the value of a child from Mirror.children prepended with the Xcode Project name?

I am printing the reflected properties of a struct instance by looping over the "children" of the Mirror of the struct, and I am seeing something I didn't expect. For the "store1" and "store" constants of the "Bookmark" structure (see screenshot), I see that the reflected values are "MirrorTest.BookmarkStore" for both (on the console log). Now, the prefix "MirrorTest" is the name of my Xcode project. I was expecting the value of to be just "BookmarkStore", not sure why the Xcode project name is being prepended. Any thoughts?

thanks

enter image description here





Restrict permissions to Drivers and Applications WinForms C#

I am currently creating a Sandbox Tool in WinForms to restrict access to certain permissions like FileIOPermission etc.. I have implemented what I think should work, but when running the Sandbox tool it does not produce any errors, it just opens the program without any exception errors which I am expecting!

I have included all Classes and code as this has me totally lost and any help / pointers would be greatly received!

Class Form1:

namespace SandboxACW
{
    public partial class Form1 : Form
    {
        List<String> listofDrives = new List<String>();
        List<String> listofPermissions = new List<String>();
        Sandbox sandbox = new Sandbox();
        Permissions permissions = new Permissions();
        private string pathToUntrusted;
        string[] allPermissions;
        List<String> CommandAgrs = new List<String>();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            driverLoad();
            permissionLoad();
        }

        public void driverLoad() {
            foreach (var Drives in Environment.GetLogicalDrives())
            {
                DriveInfo DriveInf = new DriveInfo(Drives);
                if (DriveInf.IsReady == true)
                {
                    clstboxDrives.Items.Add(DriveInf.Name);
                }
            }
        }

        public void GetArguments()
        {

            foreach (var arg in txtBoxArguments.Text.Split(new string[] {"\r\n","\n"}, StringSplitOptions.None))
            {
                CommandAgrs.Add(arg); 
            }
        }

        public void RestrictDrive()
        {
            PermissionSet permSet = new PermissionSet(PermissionState.None);
            if(listofDrives.Count != 0){
                foreach(string SelectedDrive in listofDrives){
                    permSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.NoAccess, SelectedDrive));
                }
            }
        }

        public void permissionLoad() {
            var interfaceType = typeof(IPermission);
            allPermissions = AppDomain.CurrentDomain.GetAssemblies()
              .SelectMany(x => x.GetTypes())
              .Where(x => interfaceType.IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract && x.Name != "PrincipalPermission" && x.Name != "SiteIdentityPermission" && x.Name != "StrongNameIdentityPermission"
              && x.Name != "UrlIdentityPermission" && x.Name != "ZoneIdentityPermission" && x.Name != "GacIdentityPermission" && x.Name != "PublisherIdentityPermission" && x.Name != "SqlClientPermission"
              && x.Name != "OleDbPermission" && x.Name != "OdbcPermission" && x.Name != "HostProtectionPermission")
              .Select(x => x.Name).ToArray();
            clstboxPermission.Items.AddRange(allPermissions);

        }

        private void clstboxDrives_SelectedIndexChanged(object sender, ItemCheckEventArgs e)
        {
            if (e.NewValue == CheckState.Checked)
            {
                listofDrives.Add(clstboxDrives.Items[clstboxDrives.SelectedIndex].ToString());
            }
            if (e.NewValue == CheckState.Unchecked)
            {
                listofDrives.Remove(clstboxDrives.Items[clstboxDrives.SelectedIndex].ToString());
            }
            RestrictDrive();
        }

        private void clstboxPermission_SelectedIndexChanged(object sender, ItemCheckEventArgs e)
        {
            if (e.NewValue == CheckState.Checked)
            {
                listofPermissions.Add(clstboxPermission.Items[clstboxPermission.SelectedIndex].ToString());
            }
            if (e.NewValue == CheckState.Unchecked)
            {
                listofPermissions.Remove(clstboxPermission.Items[clstboxPermission.SelectedIndex].ToString());
            }
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            try
            {
                open.Filter = "exe files (*.exe)|*.exe|All files (*.*)|*.*";
                if (open.ShowDialog(this) == DialogResult.OK)
                {
                    txtboxFilepath.Text = open.FileName;
                    pathToUntrusted = open.FileName;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Form1", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            if (pathToUntrusted != null){
                GetArguments();
                sandbox.SetupDomain(pathToUntrusted, listofDrives, listofPermissions);
            }
            else
            {
                MessageBox.Show("Please enter an .EXE file to be tested!","Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }
    }
}

Class Sandbox:

namespace SandboxACW
{
    public class Sandbox : MarshalByRefObject
    {
        public void SetupDomain(string pathToUntrusted, List<String> listofDrives, List<String> listofPermissions, params string [] Commandargs)
        {
            try
            {
                Object[] Parameters = { Commandargs };
                string untrustedClass = "";
                //PermissionSet ps = new PermissionSet(PermissionState.None);
                int index =  pathToUntrusted.LastIndexOf('\\');

                //Setting the permissions for the AppDomain. We give the permission to execute and to 
                //read/discover the location where the untrusted code is loaded.
                PermissionSet permSet =  Permissions.SetupPermissions(listofPermissions);
                if (listofDrives.Count != 0)
                {
                    foreach (var drive in listofDrives)
                    {
                        permSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.NoAccess, drive));
                    }
                }

                //Setting the AppDomainSetup. It is very important to set the ApplicationBase to a folder 
                //other than the one in which the sandboxer resides.
                AppDomainSetup adSetup = new AppDomainSetup();
                adSetup.ApplicationBase = Path.GetFullPath( pathToUntrusted.Substring(0, index));

                //We want the sandboxer assembly's strong name, so that we can add it to the full trust list.
                StrongName fullTrustAssembly = typeof(Sandbox).Assembly.Evidence.GetHostEvidence<StrongName>();

                //Now we have everything we need to create the AppDomain, so let's create it.
                AppDomain newDomain = AppDomain.CreateDomain("Sandbox", null, adSetup, permSet, fullTrustAssembly);

                AssemblyName selectedFilesAssemblyName = AssemblyName.GetAssemblyName(pathToUntrusted);
                string untrustedAssembly = selectedFilesAssemblyName.Name;

                Assembly selectedFileAssembly = Assembly.LoadFrom(pathToUntrusted);
                // needs fixing to GetTypes() array out of bounds!
                foreach (Type type in selectedFileAssembly.GetTypes()) {
                        untrustedClass = type.FullName;
                }
               // Type type = selectedFileAssembly.GetTypes()[2];

                string entryPoint = selectedFileAssembly.EntryPoint.Name;

                //Use CreateInstanceFrom to load an instance of the Sandboxer class into the
                //new AppDomain. 
                ObjectHandle handle = Activator.CreateInstanceFrom(
                    newDomain, typeof(Sandbox).Assembly.ManifestModule.FullyQualifiedName,
                    typeof(Sandbox).FullName
                    );
                //Unwrap the new domain instance into a reference in this domain and use it to execute the 
                //untrusted code.
                Sandbox newDomainInstance = (Sandbox)handle.Unwrap();
                newDomainInstance.ExecuteUntrustedCode(untrustedAssembly, untrustedClass, entryPoint, Parameters);
            } 
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message, "Sandboxer", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public void ExecuteUntrustedCode(string assemblyName, string typeName, string entrypoint, object[] parameters)
        {
            //Load the MethodInfo for a method in the new Assembly. This might be a method you know, or 
            //you can use Assembly.EntryPoint to get to the main function in an executable.
            MethodInfo target = Assembly.Load(assemblyName).EntryPoint;
            //MethodInfo target = Assembly.Load(assemblyName).GetType(typeName).GetMethod(entrypoint);
            try
            {
                //Now invoke the method.
                //bool retVal = (bool)target.Invoke(null, new object[] {parameters});
                target.Invoke(null, null);
            }
            catch (Exception ex)
            {
                // When we print informations from a SecurityException extra information can be printed if we are 
                //calling it with a full-trust stack.
                (new PermissionSet(PermissionState.Unrestricted)).Assert();
                MessageBox.Show(ex.Message, "Sandboxer", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //Console.WriteLine("SecurityException caught:\n{0}", ex.ToString());
                CodeAccessPermission.RevertAssert();
                //Console.ReadLine();
            }
        }
    }
}

Class Permissions:

namespace SandboxACW
{
    public class Permissions
    {
        public string[] selectedItem;

        public static PermissionSet SetupPermissions(List<string> checkedPermission)
        {
            PermissionSet permSet = new PermissionSet(PermissionState.Unrestricted);
            try
            {

                foreach (var test in checkedPermission)
                {
                    switch (test)
                    {
                        case "EnvironmentPermission":
                            permSet.AddPermission(new EnvironmentPermission(PermissionState.None));
                            break;
                        case "FileDialogPermission":
                            permSet.AddPermission(new FileDialogPermission(PermissionState.None));
                            break;
                        case "FileIOPermission":
                            permSet.AddPermission(new FileIOPermission(PermissionState.None));
                            break;
                        case "IsolatedStorageFilePermission":
                            permSet.AddPermission(new IsolatedStorageFilePermission(PermissionState.None));
                            break;
                        case "ReflectionPermission":
                            permSet.AddPermission(new ReflectionPermission(PermissionState.None));
                            break;
                        case "SecurityPermission":
                            permSet.AddPermission(new SecurityPermission(PermissionState.None));
                            break;
                        case "UIPermission":
                            permSet.AddPermission(new UIPermission(PermissionState.None));
                            break;
                        case "KeyContainerPermission":
                            permSet.AddPermission(new KeyContainerPermission(PermissionState.None));
                            break;
                        case "RegistryPermission":
                            permSet.AddPermission(new RegistryPermission(PermissionState.None));
                            break;
                        case "AspNetHostingPermission":
                            permSet.AddPermission(new AspNetHostingPermission(PermissionState.None));
                            break;
                        case "DnsPermission":
                            permSet.AddPermission(new DnsPermission(PermissionState.None));
                            break;
                        case "SocketPermission":
                            permSet.AddPermission(new SocketPermission(PermissionState.None));
                            break;
                        case "WebPermission":
                            permSet.AddPermission(new WebPermission(PermissionState.None));
                            break;
                        case "SmtpPermission":
                            permSet.AddPermission(new SmtpPermission(PermissionState.None));
                            break;
                        case "NetworkInformationPermission":
                            permSet.AddPermission(new NetworkInformationPermission(PermissionState.None));
                            break;
                        case "StorePermission":
                            permSet.AddPermission(new StorePermission(PermissionState.None));
                            break;
                        case "TypeDescriptorPermission":
                            permSet.AddPermission(new TypeDescriptorPermission(PermissionState.None));
                            break;
                        case "EventLogPermission":
                            permSet.AddPermission(new EventLogPermission(PermissionState.None));
                            break;
                        case "PerformanceCounterPermission":
                            permSet.AddPermission(new PerformanceCounterPermission(PermissionState.None));
                            break;
                        case "PrintingPermission":
                            permSet.AddPermission(new PrintingPermission(PermissionState.None));
                            break;
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Sandboxer", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return permSet;
        }  
    }
}

Apologies in advance if the code isn't clear enough, hopefully someone could give me some helpful advice. Thank you in advance.





Creating dynamic classes to be used in DbContext along with a Generic Repository that uses the DbContext

The problem have is - I can create the generic class however, when I try to DbSet the newly created class via the DbContext class, I always run into the problem that it cannot get the "Id" field. How can I control the MVC view to look at the dynamic class, but not the precompiled one.





Should functions preserve their name and length properties (and thus their reflective ability)?

As a functional programmer I regularly pass functions to higher order functions, to combine them in a specific way and create new behavior. Often HOFs serve as wrappers that – as a side effect - disguise the original properties of the given function, a curry function for instance.

I wonder if this reflective ability of functions should be preserved throughout the code, although this may result in considerable costs. Or is it poor style to build dependencies against such properties anyway?

If you think that this question is mainly opinion based, just answer the following:

Are there any use cases that rely on length or name in order to be implemented at all/effectively?





Why doesn't reflections.getSubTypesOf(Object.class) find enums?

If I have

Reflections reflections = new Reflections("my.package", classLoader, new SubTypesScanner(false));

then this finds my enum classes

Set<Class<? extends Enum>> enums = reflections.getSubTypesOf(Enum.class);

but this doesn't

Set<Class<?>> classes = reflections.getSubTypesOf(Object.class);

Is there a reason for this?


Reproducible example:

package cupawntae;

import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;

public class Reflector {
    public static void main(String[] args) {
        Reflections reflections = new Reflections("cupawntae", Reflector.class.getClassLoader(), new SubTypesScanner(false));
        System.out.println("Objects: " + reflections.getSubTypesOf(Object.class));
        System.out.println("Enums: " + reflections.getSubTypesOf(Enum.class));
        System.out.println("Enum's superclass: " + Enum.class.getSuperclass());
    }
}

Enum class:

package cupawntae;

public enum MyEnum {
}

Output:

Objects: [class cupawntae.Reflector]
Enums: [class cupawntae.MyEnum]
Enum's superclass: class java.lang.Object





Check fields attributes using reflection

I'm trying to find a fields in a class has a Obsolete attribute ,

What I have done is , but even thought the type has an obselete attribute its not found during iteration :

public bool Check(Type type)
{
    FieldInfo[] fields = type.GetFields(BindingFlags.NonPublic |  BindingFlags.Instance);

  foreach (var field in fields)
  { 
     if (field.GetCustomAttribute(typeof(ObsoleteAttribute), false) != null)
     {
        return true
     }
  }
}

EDIT :

class MyWorkflow: : WorkflowActivity
{
 [Obsolete("obselset")]
 public string ConnectionString { get; set; }
}

and using it like this , Check(typeof(MyWorkflow))





Load all types from all assembly in project

I'm trying to search all types that belong to a spesific to all assembly referenced by my project

What I have done , load all assemblies in my project by this :

var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
var loadedPaths = loadedAssemblies.Select(a => a.Location).ToArray();

 var referencedPaths = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
                var toLoad = referencedPaths.Where(r => !loadedPaths.Contains(r, StringComparer.InvariantCultureIgnoreCase)).ToList();
                toLoad.ForEach(path => loadedAssemblies.Add(AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(path))));

And then search for specific types

const string @namespace = "name space to search"

 var   types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes())
                .Where(t => t.IsClass && t.Namespace == @namespace );

now when I try to iterate over the types , I get a loader exception "Could not load file or assembly 'System.Windows"

and system.windows is not an assembly refrenced by my project





How to get name of method and class from where trace logs are sent in .net

I wrote my own custom trace listener and now I'm using TraceSource object to call all the custom methods that I have overridden from virtual methods of base class TraceListener namely various overloads of TraceData(..), TraceEvent(..) and TraceTransfer(..) etc.

While using TraceSource object to log traces I won't be directly calling any of my custom methods (on my custom listener) rather I would grab an instance of TraceSource and will call (on it) TraceSource object's own methods such as TraceData(..),TraceEvent(..) and TraceInformation(..) and these methods will internally call my custom methods.

Now the thing is that I need to find the name of the class and method where the trace messages or logs are coming from. I'm searching all over the internet and found something over here C# how to get the name of the current method from code

But it still is not giving me sufficient feedback as to how would I avoid compiler optimizations in production environment ( As the link given above says at one point that these attributes are needed all the way up the stack trace to avoid method in-lining and tail-recursion in production) but I can't put attributes such as

     [MethodImpl(MethodImplOptions.NoInlining)]

on TraceSource class' methods (as they are already out the box in-built functions which I have no control over) though I can do the same for my custom methods but only doing that won't solve my problem. Having said that, another problem that I'm facing (attributes issue apart). How can I send name of the class (in my case XYZ class) and the method(MyMethod) to my custom trace listener methods (since MyMethod is not directly calling my custom methods only the TraceSource's TraceData(...) is internally calling one of my custom methods), capture this info inside of my custom methods and then do whatever I want to do with that info.

 public class XYZ
 {
     static readonly TraceSource source = new TraceSource("somesource");
     public void MyMethod()
     {  
        source.TraceData(eventType.Error,1, "This is an error message");
     }
}





GetTypes from an Assembly that is an external dll

I have 2 projects in my solution. My first project is trying to search for all classes that are in a specific namespace and implement a specific interface.

My website runs of the first project and imports the second as a compiled dll. Now if I were to try and search for assemblies in a namespace that resides in my first project, then I have no issues, however the moment that I point to my second project, it can never find anything. Here is my code:

const string @namespace = "MySecondProject.Models";
var reports = from t in Assembly.GetExecutingAssembly().GetTypes()
                      where t.IsClass && t.Namespace == @namespace && typeof(IMyInterface).IsAssignableFrom(t)
                select t;

I have also tried setting up the namespace variable to include second project name as i know this can be an issue when creating an instance of an object via reflection (encountered that before)

const string @namespace = "MySecondProject.Models,MySecondProject";

I am trying to understand why I am getting back no results and what is the correct way of doing this?

I have also tried removing my interface check, but I still get same results.





Java: How do i best determine whether a local class defined in an initializer block requires an enclosing instance for instantiation?

Right now I'm implementing a method that has one parameter of the type Class and this method returns a boolean if the given class object requires an instance of it's enclosing class for it to be instantiated.

This method currently works as follows:

    if (clazz.getEnclosingClass() == null) {
        return false;
    }
    if (clazz.isAnonymousClass() || clazz.isMemberClass()) {
        return !Modifier.isStatic(clazz.getModifiers());
    }
    if (clazz.getEnclosingConstructor() != null) {
        return true;
    }
    final Method enclosingMethod = clazz.getEnclosingMethod();
    if (enclosingMethod != null) {
        return !Modifier.isStatic(enclosingMethod.getModifiers());
    }

To explain why it is designed as such:

  1. It first checks if it's a top-level class, if so, the algorithm can safely return false
  2. If the class is anonymous or a member class, it requires a closing instance if it's not static (an anynmous class is automatically static if it's declared in a static constructor/method/initializer-block)
  3. The class can now be assumed to be a local class (disregarding arrays and primitives), so it's defined in either a constructor, method or initializer. However, unlike an anonymous class, a local class is never considered static, but still requires an enclosing instance if the local class is defined in a non-static block.
  4. A constructor is never static, so in that case return true
  5. If it's defined in a method, return true if the method isn't static

I need step 6 to determine whether the local class resides in either a Static Initializer Block or an Instance Initializer Block, so I'm done with the implementation for this function.

So here's where the reflection API falls a bit short. There's no method Class.getEnclosingInitializer() or such, nor is there a class that represents an initializer in the reflection package.

Isn't an initializer block a member of a class? In the java 1.8 spec the Member interface only has the implementation classes Field, Executable (with subclasses Constructor and Method), and then there's MemberName that's out of the scope for most users of reflection.

I'm not really sure if the people behind the spec forgot about this situation and local classes actually should be static if declared in a static method/initializer (like anonymous classes). But it seems to me that it's lacking this last bit of consistency from this point of view.

So does anybody have an idea on how to ascertain in which type of initializer block the local class is declared?

I'm not really keen on digging through fields for a synthetic one of a type that equals it's enclosing class, or looping through it's constructors for something akin to that (sidenote: Parameter objects from Constructor.getParameters() always return false on isImplicit() and isSynthetic() no matter what i try... that just seems wrong). So if I can avoid such solutions that would be great.





lundi 22 février 2016

C# Sort list of class properties based on another List strings

I loop through the list of properties using reflection and assign the table cell that value. My class properties that are being looped through are assigned to the wrong column (header).

How do I sort the dataList properties names based on the header list, they are both named the same? I would rather do it this way than sort header list based on properties.

dataList type will always be a class with properties.

public void SetTableStrong<T>(List<T> dataList, List<string> header)
{       
    // Define our columns
    Column c = null;
    foreach (var item in header)
    {
        c = table.addTextColumn(item);
        c.horAlignment = Column.HorAlignment.CENTER;
    }

    // Initialize Your Table
    table.initialize();
    table.data.Clear();

    foreach (var item in dataList.Select((value, index) => new { value, index }))
    {
        Datum d = Datum.Body(item.index.ToString());

        //Property set to wrong header because they are not sorted to the same as headers.
        foreach (var property in item.value.GetType().GetProperties())
        {
            var value = property.GetValue(item.value, null);

            if (value == null)
                continue;

            d.elements.Add(value.ToString());
        }
        table.data.Add(d);
    }

    // Draw Your Table
    table.startRenderEngine();
}





Clojure list leiningen namespaces

Incanter, a graphing/plotting tool, works fine:

[incanter "1.5.6"] ; in project.clj
; in repl:
(do (use '(incanter core stats charts)) (view (histogram (sample-normal 1000))))

But how can I programmatically list namespaces from leiningen-dependencies? all-ns does not work:

; comes up empty UNTILL you (use 'incanter.charts):
(filterv #(.contains % "charts") (mapv str (all-ns)))

Is there a way to do this?





Create an instance of a class in a different assembly by strings

I need to create an instance of a class, while only having the full class name (with namespaces) and the file-name of the assembly where the class is defined. I know that the assembly is in the current working directory. The default constructor (with no arguments) should be used, as it is the only one available.

After some google, stack overflow and MSDN I am still not sure what the best solution is. Multiple assemblies will be loaded, so using an application domain would be good (?).

The application domain documentation says, I should use CreateInstanceAndUnwrap, but there I need the full assembly name. And as far as I know, I only can get it by loading the assembly. This seems somewhat very inefficient.

Which is a good way to create an instance of a class in a currently unloaded assembly?

Thanks!





How can i initialize all of the members of class at once in c#?

I have a 3 layer architecture application. the business logic has all the member fields like:

 class Demo
{
public Int64 Id{get; set;}
public string InformationLog{get; set;}
}

Currently i am initializing all of the members in the constructor of my class one by one. Is there any way to initialize all of the members at once? something like reflection?





Java: Best practice to check to which library a given class belongs? [on hold]

My task is to ensure that the fields in a given set of classes are only of specific type: Only classes from the jdk and our own projects are permitted. Any 3rd party library is forbidden.

The problem is that these classes are littered all over our projects, and I cannot simply remove any dependencies in the projects these classes belong to.

Thus I want to write an architecure test that will check this, and I have been searching for ways to evaluate this from within code. The most helpfull source I have found is this. To summarize, there seem to be 3 approaches to check the "origin" of a class:

  • Check the name of the given class: Does the package name, e.g. "java.lang", belong to some kind of approved white list.

This first approach feels uncomfortable to me, as it is not that hard to bypass a rule based on the package name. It might even happen by accident that a package name is the same as the one of some other package on an approved white list.

In a short experiment, I have no problem defining my own "java.lang.String" class. However, when called at runtime, an exception is thrown: java.lang.SecurityException: Prohibited package name: java.lang But how do I stop someone from duplicating any Class from my companies project?

  • Check the ClassLoader of a given class: Mr Friedmann-Hill points out that: "In general, a different ClassLoader will be used for system classes vs. application classes."

I lack information to have more than a gut feeling about this approach. However, I feel uncomfortable relying on the fact that specific classes will be laoded by specific class loaders. If you think this is a good approach, can you point me to any information that might help me?

  • Check the name of a *.jar file a class is loaded from. This is also done via the ClassLoader.

I do not think this approach would work for us. We use maven, and and with every new version maven changes the name of the .jar file. Thus the test would require constant maintenance to keep .jar file names up to date.

Is there any "Best Practice" to ensure that only specific libraries are used within some classes?

Thank you! Any help is greatly appreciated!





Where is the right place for annotation processing?

I write simple application. I don't want to use any frameworks. Please suggest me right place to hold annotation processing.

I have a few lines in main method:

String myString = (@NonNull String)list;

And I created @interface:

@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
public @interface NonNull {
}

Which step should I take next? Can I work with annotations without using reflection? Could you expose for me samples of such annotation processing code?





How to set array value to a field in golang using reflect?

I have a Struct with following fields

type Config struct {
        Address[]string
        Name string
}

I am reading the values for this Config from a file in JSON format

{
   "Address": ["xx.xx.xx.xx","xx.xx.xx.xx"],
   "Name":"Name"
}

I have used Reflect to identify the type and set its value to Config.I am able to set the value of Name field using func (v Value) SetString(x string) which is an inbuilt method in reflect. Is there a way to set []string values directly to a field? Please help.





Create new class instance / reset class instance of a class instance that is inherited from an abstact base class

Prior I'd like to appologize for the long title but I didn't figure out a shorter version.

I have an abstract base class that delivers generic methods to access functions in test classes, that derive from my base class.

I have a collection of classes that itself have a reference to those test classes.

The struct is:

// A really simplified example for my manager
Collection<AbstractBaseClass> Manager = new Collection<AbstractBaseClass> 
{
    TestClassA();
    TestClassB();
}

Now I come to the point that I need to kill and recreate the instance in the collection of the testclass without knowledge of which testclass is in this collection.

I try to do sth. like (pseudocode)

Manager[0] = null;
Manager[0] = new (object)Manager[0].GetType();

I already stumbled over Get a new object instance from a Type but this - however - doesn't work because CreateInstance is no member of System.Activator. Also I cannot find the ObjectType class.

Long explaination, short question: How can I create a new instance from a class where I only have an Instance?

Thank you very much, ADP.





dimanche 21 février 2016

Getting the values passed to an instance method

I have a method that I want to be able to tell what values are passed to it each time it is called.

For instance:

public void doStuff(String val1, int val2) {

}

public static void main(String[] args) {
    doStuff("Hello", 5);
    doStuff("There", 6);
}

Now I realize I could just print val1 and val2 but what I would like to do is be able to do this using something along the lines of reflection. I can currently grab the type but I am not sure how to grab the actual value passed to a specific instance.





Get type of a field of class

I have classes like this:

class A
{
    public int x;
    public int y;
}
class B
{
    public int x;
    public int y;
}
class C
{
    public A a;
    public B b;
}

public class Test<T> where T : class, new()
{
     public Test()
     {
        FieldInfo[] x = typeof(T).GetFields().ToArray();
        Type y = x[0].GetType();
     }
}

When I declare Test<C> c = new T typeof(T).GetFields().ToArray() Returns the two fields a of type A and b of type B as expected. but when I want to get type of first field itself, like this: Type y = x[0].GetType();, the value of y is System.Reflection.RtFieldInfo and not A

Why is it so? I need to get to the class A so that I can get its fields and ...





Is there a way to get the MethodInfo of a private method inside a Portable Class Library code?

I have a private method that I need to get its MethodInfo inside a PCL code.

this.GetType().GetTypeInfo().GetDeclaredMethods("ToNullableDouble").First(m=>m.IsStatic && m.IsPrivate)

Above code doesn't work because GetDeclaredMethods returns only public methods.





turn reflect into comparable data

I want to be able to compare the type of an object using reflect. Here is my code:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    tst := "cat"
    if reflect.TypeOf(tst) == string {
        fmt.Println("It's a string!")
    }

}

This gives me an error type string is not an expression. How can I fix this only using reflect? (no type switches, etc.)





How to set a struct member that is a pointer to a string using reflection in Go

I am trying to use reflection to set a pointer. elasticbeanstalk.CreateEnvironmentInput has a field SolutionStackName which is of type *string. I am getting the following error when I try to set any value:

panic: reflect: call of reflect.Value.SetPointer on ptr Value

Here is my code:

    ...
newEnvCnf := new(elasticbeanstalk.CreateEnvironmentInput)
checkConfig2(newEnvCnf, "SolutionStackName", "teststring")
    ...
func checkConfig2(cnf interface{}, key string, value string) bool {
    log.Infof("key %v, value %s", key, value)

    v := reflect.ValueOf(cnf).Elem()
    fld := v.FieldByName(key)

    if fld.IsValid() {
        if fld.IsNil() && fld.CanSet() {
            fld.SetPointer(unsafe.Pointer(aws.String(value)))
//aws.String returns a pointer

...

Here is the log output

time="2016-02-20T23:54:52-08:00" level=info msg="key [SolutionStackName], value teststring" 
    panic: reflect: call of reflect.Value.SetPointer on ptr Value [recovered]
        panic: reflect: call of reflect.Value.SetPointer on ptr Value





How to get the current ASP.NET core controller method name inside the controller using Reflection or another accurate method

I want to get the current method name of my ASP.NET Core controller

I have tried getting the method name through reflection

    [HttpGet]
    public async Task<IActionResult> CreateProcess(int catId)
    {
        string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;

but this gives me a value of MoveNext and not CreateProcess

Take note I don't want to use the ViewContext

string methodName = ActionContext.RouteData.Values["action"].ToString();

as I lowercase my urls via the startup settings.The above will get me createprocess instead of CreateProcess

I preferably want an easy one liner as not a multiline extension method.





samedi 20 février 2016

Pharo: How to compare objects in different inspectors?

I am using Pharo 4. Suppose my objects already implemented nice equality and hash methods.

How do I compare two or N objects in different inspectors?

I tried allInstances but is becoming tedious after a while.





UWP Subscribe to an event dynamically using generics and reflection

I'm trying to subscribe to a runtime event dynamically using generics and reflection. Purpose is to be able to subscribe to e.g. the PointerReleased event of a Grid using XAML and execute a command when the event is raised.

<Grid namespace:CommandExtension.Event="PointerReleased"
      ...>
</Grid>

So far i have the following code:

var eInfo = d.GetType().GetRuntimeEvent(e.NewValue.ToString());

if (eInfo != null)
{
    // Get the type of the event handler
    var handlerType = eInfo.EventHandlerType;

    // Create the add handler using CreateAddFunction and reflection
    var addFunc = typeof(CommandExtension).GetMethod(nameof(CreateAddFunction), BindingFlags.Instance | BindingFlags.NonPublic)
                                          .MakeGenericMethod(handlerType);
    dynamic add = addFunc.Invoke(new CommandExtension(), new object[] { eInfo, d });

    // Create the remove handler that is stored for removing the handler if the event changes
    Action<EventRegistrationToken> remove = (a) => { eInfo.RemoveMethod.Invoke(eInfo, new object[] { a }); };

    // Create the handler
    var action = new Action<object, RoutedEventArgs>(CommandInvoke);
    var invoke = action.GetType().GetMethod("Invoke");
    var expressionParams = handlerType.GetMethod("Invoke").GetParameters().Select(p => Expression.Parameter(p.ParameterType)).ToArray();
    var handler = Expression.Lambda(handlerType,
                                    Expression.Call(Expression.Constant(action),
                                                    invoke,
                                                    expressionParams[0], expressionParams[1]),
                                    expressionParams)
                            .Compile();

    // Add the handler
    var runtimeMarshalAdd = typeof(WindowsRuntimeMarshal).GetMethod("AddEventHandler", BindingFlags.Static | BindingFlags.Public)
                                                         .MakeGenericMethod(handlerType);
    runtimeMarshalAdd.Invoke(null, new object[] { add, remove, handler });
}

// T is the type of the event handler e.g. RoutedEventHandler
private Func<T, EventRegistrationToken> CreateAddFunction<T>(EventInfo eInfo, DependencyObject d)
{
    return new Func<T, EventRegistrationToken>((a) => { return (EventRegistrationToken)eInfo.AddMethod.Invoke(d, new object[] { a }); });
}

Now whenever runtimeMarshalAdd.Invoke is invoked an exception stating that the operation would not be available:
Exception thrown: 'System.InvalidOperationException' in mscorlib.ni.dll ("The API 'System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler[PointerEventHandler]
(System.Func'2[Windows.UI.Xaml.Input.PointerEventHandler,System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken], System.Action'1[System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken], Windows.UI.Xaml.Input.PointerEventHandler)' cannot be used on the current platform. See http://ift.tt/1mu4Xh2 for more information.")

However doing the same stuff non-generic works.

Button b = new Button();
var eInfo = b.GetType().GetRuntimeEvent("PointerReleased");

Func<PointerEventHandler, EventRegistrationToken> add = (a) => { return (EventRegistrationToken)eInfo.AddMethod.Invoke(b, new object[] { a }); };
Action<EventRegistrationToken> remove = (a) => { eInfo.RemoveMethod.Invoke(eInfo, new object[] { a }); };
PointerEventHandler handler = CommandInvoke;

WindowsRuntimeMarshal.AddEventHandler(add, remove, handler);

Am i missing something in my attempt of adding the handler?