dimanche 31 décembre 2017

C# Dynamically fitted types

I want to dynamically fit type to argument in my method yet before compiling, i mean:

public class Foo
{
    public int Prop1;
    public string Prop2;
}

public class Program
{
    public static void Main(string[] args)
    {
        Foo foo = MakeMethod(x => x.Prop1, 5); //good, Prop1 is int type, 5 isn't underlined in red in VS
        Foo foo = MakeMethod(x => x.Prop2, 10); //bad, Prop2 is string, not int, VS underlines 10 in red, and I want this behaviour
    }

    private static Foo MakeMethod(Func<Foo, object> prop, object val)
    {
        Foo result;
        //do some stuff
        return result;
    }
}

I know I should do something with object type, but i dunno what. I could simply check if second generic prop argument is the type of val, otherwise do return in my method, but that's not satisfying me. I don't want to use dynamic type either because I get exception after running my program, not at the code writing stage.





Determine base classes not in standard lib (Java or Scala) with runtime reflection

I'm generating GraphQL definitions from Scala types but can't find anything in the runtime reflection API to only get base classes that are "user defined" i.e. not part of the Scala or Java standard library.

As of right now I just have a set of the ones I know pops up e.g. Any, Object and about 8 others. Those are only in the list because they're what showed up when I was writing unit tests. Ideally I don't want a manual list, seems brittle as new types are added it'll probably break.

I don't know if this is possible with macros but that's not an option. After experimenting with macros there were too many bugs around it, including it causing the compiler to crash and the fix for that bug is suppose to be in the latest zinc but I can't use it because I'm using Gradle which can only use the 0.x.x zinc series due to namespace changes in the 1.x series.

So all that being said, does anyone know if there's a means of determining baseclasses of a type that are not from the standard libraries?





samedi 30 décembre 2017

Reflection - Set Interface Type Field

I am using reflection to edit a private (final) Map, then save it back to its original field (since its object class has no public methods for editing the map):

    Field field = null, field2 = null, modifiersField = null;
    // Get map field
    field = SimpleReloadableResourceManager.class.getDeclaredField("domainResourceManagers");
    // Make accessible
    field.setAccessible(true);

    // Get instance
    @SuppressWarnings("unchecked")
    Map<String, FallbackResourceManager> domainResourceManagers = (Map<String, FallbackResourceManager>) field.get(Minecraft.getMinecraft().getResourceManager());
    if (domainResourceManagers.get(FinalStrings.ID + "tmp") == null || !(domainResourceManagers.get(FinalStrings.ID + "tmp") instanceof ImportResourceManager)) {

        // Access other private resource
        field2 = Minecraft.class.getDeclaredField("metadataSerializer_");
        // Make accessible
        field2.setAccessible(true);
        MetadataSerializer ser = (MetadataSerializer) field2.get(Minecraft.getMinecraft());

        // Edit map instance
        domainResourceManagers.put(FinalStrings.ID + "tmp", new ImportResourceManager(ser));

        // Remove final modifier
        modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.set(field, field.getModifiers() & ~Modifier.FINAL);
        // Set map field (throws exception)
        field.set(domainResourceManagers, Minecraft.getMinecraft().getRenderManager());
    } else {
        field.setAccessible(false);
        return;
    }

This is throwing an exception saying that a Map cannot be set to a HashMap:

 java.lang.IllegalArgumentException: Can not set final java.util.Map field net.minecraft.client.resources.SimpleReloadableResourceManager.domainResourceManagers to java.util.HashMap

But java.util.Map is an interface, so I cannot set this field without constructing a new interface object in the middle of my code.

How should I go about using reflection to set an interface type field?





Kotlin superClass Kclass

I have definiction of the function

abstract class AbstractDao<T>(private val dataStore: KotlinEntityDataStore<Persistable>): Dao<T> where T: Persistable 

and I need to get Kclass from type T. It is possible in Kotlin ?





vendredi 29 décembre 2017

In scala, How could Map[_,_] and scala.collection.immutable.Map[_,_] have different TypeTag?

They refer to the same thing, yet when I compare 2 type tags:

Map[_, _] did not equal scala.collection.immutable.Map[_,_]
ScalaTestFailureLocation: 
Expected :scala.collection.immutable.Map[_,_]
Actual   :Map[_, _]

How could this happen in a typed language? How do I make them identical?





Dealing with HashMap in Reflection

Got a school-project in java, using Reflection, I managed to handle this topic except for dealing with a HashMap.

Say we have a Shape class, and polygons that extend Shape.
Every polygon inherits an ID and a name. Here's a short example for implementation with Triangle:

Class Shape{
  private static int id_counter;
  protected ID;
  protected Shape(String name){
    ID = id_counter;
    id_counter++;
    this.name = name;
  }
}

Class Triangle {
{
  public Triangle(Sting name, Point[] vertices)
  {
    super(name);
    /* some operations to define Triangle vertices*/
  }
  public int getID()
  {
    return this.ID;
  }

It's required to perform actions on the polygons by their ID only, therefore I used a HashMap called shapesHash:

HashMap <Integer, Shape> shapesHash = new HashMap <Integer, Shape>;

Things started to get tricky when I tried to create new shapes using Reflection. In Main void, I declared as follows (skipping the required try-catch wrap):

Class<? extends Shape> myClass = Class.forName("polygonName").asSubclass(Shape.class);
// String "polygonName" is given
Constructor<?> myConstructor = myClass.getDeclaredConstructor();
Object myObject = myConstructor.newInstance(name, points);
// String "name" and Points 'points' are given
Method myMethod = myClass.getMethod("getID");
Object result = myMethod.invoke(null);
shapesHash.put( (Integer) result, (Class<? extends Shape>) myClass);   

The problem is that I tried to figure out what to put as a second argument,
instead of (Class<? extends Shape>)myClass
I tried many varieties of casting, and no casting at all - but didn't succeed (I get a compilation error).

What can I do in this situation?





How to call all methods annotated @someAnnotation if this methods are in other package and class?

I fave an annotation in package "fillers":

  package fillers;
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface someAnnotation {
    }

I have methods:

package fillers;
      @someAnnotation
        public static void randomized() {
            System.out.println("one");
            }
        }

        @someAnnotation
        public static void sortedArray() {
           System.out.println("two");
        }

And I want to invoke all annotated methods from another package. And I did next:

package analyzer;
public class Analyzer {
     public static void runAllAnnotatedWith() throws Exception {
         Reflections reflections = new Reflections(new ConfigurationBuilder()
      .setUrls(ClasspathHelper.forPackage("someAnnotation.ArrayFiller"))
                 .setScanners(new MethodAnnotationsScanner()));
         Set<Class<? extends ArrayFiller>> subTypes = reflections.getSubTypesOf(ArrayFiller.class);
         Set<Method> methods = reflections.getMethodsAnnotatedWith(Filler.class);

         for (Method m : methods) {
             // for simplicity, invokes methods as static without parameters
             m.invoke(null);
         }
     }
}

And i got this:

Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/base/Predicate
    at analyzer.Analyzer.runAllAnnotatedWith(Analyzer.java:22)
    at Main.main(Main.java:11)
Caused by: java.lang.ClassNotFoundException:.......

In my mind, exception is becouse of wrong reflection. But I don`t understand fow to fix it.





Kotlin/Android – KotlinReflectionInternalError in Data Class with a lambda

kotlin.reflect.jvm.internal.KotlinReflectionInternalError: Introspecting local functions, lambdas, anonymous functions and local variables is not yet fully supported in Kotlin reflection

This exception comes from toString() of a data class.

The data class contains a lambda.

I can't reproduce it in my environment.

Do I need to override toString() to exclude the lambda? Or lambdas are not allowed in data classes at all?

data class PersistJob(
        private val id: Int,
        private val delay: Long = 10_000L,
        private val maxDelay: Long = 60_000L,
        private val iteration: Int = 0,
        private val block: suspend (Int) -> Boolean) {

    fun getDelay() = minOf(delay, maxDelay)
    fun withDelayIncreased() = copy(
            delay = minOf(delay * 2, maxDelay),
            iteration = iteration + 1)

    suspend fun execute() = block(iteration)
}

Line producing the error:

val job: PersistJob = ...
log.debug("start job id($id): $job")`// job.toString()





lambda expression cast from interface

I have following interface:

public interface IHasSchoolId
{
    long? SchoolId { get; set; }
}

and following entity:

public class Student : IHasSchoolId
{
    long? SchoolId { get; set; }
}

then there is following entity manager implementing empty interface IEntityManager<T>:

public class HasSchoolIdManager: IEntityManager<IHasSchoolId>
{
    public static Expression<Func<IHasSchoolId, bool>> Filter()
    {
        return x=> x.SchoolId != null; //this is just an example
    }
}

and finally I have following method:

private Expression<Func<TEntity, bool>> GetFilters<TEntity>()
{
    Expression<Func<TEntity, bool>> result = null;
    var entityManagers = //geting entitymanagers that are assinable to TEntity, like the one above and a lot more like IEntityManager<Student> itself
    foreach (var entityManager in entityManagers)
    {
        var filterMethod = entityManager.GetMethod("Filter");
        if (filterMethod != null)
            result = AndAlso(result, (Expression<Func<TEntity, bool>>) filterMethod.Invoke(null, null)); //this line throws exception
    }
    return result;
}

and then when I'm calling the method like GetFilters<Student>() im getting following exception:

System.InvalidCastException: 'Unable to cast object of type 'System.Linq.Expressions.Expression[System.Func[WebCore.Models.Infrastructure.Interfaces.IHasSchoolId,System.Boolean]]' to type 'System.Linq.Expressions.Expression[System.Func[WebCore.Models.Student,System.Boolean]]'.'

by the way, this is my AndAlso method which works fine:

private Expression<Func<T, bool>> AndAlso<T>(
        Expression<Func<T, bool>> expr1,
        Expression<Func<T, bool>> expr2)
{
    if (expr1 == null)
        return expr2;
    if (expr2 == null)
        return expr1;
    ParameterExpression param = expr1.Parameters[0];
    if (ReferenceEquals(param, expr2.Parameters[0]))
    {
        return Expression.Lambda<Func<T, bool>>(
            Expression.AndAlso(expr1.Body, expr2.Body), param);
    }
    return Expression.Lambda<Func<T, bool>>(
        Expression.AndAlso(
            expr1.Body,
            Expression.Invoke(expr2, param)), param);
}

and here is my empty IEntityManager interface:

public interface IEntityManager<T>
{

}

Note: not all my entities implements IHasSchoolId interface, there are many other interfaces, this is just an example

i think my question is, how to cast from Expression<Func</*an interface*/, bool>> to Expression<Func</*a class that implements that interface*/, bool>> using reflection because as you can see, im calling the filter method using reflection





jeudi 28 décembre 2017

C# Can't reflect into private field

I got an issue.

In Unity I want to reflect into a private field. But I always get null for the fieldinfo. what am I doing wrong?

public abstract class _SerializableType
{
    [SerializeField] private string name;
}

// because I am using a CustomPropertyDrawer for all inherited from _SerializeType
public class SerializableType<T> : _SerializableType { }
public class SerializableType : _SerializableType { }

so using this method should actually work.

        // propertyPath in that case is "name"
        FieldInfo info = type.GetField(propertyPath, BindingFlags.Instance
                         | BindingFlags.Public | BindingFlags.NonPublic);

What am I doing wrong?

I am calling this method in a managed library that has its own CustomInspector. so it reflects into every field and figure how to display it. AppDomain is fullyTrusted. I don't know what else could be of importance...





How to find dependency assembly path in c# .Net

I am trying to get the dependency assemblies and the location where it is loading.

To find the dependencies I am using the following code.

var assemblies = Assembly.LoadFile("C:\\My Folder\\ MyApp.exe").GetReferencedAssemblies();

I am using the for-each to get the list of assembly names to find the dependency list.

  1. How to get the location of each dependency assembly?

  2. How to get the dependency of dependent assemblies? For example, if am using myAppBase.dll in the MyApp application, How can I get the dependencies of myAppBase.dll.





mercredi 27 décembre 2017

GsonBuilder or Apache Common ReflectionToStringBuilder? How to create your own "template"?

I need to get the values of all possible variables (even if the field is private) of any object. I've seen that some asked the same questions before and I've seen different ways to solve this.

For example I have some class:

public class Person{
    private String name;
    private int age;
    private Date birthday;
    private Person father;
}

It's a good idea also to use Apache Common ReflectionToStringBuilder:

public String getAllValues(Object o){
   return ReflectionToStringBuilder.toString(o, new MultilineRecursiveToStringStyle());
}

The output looks like that

Main$Person@782b3a41[
name=John Jones,
age=32,
birthday=java.util.Date@1fb2eseb[
 ],
 father=Main$Person@11adc27[
  name=Michael Jones,
  age=72,
  birthday=<null>,
  father=Main$Person@2e1fgc38[
  name=Jamie Jones,
  age=99,
  birthday=<null>,
  father=<null>
  ]
 ]
]

And I'd like to have something like that:

name: "John Jones"
age: 32
birthDate: '1986-05-03'
father:
 name: "Michael Jones"
 age: 72
 birthday: null
 father:
       name: "Jamie Jones"
       age: 98
       birthday: null
       father: null

As I understand I need to create my own MyStyle class that extends Apache Common's MultilineRecursiveToStringStyle, don't I? Could you please point me to what exactly I should override? Is there any easier solution maybe?





ruby/irb get scope info for method

Can IRB tell me the scope of a class/object/variable/method?

For instance puts.

I am imagining something like describe puts would output information that puts is a method of object and perhaps where its source is located.





How do I get all classes within a package? [duplicate]

This question already has an answer here:

I have a function:foo.register("string", new Class("string"); An example of this would be: foo.register("emp1", new Stu("jack"); //Stu being a class in a random package, for this instance "com.sof.people"

The problem is I have to repeat this function for every class within in package . For example in "com.sof.people" their is Stu.class, Stu2.class, Stu3.class, exc. Is it possible to simply search the package and call the function based on the classes within the package.

In a perfect world it would work something like this:

public static void registerAll(String string1, String string2) {
    for(Class c: Class.fromPackage("com.sof.people") {
        foo.register(string1, new c(string2);
      }
}





Finding asp.net webform methods through reflection

I am trying to find a method in a asp.net code behind class through reflection through the following code placed on the same page I querying.

MethodInfo MyMethod = this.GetType().GetMethod("Create", BindingFlags.Static);

But this always returns null, what is more strange is that at runtime the type of this is not MyAssembly.MyPage that type shows as ASP.MyPage_aspx. What is this type? and why am I not seeing the original code behind class type? and where do I find it?

Any idea how to solve this problem?





mardi 26 décembre 2017

Setting private final field via reflection fails when ctor is removed

Suppose I have the following class:

public class SomeClass {

    private final int num;

    public SomeClass(int num) {
        this.num = num;
    }

    public int getNum() {
        return num;
    }

}

When I execute this code to set the num field, everything is fine:

SomeClass obj = new SomeClass(0);

final Field field = SomeClass.class.getDeclaredField("num");
field.setAccessible(true);
Field modField = Field.class.getDeclaredField("modifiers");
modField.setAccessible(true);
modField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(obj, 1);

System.out.println(obj.getNum()); // Prints 1 instead of the initial value 0.

However, when I remove the constructor from SomeClass, this doesn't work anymore and the println statement prints 0.

Can anyone explain this behavior?





Java Reflection - IllegalAccessException on "set" if preceded by "get" operation

I was trying to change the value of a private static final field using reflection (yes, that's probably a very bad idea to begin with, I know). And, well, for the most part it works fine using following code:

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class A {

    public static void main(String[] args) throws ReflectiveOperationException {
        System.out.println("Before :: " + B.get());
        Field field = B.class.getDeclaredField("arr");
        field.setAccessible(true);
        // System.out.println("Peek   :: " + ((String[]) field.get(null))[0]);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        field.set(null, new String[] { "Good bye, World!" });
        System.out.println("After  :: " + B.get());
    }
}

class B {
    private static final String[] arr = new String[] { "Hello, World!" };

    public static String get() {
        return arr[0];
    }
}

Which prints as expected:

Before :: Hello, World!
After  :: Good bye, World!

Problems arise when I try to get the field value via reflection prior to setting it. That is, if I uncomment the commented line in above sample, I get the following:

Before :: Hello, World!
Peek   :: Hello, World!
Exception in thread "main" java.lang.IllegalAccessException: Can not set static final [Ljava.lang.String; field B.arr to [Ljava.lang.String;
        at sun.reflect.UnsafeFieldAccessorImpl.throwFinalFieldIllegalAccessException(UnsafeFieldAccessorImpl.java:76)
        at sun.reflect.UnsafeFieldAccessorImpl.throwFinalFieldIllegalAccessException(UnsafeFieldAccessorImpl.java:80)
        at sun.reflect.UnsafeQualifiedStaticObjectFieldAccessorImpl.set(UnsafeQualifiedStaticObjectFieldAccessorImpl.java:77)
        at java.lang.reflect.Field.set(Field.java:764)
        at A.main(A.java:14)

Why is this happening?? I tried to set again the accessible flag after the call to get but it doesn't help. I tried many other things that don't seem to help either...

Thanks for your help!





How to get the WebElement Name Using Reflection

The ultimate goal is to get the WebElement variable name for reporting purposes.

To which, I tried:

 private String getVariableName(String callingClassName, WebElement element) {
    try {
        Class<?> cls = Class.forName(this.getClass().getCanonicalName());
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            if (field.getType() == WebElement.class) {
                field.setAccessible(true);
                WebElement fieldElement = WebElement.class.cast(field.get(cls));
                logger.debug("Field: \"" + field.getName() + "\""
                    + " Value: \"" + fieldElement.toString() + "\"\n"
                    + "Element: \"" + element.toString() + "\".");
                if (fieldElement.equals(element))
                    return field.getName();
            }
        }
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } 
    return element.toString();
}

Which generates the error stack trace:

java.lang.IllegalArgumentException: Can not set org.openqa.selenium.WebElement field pages.google.GoogleHomePage.searchBox to java.lang.Class
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(Unknown Source)
at sun.reflect.UnsafeObjectFieldAccessorImpl.get(Unknown Source)
at java.lang.reflect.Field.get(Unknown Source)
at pages.common.BasePageObject.getVariableName(BasePageObject.java:127)
at pages.common.BasePageObject.formatWord(BasePageObject.java:148)
at pages.common.BasePageObject.typeText(BasePageObject.java:327)
at pages.common.BasePageObject.typeText(BasePageObject.java:259)
at pages.google.GoogleHomePage.performGoogleSearch(GoogleHomePage.java:42)
at testcases.google.GoogleSearchTest.performSearch(GoogleSearchTest.java:17)
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 org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:661)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:869)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1193)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:126)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:744)
at org.testng.TestRunner.run(TestRunner.java:602)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:380)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
at org.testng.SuiteRunner.run(SuiteRunner.java:289)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1301)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1226)
at org.testng.TestNG.runSuites(TestNG.java:1144)
at org.testng.TestNG.run(TestNG.java:1115)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

The fields 'callingClassNameand 'element are parameters, the element is the given WebElement and the 'callingClassNameis just that and based off of 'element.

I have tried 'WebElement fieldElement = (WebElement)field.get(cls)andWebElement fieldElement = (WebElement)field`, both give similar errors.

Any help is appreciated.

Thank you





lundi 25 décembre 2017

write IQueryable in reflection

I'm newbie in C# refelection. Please help me to write the following code using relfection

var slItem = db.m_area
            .Where(s => s.tenant_id.Equals(sessionId))
            .Select(s => new SelectListItem
                                {
                                    Text = s.area_id,
                                    Value = s.area_name
                                }).ToList();

tenant_id, area_id, area_name, m_area, sessionId are parameters of reflection function.

Thanks in advance.





dimanche 24 décembre 2017

how I could add this jscrollpanel class to my swing builder?

Im trying to combine thiss class ScrollPaneDemo() with my swingbuilder but this appears by separate exist any way IN that I could combine two for appear as same interface I read about of reflection but i dont know how i could use

please help me with this I cant combine

enter image description here

@Bindable
class Address { 
    String street, number, city
    String toString() { "address[street=$street,number=$number,city=$city]" }
}
  class ScrollPaneDemo extends JFrame {

ScrollPaneDemo() {

    super("JScrollPane Demo");
    ImageIcon ii = new ImageIcon("pokemon.png");
    JScrollPane jsp = new JScrollPane(new JLabel(ii));
    getContentPane().add(jsp);
    setSize(300, 250);
    setVisible(true);

      jsp.addMouseListener(new MouseAdapter() {



            @Override
            public void mousePressed(MouseEvent e) {
                System.out.println("Mouse X="+e.getY()+" Mouse Y="+e.getY());

            }

        });


  }}


  public static void main(String[] args) {
    new ScrollPaneDemo();
  }



def address = new Address(street: 'Evergreen Terrace', number: '742', city: 'Springfield')

def swingBuilder = new SwingBuilder()
swingBuilder.edt {  // edt method makes sure UI is build on Event Dispatch Thread.


    lookAndFeel 'nimbus'  // Simple change in look and feel.

    frame(title: 'Address', size: [1000, 800],
            show: true, locationRelativeTo: null,

            defaultCloseOperation: EXIT_ON_CLOSE) {

        borderLayout(vgap: 5)

        panel(constraints: BorderLayout.CENTER,
                border: compoundBorder([emptyBorder(10), titledBorder('Enter your address:')])) {
            tableLayout {

                tr {
                    td {
                        label 'Street:'  // text property is default, so it is implicit.
                    }
                    td {
                        textField address.street, id: 'streetField', columns: 20
                    }
                }
                tr {
                    td {
                        label 'Number:'
                    }
                    td {
                        textField id: 'numberField', columns: 5, text: address.number
                    }
                }
                tr {
                    td {
                        label 'City:'
                    }
                    td {
                        textField id: 'cityField', columns: 20, address.city
                    }
    td {
                        textField id: 'cityField', columns: 20, address.city
                    }
                }
            }




    new ScrollPaneDemo();




      }





        panel(constraints: BorderLayout.SOUTH) {
            button text: 'Save', actionPerformed: {
                println address
            }
        }

        // Binding of textfield's to address object.
        bean address,
            street: bind { streetField.text },
            number: bind { numberField.text },
            city: bind { cityField.text }
    } 
}

PLease help me





Unable to access Controller Annotation data from Spring Controller

I am developing a Maven plugin which generates some application metadata related to Spring Controllers. Currently I am unable to get the "Controller" annotation (with its "value" property) of my spring controllers so I am kinda stuck... "analyzedClass" is the class instance from my Spring Controllers

How could I get this annotation and its value ?. Thankx





AutoMapper : Open - Close Princple

I got the code from the given link

AutoMapper Code for Open Close Princple Code

I am trying to use it in my project but I am stuck due to Static API has been removed from AutoMapper version 4.2.0.

For Reference see this

Please can any one help me how to implement the below code's in latest version of automapper.

1) Mapper.CreateMap(TSource,TDestination)

 private void RegisterStandardMappings(IEnumerable<Type> types)
    {
        var maps = (from t in types
                    from i in t.GetInterfaces()
                    where i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapForm<>)
                          && !t.IsAbstract
                          && !t.IsInterface
                    select new
                    {
                        Source = i.GetGenericArguments()[0],
                        Destination = t
                    }).ToArray();

        foreach (var map in maps)
        {
            //Need to optimize below line with current version.
            Mapper.CreateMap(map.Source, map.Destination);
        }
    }

2) Getting IConfiguration as it has been changed to IConfigurationProvider

 private void ReverseCustomMappings(IEnumerable<Type> types)
 {
        var maps = (from t in types
                    from i in t.GetInterfaces()
                    where typeof(IHaveCustomMappings).IsAssignableFrom(t)
                          && !t.IsAbstract
                          && !t.IsInterface
                    select (IHaveCustomMappings)Activator.CreateInstance(t)).ToArray();

        foreach (var map in maps)
        {
            //Need to optimize below line with current version.
            map.CreateMappings(Mapper.Configuration);
        }
  }

public interface IHaveCustomMappings
{
    void CreateMappings(IConfiguration configuration);
}

Please need your suggestion's any help with appreciated.





samedi 23 décembre 2017

How to log parameters from generic function

Given the following code:

int result = Execute(() => Foo(1, 2));

public int Foo(int x, int y)
{
    return x + y;
}

public T Execute<T>(
    Func<T> function)
{
    Console.Write(function.Method.Name + ": " + string.Join(", ", params));
    return function();
}

Is it possible to get the parameters? So the output would read something like:

"Foo: 1, 2"





Geting property type with reflection

I have a little problem by getting the type of an Property by reflection.

I have a class which include only simple types like string, int, decimal...

public class simple 
{
  public string article { get; set; }
  public decimal price { get; set; }
}

Now I need to take this properties by reflection and handle them by it's type.

I need something like this:

Type t = obj.GetType();
PropertyInfo propInfo = t.GetProperty("article");
Type propType = ??  *GetPropType*() ??

switch (Type.GetTypeCode(propType))
{
  case TypeCode.Decimal:
    doSome1;
    break;
  case TypeCode.String:
    doSome2;
    break;
}

For strings it works to do propInfo.PropertyType.UnderlyingSystemType as GetPropType() but not for decimal for example.

For decimal works propInfo.PropertyType.GenericTypeArguments.FirstOrDefault(); but not for strings.

Hos can get the type for all simple types?

Thank you much. Nu





What kind of reflection does JavaScript support?

A fully reflective system has introspection, interception and modification abilities. I am trying to understand whether one can say that JavaScript has full reflective capabilities. Looking at the Reflection object it looks to me as if it does, but I would like to use more sources to confirm. Unfortunately, I have a hard time finding more sources.





vendredi 22 décembre 2017

Instantiate class dynamically with locate

I am trying to instantiate a class dynamically from a string that is fed to a method.

name = "folder.subfolder.classname"
my_class = locate(name)
instance = my_class()

Doing this results in an error:

TypeError: 'module' object is not callable

My question is: how can I dinamically know which class I need to call? If I hardcode the value and do my_class.classname() I can instantiate it, but I want that last part to be dynamic, instead of hardcoded. How can I do that?





Cannot set a struct property using reflection due to boxing issues

In my code I have the interface

public interface MyInterface
{
    object Value { get; set; }
}

which is supposed to be a base interface for a few structs, e.g. a struct like this:

public struct DemoStruct : MyInterface
{
    public object Value { get; set; }
}

and I want to be able to set the Value property using Reflection. But due to issues with boxing and unboxing, I cannot set the property directly nor have define a setting method on the interface which can be called later (see examples below), so I have to resort to this working solution, but I would rather not want to program against the implementation (i.e. setting the field name explicitly, as shown below):

public struct MyStruct : MyInterface
{
    internal object ValueField; // Workaround.

    public object Value
    { 
        get { return this.ValueField; }
        set { this.ValueField = value; } 
    } 
}

The setting method:

public void SetValue<TStruct>(TStruct instance) where TStruct : struct, IMyInterface
{
    (instance as IMyInterface).GetType().GetField("ValueField", BindingFlags.Instance | BindingFlags.NonPublic).SetValueDirect(__makeref(instance), this.GetSomeValue());
    //                                            ^^^^^^^^^^^^
}    

Below are two alternatives I came up with, which sadly don't work due to boxing / unboxing issues I guess:

(instance as IMyInterface).GetType().GetProperty(nameof(IMyInterface.Value), BindingFlags.Instance | BindingFlags.NonPublic).SetValue(instance, this.GetSomeValue());
//                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^
// I would prefer this, because it does not depend on the implementation, but does not work due to the boxing.

(instance as IMyInterface).SetValue(this.GetSomeValue());
// Implied that IMyInterface provides a method definition of SetValue, this would be the shortest and cleanest solution, but it does not work either.


I glady appreciate any help.





jeudi 21 décembre 2017

Java - get a class attribute name when get Method is called

Can anyone please clarify me, if it is possible to get a class attribute name when I call get/set method of the class in java.
I saw something on online that it is possible to get class attribute name using Reflection concept.

My situation:
Trying to write a method that checks the value of the attribute for null/empty and return the attribute name in case the attribute value is null/empty.

example:

Class:

public class MyClass {
  private appName;

  public void setAppName(String appName) {
  this.appName = appName;
  }

  public String getAppName() {
  return this.appName;
  }
}

Validation Method:

public String validateForNull(MyClass myclass) {
   String name = myclass.getAppName();
   if(name == null || name.isEmpty()) {
   return //here I want to return attributeName which will be "appName"
   }
}

I realized returning the constant string that represent attribute name will be lot easier and neat way for the approach. But I was wondering if I can do it as a generic way where validate method takes the class object and check all/specified attributes for null/empty and return attribute name in case null/empty value.

Thanks





Remove duplicate objects from hashset

I am trying to remove duplicate objects from my hashset using c#, I have this code and structure as of now :

var more_data = new Order 
{ 
      amount = amount, 
      links = new List<Links> {  links  }, 
      payment_mode = "Paypal", 
      reason_code = "Broken and rubbish product" 
};

Details amountDetails = new Details();
amountDetails.subtotal = "0.00";
amountDetails.tax = "0.00";
amountDetails.shipping = "0.00";
amountDetails.fee = "";
amountDetails.handling_fee = "";
amountDetails.shipping_discount = "20%";
amountDetails.insurance = "34";
amountDetails.gift_wrap = "";

Amount amount = new Amount();
amount.total = "0.00";
amount.currency = "GBP";
amount.details = amountDetails;

var hash_set = new HashSet<object>();
hash_set.Add(more_data);
hash_set.Add(amount);

The two entries are added in, now I want to be able to eliminate the duplicate objects if it already exists can I do this using a Hashset in c# after using reflection?





Why does GetName in System.Reflection.Assembly appear to throw a NotImplementedException when decompiled?

While debugging an issue I was digging in to mscorlib and specifically at GetName() in System.Reflection.Assembly.

Looking at the code for the method in dotPeek and also on reference source the code for GetName() seems to have nothing in it and throws a not implemented exception (see image).

enter image description here

Can anyone explain why this appears to throw an exception, but using a line of code such as typeof(object).GetTypeInfo().Assembly.GetName().Version.ToString() returns the correct version of the DLL?





Reflecting COM interop interfaces

I have a need to compare "Microsoft.Office.Interop.Publisher.Font" instances, so that I can tell if specific text range has the same text formatting as another range.

The Font interface has about 38 properties and a bunch of methods. This is what object browser shows and what I call successfully access in the code.

The first obvious one is to write a method which would compare property by property. Thankfully most of the properties are kind-of-bool values. Yet there are some advanced, like Color, which itself is ColorFormat interface with 9 properties, etc. All in all this sounds boring.

I thought, OK, why would not I serialize that into a string and compare results instead. I tried standard xml serialization and json.net, both return empty result. No errors, just empty. Ouch, COM interop interfaces cannot be serialized (well, they can with some workaround, but read on, it would not help anyway). What a pity, I do not need to deserialize the result anyway.

Then I thought, alright I can use reflection on Font interface and get all properties myself (isn't this is what serializers do anyway), and recursively build unique string comprised of values for comparison. So I went for "typeof(Font).GetMembers()". But... wait, only 22 members. How come?

Why object browser shows more members than reflection? Why reflection on COM interop interface (just this one) show only partial information? And how I can reflect missing members?

As a more generic questions, would anyone point me to an article which describes in detail what happens behind the scene when object browses queries COM interfaces for type information please?





mercredi 20 décembre 2017

Reflection get nested class

In debugger I've the following object o = {$Proxy0@1045} "Proxy[RMIServer,RemoteObjectInvocationHandler[UnicastRef2[liveRef:[endpoint:127.0.0.1:3233,objID:[645345345:43434324ab:-6eee.-54232323232]]]]"

How can I get an object with this host = 127.0.0.1 and port ? How to cast this object if Proxy class here is dynamic, and I can't use it just like that (Proxy) obj. Thanks in advance!





Reflection Java Getter returning null

I have this very weird problem.

I have a UI that has a few textboxes.

Every one is linked to a documentListener that sets the value with a setter.

In the document Listener, I have used the println method to check if the data is being saved properly. It is, also, I call the getter from there, and it returns the proper value.

In another class (the UI and this class are being loaded with reflection, also, they are in the exact same location if that matters), I call the getter like this UI.getStuff(). This time, it returns null.

Here is a setter:

public static String setItem1(Object item2)
{
    JTextField a = (JTextField) item2;
    String item = a.getText();
    System.out.println(item);
    return item1 = item;
}

And here is a getter:

public static String getItem1()
{
    return item1; //Item 1 is a variable declared outside (so it's not declared inside a method)
}





Why C# reflection throw this excetion

Here is my application code. Just simple one. I'm new in C#. I tried other examples which work perfectly. But the exception "An attempt was made to load a program with an incorrect format." I have no clue why. Please let me know. Is there a way that the Core.dll won't allow loading dynamically and call by refection.

           Assembly asm = null;
            try
            {
                // Excepition in this line
                 asm = Assembly.LoadFrom(@"C:\myproj\Core.dll");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.GetBaseException());
                Console.WriteLine(e.Message);

            }

        MethodInfo staticMethodInfo = t.GetMethod("Create");
        if (staticMethodInfo == null)
        {

        }
        List<Assembly> assemblies = new List<Assembly>();
        staticMethodInfo.Invoke(null, new object[] { typeof(string), typeof(JObject), assemblies });

I get the following exception:-

System.BadImageFormatException: Could not load file or assembly 'http://file/C:\myproj\Core.dll' or one of its dependencies. An attempt was made to load a program with an incorrect format.
File name: 'http://file/C:\myproj\Core.dll'
   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark)
   at System.Reflection.Assembly.LoadFrom(String assemblyFile)
   at MyApp.Program.Main(String[] args) in C:\practice\csharp\MyApp\MyApp\Program.cs:line 61

=== Pre-bind state information ===
LOG: Where-ref bind. Location = C:\myproj\Core.dll
LOG: Appbase = file:///C:/practice/csharp/MyApp/MyApp/bin/Debug/
LOG: Initial PrivatePath = NULL
Calling assembly : (Unknown).
===
LOG: This bind starts in LoadFrom load context.
WRN: Native image will not be probed in LoadFrom context. Native image will only be probed in default load context, like with Assembly.Load().
LOG: Using application configuration file: C:\practice\csharp\MyApp\MyApp\bin\Debug\MyApp.vshost.exe.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Attempting download of new URL file:///C:/myproj/Core.dll.
ERR: Failed to complete setup of assembly (hr = 0x8007000b). Probing terminated.

Could not load file or assembly 'http://file/C:\myproj\Core.dll' or one of its dependencies. An attempt was made to load a program with an incorrect format.





WPF - How to create a group of Controls based on properties of a model class

I'm writing a desktop application which contains some user permission management, and therefore I'm building a segment to manage all the user permissions.

Before I start hardcoding all the different types of permissions into the UI, I was wondering if it is possible, to let WPF do this dynamically for me.

To be more specific, I have a model with the user and his permissions (each User has a Role) which looks like this:

public class Role
{
    public enum Permission
    {
        None,
        Read,
        Write
    };

    public int id;
    public string name;
    public bool isAdmin;
    public Permission Usermanagement;
    public Permission Appointments;
    public Permission Events;

and for each Permission in this class I want WPF to create a Template with the name and a comboBox to select the kind of permission. My first guess was to use a ListView/ListBox with a Template (that part is not the problem).

My question is how can I get the list of permissions as a source list for my Template, and afterwards how to bind the real object to it, so the right permission gets updated.

This is more a question about possibility, I could just hardcode my permissions and bind them one-by-one.





Compile a method at runtime and get its parameters in C#

I've got a string such as:

string s = "public bool function([System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] ref string param1, [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] string param2, [System.Xml.Serialization.XmlElementAttribute(\"param3\", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] paramType[] param3) {";

Im only interested in the parameters names, datatypes and if they are passed as "ref" or "out". Is there a way to compile the string as a method and get the methods parameters?





Custom server-side DataTables processing: "typeof(Enumerable).GetMethod" is null


I have been struggling for days over an old (2011) piece of C# code I extracted from a DLL my boss wants me to edit.

The application queries a database with LINQ, server-side processes it and displays the data with a DataTable. From what I gathered, the guy who wrote it had created an ASP.NET Web Forms Site in Visual Studio 2010, with .NET Framework 4.0.

He used the DataTables plugin along with the server-side parser from Zack Owens. In the project I recreated in VS 2017, everything builds well, but at runtime, a bug comes from the little customizations he made to the DataTable parser: among them, the SelectProperties() function has been completely rewritten from this:

private Expression<Func<T, List<string>>> SelectProperties
{
    get
    {
        return value => _properties.Select
        (
            // empty string is the default property value
            prop => (prop.GetValue(value, new object[0]) ?? string.Empty).ToString()
        )
        .ToList();
    }
}

to this:

private Expression<Func<T, List<string>>> SelectProperties
{
    get
    {
        var parameterExpression = Expression.Parameter(typeof(T), "value");

       // (Edited) The bug happens there: type_RD is null because GetMethod is not valid
        var type_RD = typeof(Enumerable).GetMethod(
            "ToList",
            new Type[] {
                typeof(IEnumerable<string>)
            }
        );

        // The programs crashes there (System.Null.Exception)
        var methodFromHandle = (MethodInfo)MethodBase.GetMethodFromHandle(
            type_RD
        .MethodHandle);

        var expressionArray = new Expression[1];

        var methodInfo = (MethodInfo)MethodBase.GetMethodFromHandle(
            typeof(Enumerable).GetMethod("Select", new Type[] {
                typeof(IEnumerable<PropertyInfo>),
                typeof(Func<PropertyInfo, string>)
            })
        .MethodHandle);

        var expressionArray1 = new Expression[] {
            Expression.Field(
                Expression.Constant(
                    this,
                    typeof(DataTableParser<T>)
                ),
                FieldInfo.GetFieldFromHandle(
                    typeof(DataTableParser<T>).GetField("_properties").FieldHandle,
                    typeof(DataTableParser<T>).TypeHandle
                )
            ), null
        };

        var parameterExpression1 = Expression.Parameter(
            typeof(PropertyInfo),
            "prop"
        );

        var methodFromHandle1 = (MethodInfo)MethodBase.GetMethodFromHandle(
            typeof(PropertyInfo).GetMethod(
                "GetValue",
                new Type[] {
                    typeof(object),
                    typeof(object[])
                }
            )
        .MethodHandle);

        var expressionArray2 = new Expression[] {
            Expression.Convert(
                parameterExpression,
                typeof(object)
            ),
            Expression.NewArrayInit(
                typeof(object),
                new Expression[0]
            )
        };

        var methodCallExpression = Expression.Call(
            Expression.Coalesce(
                Expression.Call(
                    parameterExpression1,
                    methodFromHandle1,
                    expressionArray2
                ),
                Expression.Field(
                    null,
                    FieldInfo.GetFieldFromHandle(
                        typeof(string).GetField("Empty").FieldHandle
                    )
                )
            ),
            (MethodInfo)MethodBase.GetMethodFromHandle(
                typeof(object).GetMethod("ToString").MethodHandle
            ),
            new Expression[0]
        );

        expressionArray1[1] = Expression.Lambda<Func<PropertyInfo, string>>(
            methodCallExpression,
            parameterExpression1
        );
        expressionArray[0] = Expression.Call(
            null,
            methodInfo,
            expressionArray1
        );

        // Return Lambda
        return Expression.Lambda<Func<T, List<string>>>(
            Expression.Call(
                null,
                methodFromHandle,
                expressionArray
            ),
            parameterExpression
        );
    }
}

My questions:

  • How to make this SelectProperties function work?
  • What exactly is its purpose, compared to the original one? I didn't get any of the "MethodHandle" bits ...

The only hint I have is that, when I use the original SelectProperties code, the data are in the wrong columns and the sorting causes errors 500 with some of the columns. Here is the full code of this custom DataTable.cs parser:
Tip: look for the (Edited) tags

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;

// (Edited) Source : Zack Owens commented http://ift.tt/2ks1VOY

/* (Edited) Adapting to custom namespace
namespace DataTables
*/
namespace MyApp.Web.WebServices.Utils
{
    /// <summary>
    /// Parses the request values from a query from the DataTables jQuery plugin
    /// </summary>
    /// <typeparam name="T">List data type</typeparam>
    public class DataTableParser<T>
    {
        /*
         * int: iDisplayStart - Display start point
        * int: iDisplayLength - Number of records to display
        * string: string: sSearch - Global search field
        * boolean: bEscapeRegex - Global search is regex or not
        * int: iColumns - Number of columns being displayed (useful for getting individual column search info)
        * string: sSortable_(int) - Indicator for if a column is flagged as sortable or not on the client-side
        * string: sSearchable_(int) - Indicator for if a column is flagged as searchable or not on the client-side
        * string: sSearch_(int) - Individual column filter
        * boolean: bEscapeRegex_(int) - Individual column filter is regex or not
        * int: iSortingCols - Number of columns to sort on
        * int: iSortCol_(int) - Column being sorted on (you will need to decode this number for your database)
        * string: sSortDir_(int) - Direction to be sorted - "desc" or "asc". Note that the prefix for this variable is wrong in 1.5.x, but left for backward compatibility)
        * string: sEcho - Information for DataTables to use for rendering
         */

        private const string INDIVIDUAL_SEARCH_KEY_PREFIX = "sSearch_";
        private const string INDIVIDUAL_SORT_KEY_PREFIX = "iSortCol_";
        private const string INDIVIDUAL_SORT_DIRECTION_KEY_PREFIX = "sSortDir_";
        private const string DISPLAY_START = "iDisplayStart";
        private const string DISPLAY_LENGTH = "iDisplayLength";
        private const string ECHO = "sEcho";
        private const string ASCENDING_SORT = "asc";
        private const string OBJECT_DATA_PREFIX = "mDataProp_";

        private IQueryable<T> _queriable;
        private readonly HttpRequestBase _httpRequest;
        private readonly Type _type;
        private readonly PropertyInfo[] _properties;

        public DataTableParser(HttpRequestBase httpRequest, IQueryable<T> queriable)
        {
            _queriable = queriable;
            _httpRequest = httpRequest;
            _type = typeof(T);
            _properties = _type.GetProperties();
        }

        public DataTableParser(HttpRequest httpRequest, IQueryable<T> queriable)
            : this(new HttpRequestWrapper(httpRequest), queriable) { }

        /// <summary>
        /// Parses the <see cref="HttpRequestBase"/> parameter values for the accepted 
        /// DataTable request values
        /// </summary>
        /// <returns>Formated output for DataTables, which should be serialized to JSON</returns>
        /// <example>
        ///     In an ASP.NET MVC from a controller, you can call the Json method and return this result.
        ///     
        ///     public ActionResult List()
        ///     {
        ///         // change the following line per your data configuration
        ///         IQueriable<User> users = datastore.Linq();
        ///         
        ///         if (Request["sEcho"] != null) // always test to see if the request is from DataTables
        ///         {
        ///             var parser = new DataTableParser<User>(Request, users);
        ///             return Json(parser.Parse());
        ///         }
        ///         return Json(_itemController.CachedValue);
        ///     }
        ///     
        ///     If you're not using MVC, you can create a web service and write the JSON output as such:
        ///     
        ///     using System.Web.Script.Serialization;
        ///     public class MyWebservice : System.Web.Services.WebService
        ///     {
        ///         public string MyMethod()
        ///         {
        ///             // change the following line per your data configuration
        ///             IQueriable<User> users = datastore.Linq();
        ///             
        ///             response.ContentType = "application/json";
        ///             
        ///             JavaScriptSerializer serializer = new JavaScriptSerializer();
        ///             var parser = new DataTableParser<User>(Request, users);
        ///             return new JavaScriptSerializer().Serialize(parser.Parse());
        ///         }
        ///     }
        /// </example>
        public FormatedList<T> Parse()
        {
            var list = new FormatedList();
            list.Import(_properties.Select(x => x.Name).ToArray());

            list.sEcho = int.Parse(_httpRequest[ECHO]);

            list.iTotalRecords = _queriable.Count();

            ApplySort();

            int skip = 0, take = 10;
            int.TryParse(_httpRequest[DISPLAY_START], out skip);
            int.TryParse(_httpRequest[DISPLAY_LENGTH], out take);

            /* (Edited) This new syntax works well
            list.aaData = _queriable.Where(ApplyGenericSearch)
                                    .Where(IndividualPropertySearch)
                                    .Skip(skip)
                                    .Take(take)
                                    .Select(SelectProperties)
                                    .ToList();

            list.iTotalDisplayRecords = list.aaData.Count;
            */
            list.aaData = _queriable.Where(ApplyGenericSearch)
                                    .Where(IndividualPropertySearch)
                                    .Skip(skip)
                                    .Take(take)
                                    .ToList()
                                    .AsQueryable()
                                    .Select(SelectProperties)
                                    .ToList();

            list.iTotalDisplayRecords = list.iTotalRecords;

            return list;
        }

        private void ApplySort()
        {
            // (Edited) Added one line, see after
            bool firstSort = true;
            foreach (string key in _httpRequest.Params.AllKeys.Where(x => x.StartsWith(INDIVIDUAL_SORT_KEY_PREFIX)))
            {
                int sortcolumn = int.Parse(_httpRequest[key]);
                if (sortcolumn < 0 || sortcolumn >= _properties.Length)
                    break;

                string sortdir = _httpRequest[INDIVIDUAL_SORT_DIRECTION_KEY_PREFIX + key.Replace(INDIVIDUAL_SORT_KEY_PREFIX, string.Empty)];

                var paramExpr = Expression.Parameter(typeof(T), "val");

                /* Edited as per http://ift.tt/2kPUpNd and mentioned here too http://ift.tt/2krIKVz
                var propertyExpr = Expression.Lambda<Func<T, object>>(Expression.Property(paramExpr, _properties[sortcolumn]), paramExpr);
                */
                var expression = Expression.Convert(Expression.Property(paramExpr, _properties[sortcolumn]),typeof(object));
                var propertyExpr = Expression.Lambda<Func<T, object>>(expression, paramExpr);

                /* Edited cf. http://ift.tt/2krIKVz
                 * Correcting multi-sort errors
                if (string.IsNullOrEmpty(sortdir) || sortdir.Equals(ASCENDING_SORT, StringComparison.OrdinalIgnoreCase))
                    _queriable = _queriable.OrderBy(propertyExpr);
                else
                    _queriable = _queriable.OrderByDescending(propertyExpr);
                 */
                if (firstSort)
                {
                    if (string.IsNullOrEmpty(sortdir) || sortdir.Equals(ASCENDING_SORT, StringComparison.OrdinalIgnoreCase))
                        _queriable = _queriable.OrderBy(propertyExpr);
                    else
                        _queriable = _queriable.OrderByDescending(propertyExpr);

                    firstSort = false;
                }
                else
                {
                    if (string.IsNullOrEmpty(sortdir) || sortdir.Equals(ASCENDING_SORT, StringComparison.OrdinalIgnoreCase))
                        _queriable = ((IOrderedQueryable<T>)_queriable).ThenBy(propertyExpr);
                    else
                        _queriable = ((IOrderedQueryable<T>)_queriable).ThenByDescending(propertyExpr);
                }
            }
        }

        /// <summary>
        /// Expression that returns a list of string values, which correspond to the values
        /// of each property in the list type
        /// </summary>
        /// <remarks>This implementation does not allow indexers</remarks>
        private Expression<Func<T, List<string>>> SelectProperties
        {
            get
            {
                /* (Edited) This is the edit that does not work and that I don't understand
                return value => _properties.Select
                (
                    // empty string is the default property value
                    prop => (prop.GetValue(value, new object[0]) ?? string.Empty).ToString()
                )
               .ToList();
               */
                var parameterExpression = Expression.Parameter(typeof(T), "value");

               // (Edited) The bug happens there: type_RD is null because GetMethod is not valid
                var type_RD = typeof(Enumerable).GetMethod(
                    "ToList",
                    new Type[] {
                        typeof(IEnumerable<string>)
                    }
                );

                // The programs crashes there (System.Null.Exception)
                var methodFromHandle = (MethodInfo)MethodBase.GetMethodFromHandle(
                    type_RD
                .MethodHandle);

                var expressionArray = new Expression[1];

                var methodInfo = (MethodInfo)MethodBase.GetMethodFromHandle(
                    typeof(Enumerable).GetMethod("Select", new Type[] {
                        typeof(IEnumerable<PropertyInfo>),
                        typeof(Func<PropertyInfo, string>)
                    })
                .MethodHandle);

                var expressionArray1 = new Expression[] {
                    Expression.Field(
                        Expression.Constant(
                            this,
                            typeof(DataTableParser<T>)
                        ),
                        FieldInfo.GetFieldFromHandle(
                            typeof(DataTableParser<T>).GetField("_properties").FieldHandle,
                            typeof(DataTableParser<T>).TypeHandle
                        )
                    ), null
                };

                var parameterExpression1 = Expression.Parameter(
                    typeof(PropertyInfo),
                    "prop"
                );

                var methodFromHandle1 = (MethodInfo)MethodBase.GetMethodFromHandle(
                    typeof(PropertyInfo).GetMethod(
                        "GetValue",
                        new Type[] {
                            typeof(object),
                            typeof(object[])
                        }
                    )
                .MethodHandle);

                var expressionArray2 = new Expression[] {
                    Expression.Convert(
                        parameterExpression,
                        typeof(object)
                    ),
                    Expression.NewArrayInit(
                        typeof(object),
                        new Expression[0]
                    )
                };

                var methodCallExpression = Expression.Call(
                    Expression.Coalesce(
                        Expression.Call(
                            parameterExpression1,
                            methodFromHandle1,
                            expressionArray2
                        ),
                        Expression.Field(
                            null,
                            FieldInfo.GetFieldFromHandle(
                                typeof(string).GetField("Empty").FieldHandle
                            )
                        )
                    ),
                    (MethodInfo)MethodBase.GetMethodFromHandle(
                        typeof(object).GetMethod("ToString").MethodHandle
                    ),
                    new Expression[0]
                );

                expressionArray1[1] = Expression.Lambda<Func<PropertyInfo, string>>(
                    methodCallExpression,
                    parameterExpression1
                );
                expressionArray[0] = Expression.Call(
                    null,
                    methodInfo,
                    expressionArray1
                );

                // Return Lambda
                return Expression.Lambda<Func<T, List<string>>>(
                    Expression.Call(
                        null,
                        methodFromHandle,
                        expressionArray
                    ),
                    parameterExpression
                );
            }
        }

        /// <summary>
        /// Compound predicate expression with the individual search predicates that will filter the results
        /// per an individual column
        /// </summary>
        private Expression<Func<T, bool>> IndividualPropertySearch
        {
            get
            {
                var paramExpr = Expression.Parameter(typeof(T), "val");
                Expression whereExpr = Expression.Constant(true); // default is val => True
                List<Expression> le = new List<Expression>() { whereExpr };
                List<ParameterExpression> lp = new List<ParameterExpression>() { paramExpr };

                foreach (string key in _httpRequest.Params.AllKeys.Where(x => x.StartsWith(INDIVIDUAL_SEARCH_KEY_PREFIX)))
                {
                    var mDataProp = key.Replace(INDIVIDUAL_SEARCH_KEY_PREFIX, OBJECT_DATA_PREFIX);
                    if (string.IsNullOrEmpty(_httpRequest[key]) || string.IsNullOrEmpty(_httpRequest[mDataProp]))
                    {
                        continue; // ignore if the option is invalid
                    }
                    var f = _properties.First(p => p.Name == _httpRequest[mDataProp]);
                    string query = _httpRequest[key].ToLower();

                    MethodCallExpression mce;
                    if (f.PropertyType != typeof(string))
                    {
                        // val.{PropertyName}.ToString().ToLower().Contains({query})
                        mce = Expression.Call(Expression.Call(Expression.Property(paramExpr, f), "ToString", new Type[0]), typeof(string).GetMethod("ToLower", new Type[0]));
                    }
                    else
                    {
                        mce = Expression.Call(Expression.Property(paramExpr, f), typeof(string).GetMethod("ToLower", new Type[0]));
                    }

                    // reset where expression to also require the current constraint
                    whereExpr = Expression.And(whereExpr, Expression.Call(mce, typeof(string).GetMethod("Contains"), Expression.Constant(query)));
                    le.Add(whereExpr);
                }

                var agg = le.Aggregate((prev, next) => Expression.And(prev, next));
                return Expression.Lambda<Func<T, bool>>(agg, paramExpr);
            }
        }

        /// <summary>
        /// Expression for an all column search, which will filter the result based on this criterion
        /// </summary>
        private Expression<Func<T, bool>> ApplyGenericSearch
        {
            get
            {
                string search = _httpRequest["sSearch"];

                // default value
                if (string.IsNullOrEmpty(search) || _properties.Length == 0)
                    return x => true;

                // invariant expressions
                var searchExpression = Expression.Constant(search.ToLower());
                var paramExpression = Expression.Parameter(typeof(T), "val");

                // query all properties and returns a Contains call expression 
                // from the ToString().ToLower()
                var propertyQuery = (from property in _properties
                                     let tostringcall = Expression.Call(
                                                         Expression.Call(
                                                             Expression.Property(paramExpression, property), "ToString", new Type[0]),
                                                             typeof(string).GetMethod("ToLower", new Type[0]))
                                     select Expression.Call(tostringcall, typeof(string).GetMethod("Contains"), searchExpression)).ToArray();

                // we now need to compound the expression by starting with the first
                // expression and build through the iterator
                Expression compoundExpression = propertyQuery[0];

                // add the other expressions
                for (int i = 1; i < propertyQuery.Length; i++)
                    compoundExpression = Expression.Or(compoundExpression, propertyQuery[i]);

                // compile the expression into a lambda 
                return Expression.Lambda<Func<T, bool>>(compoundExpression, paramExpression);
            }
        }
    }

    public class FormatedList<T>
    {
        public FormatedList()
        {
        }

        public int sEcho { get; set; }
        public int iTotalRecords { get; set; }
        public int iTotalDisplayRecords { get; set; }
        public List<T> aaData { get; set; }
        public string sColumns { get; set; }

        public void Import(string[] properties)
        {
            sColumns = string.Empty;
            for (int i = 0; i < properties.Length; i++)
            {
                sColumns += properties[i];
                if (i < properties.Length - 1)
                    sColumns += ",";
            }
        }
    }
}

I am a beginner at C#, .NET, Linq etc., though I know quite a few other languages.
Setup: Windows 7 64, Visual Studio 2017.

Thank you for your help!





java 8 reflection doesn't work

We use the hibernate validator and dynamically class-loading in our project (by load class into a separate class-loader). After we realise that the class is not required we remove all references to the class and class-loader, then GC collects this.

What we get: Some time after the application starts the java reflection stops working.

java.lang.reflect.UndeclaredThrowableException: null
    at com.sun.proxy.$Proxy253.equals(Unknown Source)
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorManager$CacheKey.equals(ConstraintValidatorManager.java:287)
    at java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:940)
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorManager.getInitializedValidator(ConstraintValidatorManager.java:104)
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getConstraintValidatorNoUnwrapping(ConstraintTree.java:301)
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getConstraintValidatorInstanceForAutomaticUnwrapping(ConstraintTree.java:242)
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getInitializedConstraintValidator(ConstraintTree.java:163)
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:116)
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateComposingConstraints(ConstraintTree.java:396)
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:98)
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:87)
    at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:73)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:616)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:581)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForSingleDefaultGroupElement(ValidatorImpl.java:527)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:495)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:460)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:410)
    at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:207)
    at org.springframework.validation.beanvalidation.SpringValidatorAdapter.validate(SpringValidatorAdapter.java:281)
    ... Many spring filters calls ...
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.multipart.support.MultipartFilter.doFilterInternal(MultipartFilter.java:122)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at *someAwesomePackage*.microservice.rest.spring.webapp.CabinetRequestFilter.doFilterInternal(CabinetRequestFilter.java:98)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException: null
    at sun.reflect.GeneratedMethodAccessor268.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.hibernate.validator.internal.util.annotationfactory.AnnotationProxy.invoke(AnnotationProxy.java:69)
    ... 260 common frames omitted
Caused by: java.lang.NullPointerException: null
    at org.hibernate.validator.internal.util.annotationfactory.AnnotationProxy.getAnnotationMemberValue(AnnotationProxy.java:248)
    at org.hibernate.validator.internal.util.annotationfactory.AnnotationProxy.equals(AnnotationProxy.java:104)
    ... 264 common frames omitted

Error happens in this place (method from Class.java):

        private static Method searchMethods(Method[] methods,
                                    String name,
                                    Class<?>[] parameterTypes)
{
    Method res = null;
    String internedName = name.intern();
    for (int i = 0; i < methods.length; i++) {
        Method m = methods[i];
        if (m.getName() == internedName
            && arrayContentsEq(parameterTypes, m.getParameterTypes())
            && (res == null
                || res.getReturnType().isAssignableFrom(m.getReturnType())))
            res = m;
    }

    return (res == null ? res : getReflectionFactory().copyMethod(res));
}

Class has method, but the comparison of m.getName () == internedName is false. Comparison returns false because names of the methods are not interned.

This always happens after some time from the application start.

Did anybody encounter such a problem?

Thank you in advance.





Use reflection to invoke dynamically Add method of System.Data.Entity.DbSet

I used edmx(Entity Data Model) to access Oracle DB in my .net project.

I can send data manuelly to db in this way.

Table1 tb1=new Table1();

using (Entities dbo = new Entities())

{

dbo.Table1.add(tb1);

dbo.SaveChanges();

}

But I try to send data dynamically to db in this way. For this reason I must invoke add method with reflection.

Type type = Type.GetType("Table1");

object reflectedTableInstance = Activator.CreateInstance(type);

using (Entities dbo = new Entities())

{

THİS İS MY ISSUE! reflectedType comes null in this way

Type reflectedType=Type.GetType("DbSet>TEntity>")

MethodInfo method= reflectedType.GetMethod("Add");

method.Invoke(reflectedInstance, new object{reflectedTableInstance })

dbo.SaveChanges();

}





mardi 19 décembre 2017

Groovy does not like Reflections Constructor taking null args

I have created a groovy-reflection-troubleshooting repo to reproduce this entirely and easily.


Basically this Groovy code runs fine:

Class<?> clazz = Class.forName('troubleshooting.DangWidget')
Constructor<?> constructor = clazz.getConstructor(Configuration)
Object testClassInstance = constructor.newInstance(new Configuration())
// Object testClassInstance = constructor.newInstance(null)

But this throws an IllegalArgumentException:

Class<?> clazz = Class.forName('troubleshooting.DangWidget')
Constructor<?> constructor = clazz.getConstructor(Configuration)
// Object testClassInstance = constructor.newInstance(new Configuration())
Object testClassInstance = constructor.newInstance(null)

Stack trace:

Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        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:498)

I guess I'm wondering why I can't pass null into constructor.newInstance(null) and what I can pass constructor.newInstance if I truly wish to pass the new instance the value null?!





How to copy from List to list using reflection? C#

Both object are "the same" but its imposible for me, to copy de object definition directly.

The class A looks like:

public class A { 
    [JsonProperty(PropertyName="MyPROP")]
    List<Namespace.Property> pro {get; set;}
}

The class B looks like:

public class B { 
    [JsonProperty(PropertyName="MyNewPropertyName")]
    List<MyNames.Property> pro {get; set;}
}

As you can see, the only differences are attributes and namespace, both classes has the same methods and properties.

The error I'm getting using reflection is this

El objeto de tipo 'System.Collections.Generic.List1[Namespace.Property]' no puede convertirse en el tipo 'System.Collections.Generic.List1[MyNames.Property]'.





Given an object that I happen to know is a System.RuntimeType how do I get a typed object out?

I've done some hideous DI reflection :(

I've gotten a FieldInfo object and called GetValue() on it.

I get an object back.

Examining this object in VisualStudio, I discover that it is a "prototype", and that GetType() returns System.RuntimeType.

In the immediate window, I can cast my object as System.RuntimeType, and then I discover an AsType() method, which returns me my real, typed object.

Unfortunately, when try to write this in my code, I'm told that System.RuntimeType is an internal type, and thus I can't use it :(.

How can I get a typed object out of this object?


Full code:
KernelBase baseKernel = (KernelBase)ninjectKernel;
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
FieldInfo field = typeof(KernelBase).GetField("bindings", flags);

Multimap<Type, IBinding> allBindingsPerTypeMap = (Multimap<Type, IBinding>)field.GetValue(baseKernel);

var aBinding = allInterfaceTypesWithAllBindings.First(pair => pair.InterfaceType.Name.Contains("FilePath")).Binding;
var aBindingTarget = aBinding .BindingConfiguration.ProviderCallback.Target;

var prototype = aBindingTarget.GetType().GetField("prototype").GetValue(aBindingTarget);

// prototype is an object, which I'd like to turn into a real type.
var runtimeType = prototype.GetType(); // this returns System.RuntimeType


Note that I genuinely don't actually know what the type of the object is - the thing I'm reflecting on, is itself a piece of reflection ... I'm trying to extract binding info from my DI framework.

Solutions to the root problem are useful, but I do actually want to know how to interact with this System.RuntimeType object.





Unable to cast object of type System.RuntimeType to System.Enum

I've been tasked to generate a dynamic enumeration that has database driven values to alleviate recompiling and deployment of the Enum object when new values are added. The enumeration will exist as part of a internally consumed service.

The natural and most obvious advantage of this approach I suppose would be that anyone having need to consume the service would know immediately what values are available during development.

I'm not a big fan of this approach but I am up for the challenge.

The following code produces a RuntimeType but it throws an error on every attempt I've made in effort to cast this as an Enum.

    public Enum GenerateDynamicSmsEnumValues<T>(Dictionary<int,string> enumValues)
    {
        try
        {
            //    Create Base Assembly Objects
            AppDomain appDomain = AppDomain.CurrentDomain;
            AssemblyName asmName = new AssemblyName("SmsApplicationID");
            AssemblyBuilder asmBuilder = appDomain.
              DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);

            //    Create Module and Enumeration Builder Objects
            ModuleBuilder modBuilder = asmBuilder.
              DefineDynamicModule("SmsApplicationID");
            EnumBuilder enumBuilder = modBuilder.
              DefineEnum("SmsApplicationID", TypeAttributes.Public, typeof(int));

            //  Build enumerations
            foreach (var pair in enumValues)
                enumBuilder.DefineLiteral(pair.Value, pair.Key);

            var returnType = enumBuilder.CreateType();
            var enm = (object)returnType;

            return (Enum)enm; // <-- Error Thrown Here
        }
        catch(Exception ex)
        {
            return null;
        }

If I inspect the object before the attempted cast the IsEnum attribute is set to true so I believe I have the object I need.

I just cannot figure out how to properly cast it to an Enum type to be used by any code leveraging the method.

I have also tried this approach using a Generic Template method but the problem is pretty much the same.

How can I cast this to an Enum object???





Can I use Reflection with ProGuard obfuscated classes?

I have a certain class method which I want to invoke using Reflection.
Here is an example of my code in my Activity onCreate:

try {
    aMethod = getClass().getDeclaredMethod("myMethodName", SomeParameter.class);
} catch (NoSuchMethodException e) {
    e.printStackTrace();
}

When I run it directly from Android Studio, it works, but when I create a release version, the method name is not automatically changed by ProGuard. What can I do?





How can you get the string-representation of a variable's name in Swift

Ok, there's an existing question here on S/O with the following title:

Swift: Get Variable Actual Name as String

By it's name, it seems that's exactly what I want. However, looking at the accepted answer (and the other non-accepted ones), they are referring to key path manipulation, which isn't what I'm after. (i.e. This is not a duplicate!)

In my case, I want the name of one variable to be stored in a second variable of type string.

In C#, this is trivial using nameof, like so...

int someVar = 3

string varName = nameof(someVar)
// 'varName' now holds the string value "someVar"

This I believe happens at compile-time so no reflection or anything else is needed at run-time. It simply subs in the name of the variable.

It's pretty handy when you, for instance, want to define a query object where your member names match the query parameters passed in a URL.

Here's a pseudo-code example (i.e. this clearly won't compile, but shows what I'm after):

struct queryObject{

    let userName  : String
    let highScore : Int

    var getUrl:String{
        return "http://ift.tt/2yY8JZ9"
    }
}

Here's how you'd use it and what it would return:

let queryObject = QueryObject(userName:"Maverick", highScore:123456)

let urlString = queryObject.getUrl

The return value would be:

http://ift.tt/2BdWq0F

The advantages of this are:

  1. The names of your members are used as the query parameters keeping the struct's usage clean and simple
  2. There's no need to define constants to hold the query parameter names since they are implicit from the member names
  3. You get full refactoring support of actual symbols, not find-replace of strings

For instance, if I simply refactored userName to be userId, the output would now be...

http://ift.tt/2yYBbtO

...without me having to change any string constants.

So, can this be done in Swift? Can you get the actual variable name and store it in a second variable?





cannot access a member of class java.nio.DirectByteBuffer (in module java.base) with modifiers "public"

Got a project which is built to still support Java 6. The code below is inside a jar file built with Compiler compliance level 1.6

That jar file should be called from java apps built for java 6 or newer. It runs fine in Java 8 as well.

Now with Java9, I get problems with nio.DirectByteBuffer, and I tried to solve it this way, using reflection:

@SuppressWarnings("unchecked")
static void cleanDirectBuffer(sun.nio.ch.DirectBuffer buffer) {
    if (JAVA_VERSION < 1.9) {
        sun.misc.Cleaner cleaner = buffer.cleaner();
        if (cleaner != null) cleaner.clean();
    } else {
        // For java9 do it the reflection way
        @SuppressWarnings("rawtypes")
        Class B = buffer.getClass(); 
        // will be a java.nio.DirectBuffer, which is unknown if compiled in 1.6 compliance mode
        try {
            java.lang.reflect.Method CleanerMethod = B.getMethod("cleaner");
            CleanerMethod.setAccessible(true);  // fails here !
            Object cleaner = CleanerMethod.invoke(buffer);
            if (cleaner == null) return;
            @SuppressWarnings("rawtypes")
            Class C = cleaner.getClass();
            java.lang.reflect.Method CleanMethod = C.getMethod("clean");
            CleanMethod.invoke(cleaner);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (Exception other) {
            other.printStackTrace();
        }
    }
}

The JAVA_VERSION detection is fine and switches nicely, depending on the version my calling code is using. jre6 to jre8 environments use nicely the sun.misc.Cleaner path, but that does not work in java9

You'll probably notice that I'm not an expert in java.reflection. By guessing, I found .setAccessible(true); but that did not help at all.

What else am I missing, or is there a better approach to my problem?





A way to find the angle at which to emit a ray so that it hits the target. With the source and target known

I wanted to make an AI that makes the decision to shoot a reflecting laser towards the target accurately from it's position, reflecting from a stable, non moving smooth surface like a mirror.

One option is to rotate the ray until it finds the position to hit the mirror so that the laser hits the target after reflection. But I would like to consider more options apart from the apparent brute force method.





In UWP can we dynamically compile and invoke new Page in UWP using Dynamic compilation and member invocation using C# Reflection?

Using System.CodeDom.Compiler.CodeDomProvider I can able to compile codes till .Net 4+. So I can dynamically compile the code in runtime and invoke any WinFrom forms using C# Reflection programmatically.

Similarly can we do that in UWP platform? I tried the same flow with UWP, but those compiler assemblies are not supported in UWP.





lundi 18 décembre 2017

Nullable Annotation not appears in field

I'm using Java Reflections for get model's fields and some fields are Nullables with the @Nullable annotation.

public class Category implements Serializable {

    private String id;
    private String name;
    @Nullable
    private String description;
    @Nullable
    private String urlIcon;
    private ArrayList<String> sounds;

    //Getters and setters
}

And when I try to get the annotations of fields, any field has annotations :( I don't know why.

Can you help me please.

public static <T> String getCreateSentence(Class<T> clazz) {
    StringBuilder sentence = new StringBuilder("CREATE TABLE " + clazz.getSimpleName() + " (");
    //Loop for ever field in Model
    for (Field field : clazz.getDeclaredFields()) {
        if (field.getType().isPrimitive() && !field.getName().equals("serialVersionUID")) {
            if (field.getType().equals(Integer.TYPE)
                    || field.getType().equals(Boolean.TYPE)
                    || field.getType().equals(Byte.TYPE)
                    || field.getType().equals(Long.TYPE)
                    || field.getType().equals(Short.TYPE)) {
                //field.isAnnotation is false ever and field.getDeclaredAnnotations has 0 items ever
                if (field.isAnnotationPresent(Nullable.class)) {
                    sentence.append(field.getName()).append(" INT NULL, ");
                } else {
                    sentence.append(field.getName()).append(" INT NOT NULL, ");
                }
            } else {
                //I evaluate another field types
            }
        }
    }

    return sentence.substring(0, sentence.lastIndexOf(",")) + ");";
}





Detecting Duplicates in Class Instance's Variable Values

class Translator(object):
    def __init__(self, tracking_col='tracking_id', coding_col='coding', qualifying_code_col='qualifying_code',
                 translation_col='translation'):
        self._results = []
        self.tracking_col = tracking_col
        self.data_col = coding_col
        self.definition_col = qualifying_code_col
        self.translation_col = translation_col
        self.__validate_parameters(self.__dict__)

    def __validate_parameters(self, variable_values):
        class_values = {}
        for key, value in variable_values.items():
            if type(value) is str:
                class_values.setdefault(value, set()).add(key)
        for key, values in class_values.items():
            # If there is more than one value, there is a duplicate
            if len(values) > 1:
                raise Exception('Duplicate column names exist in parameters. \'{}\' are set to \'{}\'. '
                                'Do not use duplicate column names.'.format(values, key))

This class cannot have the duplicate values for any of the 'col' variables. If duplicate values exist, logic further in the class may not crash but will create unpredictable results.

Upon instantiation my function __validate_parameters will detect duplicate values and raise an Exception. The problem is I am dumping all the values out to a dictionary, iterating to create another dictionary, and finally manually raising an exception (which from what I've been told is the wrong thing to do in any situation). It's also rather verbose.

Is there a shorter and more concise way to validate for duplicates while propogating an error up without the complexity above?





dimanche 17 décembre 2017

Ray tracing sphere reflection bug

I am trying to implement the ray tracing algorithm and I have some trouble computing the reflected rays of spherical objects.It seems that for some particular rays, the reflected ray just passes through and is collinear with the traced ray. Bellow is how i record the ray - sphere intersection:

bool Sphere::intersectLocal(const ray & r, isect & i) const {
    Vec3d P = r.getPosition();
    Vec3d D = r.getDirection();
    //D.normalize();
    double a = dot(D, D);
    double b = 2 * dot(P, D);
    double c = dot(P, P) - 1;
    double delta = b * b - 4 * a * c;
    if (delta < 0)
        return false;
    if (delta == 0) {
        double t = -b / 2 * a;
        Vec3d Q = P + t * D;
        Vec3d N = Q;
        N.normalize();
        i.setT(t);
        i.setN(N);
        i.setObject(this);
        return true;
    }
    if (delta > 0) {
        double t1 = (-b - sqrt(delta)) / 2 * a;
        double t2 = (-b + sqrt(delta)) / 2 * a;
        double t;
        if (t1 > 0) t = t1;
        else if (t2 > 0) t = t2;
        else return false;
        Vec3d N = P + t * D;
        N.normalize();
        i.setT(t);
        i.setN(N);
        i.setObject(this);
        return true;
    }
    return false;
}

And this is how I compute the reflected ray for each intersection:

isect i;
if (scene - > intersect(r, i)) {
    // An intersection occured!  
    const Material & m = i.getMaterial();
    double t = i.t;
    Vec3d N = i.N;
    Vec3d I = m.shade(scene, r, i); //local illumination
    if (!m.kr(i).iszero() && depth >= 0) {
        // compute reflection direction
        Vec3d raydir = r.getDirection();
        Vec3d refldir = 2 * dot(-raydir, i.N) * i.N + raydir;
        refldir.normalize();
        ray reflectionRay = ray(r.at(i.t), refldir, ray::RayType::REFLECTION);
        Vec3d reflection = traceRay(reflectionRay, thresh, depth - 1);
        Vec3d R = reflection;
        I += R;
    }
    return I;
} else {
    // No intersection.  This ray travels to infinity, so we color
    // it according to the background color, which in this (simple) case
    // is just black.
    return Vec3d(0.0, 0.0, 0.0);
}

The code above seems to work fine for most of the points on the sphere where the rays intersect, but for others it does not reflect as i expected

enter image description here

enter image description here

enter image description here





samedi 16 décembre 2017

Restricted AppDomain invoke method via reflection and passing boxed argument

i created new restricted AppDomain and loaded some assemblies to this AppDomain, but when i try to invoke method via reflection Security Exception occurs when my argumet is boxed to object, when argument type exactly equal to parameter type it works as expected, what permission i should add to pass boxed parameters ?

I use these permissions:

        var ps = new PermissionSet(PermissionState.None);
        ps.AddPermission(new SecurityPermission(PermissionState.Unrestricted));
        ps.AddPermission(new FileIOPermission(FileIOPermissionAccess.AllAccess, pluginPath));
        ps.SetPermission(new ReflectionPermission(PermissionState.Unrestricted));





Why getDeclaredMethod with Class as second param throws NoSuchMethodException?

I want to test a private method using reflection. In this case isEdible method from Food class.

public class Food {

  private Boolean isEdible() {
    return true;
  }
}

When I'm using getDeclaredMethod without specifying Food class, it ran successfully.

@Test
  public void foodTestOne() throws Exception {
    Food food = new Food();
    Method method = food.getClass().getDeclaredMethod("isEdible");
    method.setAccessible(true);
    boolean isEdible = (boolean) method.invoke(food);
    assertTrue(isEdible);
  }

But when I add Food Class on a second parameter I got NoSuchMethodException.

@Test
  public void foodTestTwo() throws Exception {
    Food food = new Food();
    Method method = food.getClass().getDeclaredMethod("isEdible", Food.class);
    // execution stop here
  }

My questions are:

  1. What should I put in second parameters to make it work? Changing getDeclaredMethod("isEdible", Boolean.class) still throws the same Exception.
  2. It seems pretty basic and intuitive, why is this happening?