lundi 30 novembre 2015

Passing value from a different app domain to the primary (Main) app domain

From this post, I am able to load a dll into an app domain and get the types in that dll and print them in the temporary domain's function if I want to. But I now want to pass these types back to the primary domain (which has Main). I found this thread which says I need to wrap my object in a MarshalByRef type of class and pass it as an argument, and I tried that but I get an exception. Here is what I have (slightly modified from the example given by @Scoregraphic in the first linked thread)

    public class TypeListWrapper : MarshalByRefObject
    {
            public Type[] typeList { get; set; }
    }

    internal class InstanceProxy : MarshalByRefObject
    {
        public void LoadLibrary(string path, TypeListWrapper tlw)
        {
            Assembly asm = Assembly.LoadFrom(path);

            var x = asm.GetExportedTypes();//works fine

            tlw.typeList = x;//getting exception on this line
        }
    }

    public class Program
    {

        public static void Main(string[] args)
        {
            string pathToDll = Assembly.GetExecutingAssembly().Location;
            string path = "/path/to/abc.dll";

            try
            {
                AppDomainSetup domainSetup = new AppDomainSetup
                {
                    PrivateBinPath = pathToDll
                };
                AppDomain domain = AppDomain.CreateDomain("TempDomain", null, domainSetup);
                InstanceProxy proxy = domain.CreateInstanceFromAndUnwrap(pathToDll, typeof(InstanceProxy).FullName) as InstanceProxy;
                TypeListWrapper tlw = new TypeListWrapper();
                if (proxy != null)
                {
                    proxy.LoadLibrary(path, tlw);
                }


                AppDomain.Unload(domain);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
            }

            Console.ReadLine();
        }
    }

I get the exception:

Could not load file or assembly 'abc, Version=1.0.0.5, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

If I remove the tlw argument from the function and remove this assignment, it works just fine. I'm completely stumped on this.





Reflection on swing components

I'm trying to assign a value to a swing component through reflection. Let's use a JCheckBox for example. I have the following class:

public class JCheckBoxTest
{
    private JCheckBox test;

    public JCheckBoxTest()
    {
        this.test = new JCheckBox();
    }

    public reflectionTest()
    {
        Field field;
        Method method;

        field = this.getClass().getDeclaredField("test");
        method = field.getType().getSuperclass().getDeclaredMethod("setSelected");

        method.invoke(field, "true");
    }
}

This code fails at:

method = field.getType().getSuperclass().getDeclaredMethod("setSelected");

because it cannot find the specified "setSelected" method since it is located inside the inner class "ToggleButtonModel" of the superclass "JToggleButton" which is extended by the "JCheckBox" class.

What would be the best approach to solve this?

Thanks.

Edit: Corrected typo in code.





Java - Annotation Processing

I have an annotation which marks classes that contain an inner class which implements a named interface.

Here's an example of how this annotation is used:

public interface Implementable {}

@Deserializable(Implementable.class)
public class ImplementableFactory {
    public static Implementable getImplementable() {
        return new Impl();
    }
    private class Impl implements Implementable {}
}

And here's the annotation itself:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public @interface Deserializable {
    Class value();
}

I'd like to do some annotation processing to ensure this contract. I've created an annotation processing class for that purpose:

public class DeserializableProcessor extends AbstractProcessor {

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        for(Element element : roundEnv.getElementsAnnotatedWith(Deserializable.class)){
            TypeMirror expected = getDeserializableValue(element);
            if (expected != null) {
                element.getEnclosedElements().forEach( enclosed -> {
                    if (enclosed.getKind().equals(ElementKind.CLASS)) {
                        Boolean found = false;
                        ***...?***
                        if (!found) {
                            String message = String.format("Classes marked with the Deserializable annotation must contain an inner class with implements the value of the annotation. %s does not contain a class which implements %s.",
                                    element.getSimpleName().toString(),
                                    expected.toString());
                            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message);
                        }
                    }
                });
            }
        }
        return true;
    }

    private TypeMirror getDeserializableValue(Element element) {
        ...
    }
}

At this point it simply iterates through each of the inner classes - I'm not sure how to check to see if enclosed implements expected. Can someone point me in the right direction?





Get generic type from a Function

I would like to get the result type of a java.util.function.Function. (If the return type is already Optional then I don't have to do anything, but otherwise I have to wrap it in Optionals and for obvious reasons I don't want to wrap it twice.

Here is my example code:

public static void main(String[] args) {
    printType(Integer::parse);
    printType(new Foo());
    printType(Functions::tryParseInt);
}

public static void printType(Function<String, ?> function) {
    System.out.println(function.getClass());
    System.out.println(function.getClass().getGenericInterfaces()[0]);
    if (!returnsOptional(function)) function = function.then(Optional::ofNullable);
    [...]
}

private static class Foo implements Function<String, Integer> {
    @Override
    public Integer apply(String t) {
        return Integer.parse(t);
    }

}

public static Optional<Integer> tryParseInt(String a) {
    return Optional.empty();
}

I get this as result:

class my.util.Functions$$Lambda$1/1705736037
interface java.util.function.Function
class my.util.Functions$Foo
java.util.function.Function<java.lang.String, java.lang.Integer>
class my.util.Functions$$Lambda$3/764977973
interface java.util.function.Function

but actually I would like get java.lang.Integer or java.util.Optional from the method. For second one this works using get getGenericSuperClass() + ParameterizedType, but not for the other two? What am I doing wrong?

java version "1.8.0_51"





How to get absolute physical path of .java file?

I am not trying to get the working directory or the .class file path, instead I want the path of the code that is running.

something like "C:\Workspace\ProjectName...\src\test\java...\MyFile.java"

This has to be obtained by running MyFile.java

Any ideas?





how to find all extended classes from package/single java file using reflection in java?

Suppose I use a single Java file which contains 2 classes like A & B (B extends A).

Then how can I find class A using reflection in Java?

Are there any methods present in Java reflection to get all super classes?





Is there a way to implement dynamic factory pattern in c++?

The DYNAMIC FACTORY pattern describes how to create a factory that allows the creation of unanticipated products derived from the same abstraction by storing the information about their concrete type in external metadata

from : http://ift.tt/1NDlRc7





dimanche 29 novembre 2015

Type.GetMethod returns allways null

I want to get a MethodInfo object from the calling method to determine if there is a special attribute set on that method.

The Programm class with the calling method Run()

class Program
    {
        private static RestHandler _handler = new RestHandler();
        static void Main(string[] args)
        {
            Run();
        }

        [Rest("GET")]
        static void Run()
        {   
            _handler.Handler(typeof(Program));
        }
    }

The Class where I would like to determine the custom attribute

public class RestHandler
    {
        public void Handler(Type t)
        {
            StackFrame frame = new StackFrame(1);
            var method = frame.GetMethod();

            MethodInfo methodInfo = t.GetMethod(method.Name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);

            var attributes = methodInfo.GetCustomAttributes<RestAttribute>();
        }
    }

The attribute class

 public class RestAttribute : Attribute
    {
        public RestAttribute(string method)
        {
            Method = method;
        }

        public string Method { get; set; }
    }

My problem here is that the MethodInfo object (methodInfo) is allways null even the method object from the stack frame ist set correctly. The property method.Name returns the correct name of the calling method. Any idea why the methodInfo object is allways null?





java - limitation of static methods and newInstance() introspection - any workaround?

So, I'm working on a custom logging/audit module for some of our java spring back-ends.

This module is used to fire all sorts of custom events that are saved to a database for later retrieval/reporting.

  • "User2 registered"
  • "User5 bought productX"
  • "MoonLanding occurred with UserN, UserB"

all sorts of events really. each event has an event_type and an event_category and a wide variety of varying parameters.

There is a big hierarchy of EventBuilder classes which allow building all those custom events that end up in the exact same database table (using one single associate JPA Entity). Each of those EventBuilder has a different constructor that takes different parameters relevant to that "custom event record" we are trying to build.

Now the Problem is as follow: All EventBuilder have the 2 following method: getEventType() and getEventCategory() which are sort of meta static methods but are not declared as such. The only reason they are not declared as static is so that some introspection/reflection code can find all the EventBuilder classes, instantiate them using newInstance(), assume those 2 methods will be there (as part of an Interface always implemented) and build a list of all possible event_types, event_categories and how they relate to each other.

The problem with this is that is required those EventBuilder classes to have a default constructor so that those 2 methods can be queried and that info retrieved without having to use the real custom constructors of those object. It works but it introduces the possibility to have EventBuilder instance not initialised properly.

It seems that the 2 available options are massively flawed:

  • current solution of bad default constructor (so that all those classes can be instantiated in a generic way) and 2 static methods not declared as static (so that they can be overridden in the class hierarchy)
  • making the 2 methods static but now they can't be part of a java interface, they can't be overridden in the class hierarchy, the introspection/reflection code can't assume they will be there, etc.

Has anyone got a better third idea? Many Thanks!





samedi 28 novembre 2015

Kotlin: Reflection exposes KClassImpl to me rather than proper type

It seems that Kotlin is exposing a KClassImpl to me rather than the real type.

For example:

val TYPE_TO_BYTES = mapOf(Boolean::class to 1, Byte::class to 1, Short::class to 2)

inline fun <reified T> read(address: Long): T {
    val type = T::class
    val bytes = TYPE_TO_BYTES.getRaw(type) // null
    ...
}

Yet when I call methods on T::class they seem correct; for example T::class.simpleName does give me the proper values.

If I print type it shows kotlin.reflect.jvm.internal.KClassImpl, thus the reason TYPE_TO_BYTES doesn't work correctly.

I "patched" this by both mapping and getting using qualifiedName but this isn't as elegant and isn't as safe as possible for my use case.





Returning Annotations of all methods in a given class using reflection

I have been searching around the internet for awhile now, and am having some issues when it comes to returning annotations specifically for methods. The code I have already returns it for classes, but I want a second section that names each method, and its annotations. Can someone point me to how I can achieve this?

My main file:

import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Scanner;
import java.lang.reflect.*;



public class A1 {
     public static void main (String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException {
            for (String s: args) {
                Class classTemp = Class.forName(s); //class named after argument
                Method tempMethods[] = classTemp.getMethods();

                if(classTemp.isAnnotationPresent(AnnoInterface.class)) { // checks for annotations
                AnnoInterface ai = (AnnoInterface) classTemp.getAnnotation(AnnoInterface.class); //gets annotations

                System.out.println("");
                System.out.println("---------------------------------------");
                System.out.println("Class Review Information:");

                //Print out class annotation for reviewers
                System.out.println("");
                System.out.print("Reviewers: ");
                for (String reviewers: ai.reviewers()) {
                System.out.print(reviewers + ", ");
                } // end

                //Print out class annotation for review dates
                System.out.println("");
                System.out.print("Review Dates: ");
                for (String reviewers: ai.reviewDates()) {
                System.out.print(reviewers + ", ");
                } // end

                //Prints out problem with class
                System.out.println("");
                System.out.print("Problem(s): " + ai.problem());
                //end

                //Prints out if it has been changed since the last review
                System.out.println();
                String temp = "";
                if (ai.isChanged() == true) { temp = "The code has been changed since the last review"; }
                if (ai.isChanged() == false) { temp = "The current review is in date, no changes made since."; }
                System.out.print(temp);
                //end

                System.out.println();
                System.out.println("--------------------------------------- ");



                }

                else {
                    System.out.println("");
                    System.out.println("-------------------------------------------");
                    System.out.println("Sorry, this class has not yet been reviewed");
                    System.out.println("Please review it then try again.");
                    System.out.println("-------------------------------------------");
                }
}
}
}

AnnotationInterface -

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD })

public @interface AnnoInterface
{
/** Reviewers */
 String[] reviewers();

 /** reviewed date */
 String[] reviewDates();

 /** what kind of problem the class/method has */
 public enum problems { 
     Syntax, Logic, Runtime, None;
     }

 problems problem();

 /** have changes been made since the last review */
 boolean isChanged() default false;

 /** has the class been reviewed */
 boolean isReviewed() default false;

}

ClassExample1 - (The class I'm running the annotation check on) -

import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;



@AnnoInterface (reviewDates = { "1/5/1995", "5/10/2005" }, 
                reviewers = { "John Doe", "Mom" }, 
                isChanged = false,
                isReviewed = true,
                problem = AnnoInterface.problems.Logic
    )

public class ClassExample1 {

    @AnnoInterface (reviewDates = { "5/1/5991", "10/5/5002" }, 
            reviewers = { "Mom", "John Doe" }, 
            isChanged = true,
            isReviewed = false,
            problem = AnnoInterface.problems.Syntax
)
    public static void helloWorld(String args[]){
        System.out.println("Hello World !");

}

    public static void evenOrOdd (String[] args) {
        int[] numbers = new int[]{1,2,3,4,5,6,7,8,9,10};
          for(int i=0; i < numbers.length; i++){
              if(numbers[i]%2 == 0)
                  System.out.println(numbers[i] + " even");
              else
                  System.out.println(numbers[i] + " odd");
          }
    }


}

The only code I've managed to get some kind of success with was when I asked the user specifically for what method they wanted to look up annotations for, but it would always return a "NoSuchMethodException". The thing is I would like to return all annotations in the class file, and not just the specific methods asked anyway.

Any help is greatly appreciated.. thanks!

Edit -

Okay so.. I tried something again and its closer than what I've had.. i added this snippet -

Method[] methods = ai.getClass().getMethods();
                 for (Method method : methods) {
                     if ( method.isAnnotationPresent(AnnoInterface.class));
                        AnnoInterface temp1 = method.getAnnotation(AnnoInterface.class);
                        System.out.println("");
                        System.out.print("Reviewers: ");
                        for (String reviewers: temp1.reviewers()) {
                        System.out.print(reviewers + ", ");
             }
            }

but.. i get an exception in thread "main" java.lang.NullPointersException at A1.main(A1.java:62). Line 62 is:

for (String reviewers: temp1.reviewers())

Alright.. realized I didnt add brackets to an if statement which fixed the nullpointerexception.. but now its just empty after the class annotations.. will update when I figure this out...





Scala object reference with reflection

I'm new to the reflection API.

I'd like to get a reference to an object from its name. I've made it to the point where I can get a reference using the class name of the object.

$ scala
Welcome to Scala version 2.11.7 ...

scala> case object Foo { val x = 5 }
defined object Foo

scala> import scala.reflect.runtime.{universe => ru}
import scala.reflect.runtime.{universe=>ru}

scala> val m = ru.runtimeMirror(getClass.getClassLoader)
m: reflect.runtime.universe.Mirror...

scala> val f = m.reflectModule(m.staticModule(Foo.getClass.getName)).instance.asInstanceOf[Foo.type]
f: Foo.type = Foo

scala> f.x
res0: Int = 5

Works just fine. However, trying to use the computed type name as a string doesn't work:

scala> m.staticModule(Foo.getClass.getName)
res2: reflect.runtime.universe.ModuleSymbol = object iw$Foo$

scala> Foo.getClass.getName
res1: String = Foo$

scala> m.staticModule("Foo$")
scala.ScalaReflectionException: object Foo$ not found.
  at scala.reflect.internal.Mirrors$RootsBase.staticModule(Mirrors.scala:162)
  at scala.reflect.internal.Mirrors$RootsBase.staticModule(Mirrors.scala:22)
  ... 33 elided

I would expect the following to work

scala> val f = m.reflectModule(m.staticModule("Foo$").instance.asInstance

What am I missing here? Thanks.





Get Value from java.lang.reflect.Field Object Without Knowing Original Object

I have a program which turns a .class file into a Class object. I then extract every field from the Class object with getFields(). I iterate through each field, and I want to print out their value. I know I can use:

field.get(obj)

But I don't know what to put in the obj parameter. I didn't have the field's object originally, so how do I get the field's value?

Thanks for your help!





how can I detect that I'm calling repeatedly to static fields

If I have two classes, Person and Email and the class Person have static field of Email (that it's name is "email") and the class Email have static field of String (that it's name is "address").

There is a way to know that I'm came from Person if I execute the line code: "Person.email.address"?





Assigning to an array field through reflection in c#

I use reflection to get FieldInfos in a class and assign to them with FieldInfo.SetValue. It works fine when i assign primitive types (i use Convert.ChangeType to convert from object to type) but doesn't work if the field is an array. It works if i use Array.Cast but the type is only known at runtime so i cant cast. I saw lots of topics on this but none of them worked so far.

I get this exception:

ArgumentException: Object type System.Object[] cannot be converted to target type: System.Single[]

I know why it happens i just can't find a way to convert the data. Any ideas?





Using Scala reflection to check for a method on an object or to find key type on a Map

I am porting a class from Ruby to Scala 2.11 that implements variable merging in messages. I would like to pass an array of objects to the merge method and have it search each object for the keys that are referenced in the text of the message.

The core of this is a method called lookUp(key: String, obj: AnyRef) which receives a single key for which to search, and a single object on which to search for the key. If the object is a Map, and the Map's keys are either Symbol or String, then it will look in the Map for the requested key. Otherwise it will check if the object has a method with the same name of the key, and if so, it will invoke that method.

In the existing Ruby code, it is trivially easy to do this:

def look_up(key, obj)
  if obj.respond_to?(:has_key?) && obj.has_key?(key)
    obj[key]
  elsif obj.respond_to?(key)
    obj.send(key)
  elsif obj.instance_variable_defined?(ivar = "@#{key}")
    obj.instance_variable_get(ivar)
  end
end

Since it's easy to do so, the Ruby code also looks for an instance variable of the same name. I don't necessarily need that functionality in my Scala version.

One of the issues I am having is that the examples I've found require that I know the object's class ahead of time so I can call ru.typeOf[MyClass].declaration(ru.TermName("key")) (where ru is scala.reflect.runtime.universe).

Another issue is that this message merge can be happening hundreds of times per minute, and reflection seems to be a slow, involved process. If this all works as planned, I'll likely cache the reflection results by object type.





Go: GAE - Datastore and reflection

I'm trying to get rid of some boiler plate code when it comes to checking if an Entity already exists in the Datastore. Since I haven't used the reflect package before I figured this would be a good start.

This is what I came up with - seems to work, are there any obvious no-no's when looking at this snippet of code? Using reflection feels like black magic to me ;)

func exists(c appengine.Context, entity interface{}, field string, value string) (interface{}, error) {
  T := reflect.TypeOf(entity)
  result := reflect.New(reflect.SliceOf(T))
  entityName := T.Elem().Name()

  q := datastore.NewQuery(entityName).Filter(field+" =", value).Limit(1)
  keys, err := q.GetAll(c, result.Interface())
  if err != nil {
    return false, err
  }

  objects := result.Elem().Interface()
  if reflect.ValueOf(objects).Len() == 1 {
    elem := reflect.ValueOf(objects).Index(0).Elem()
    if elem.Kind() != reflect.Struct {
      // TODO: Return appropriate error msg
      return nil, nil
    }

    f := elem.FieldByName("KeyId")
    if f.IsValid() && f.CanSet() {
      f.SetInt(keys[0].IntID())
    }

    return elem.Interface(), nil
  }

  return nil, nil
}





vendredi 27 novembre 2015

Go Differentiate Between Structs with same name in the same package

Background:

I am trying to cache some struct information for efficiency but am having trouble differentiating between struct with the same name, within the same package.

Example Code:

func Struct(s interface{}){
  val := reflect.ValueOf(s)
  typ := val.Type()

  // cache in map, but with what key? 
  typ.Name()               // not good enough
  typ.PkgPath + typ.Name() // not good enough
}

func Caller1() {
  type Test struct {
    Name string
  }

  t:= Test{
    Name:"Test Name",
  }

  Struct(t)
}

func Caller2() {
  type Test struct {
    Address string
    Other string
  }

  t:= Test{
    Address:"Test Address",
    Other:"OTHER",
  }

  Struct(t)
}

Problem

Can't find a proper unique key as:

  • Name is the same "Test"
  • PkgPath with be identical as both functions are in same package
  • Pointers etc is out because need a consistent key otherwise caching would be pointless

Can anyone help in finding a way to uniquely identify these structs?

P.S. I do realize that changing of the struct name would solve the issue, but need to handle this scenario as I have a generic library that others will be calling and may have the structs defined like the above example.





getDeclaredField and Annotation

I am suing springframework validation to validate my applications. Currently I am passing my fieldname as a hardcoded string to the validator. This has caused a lot of issue, where if a fieldname in the model changes the validations would fail.

I have looked into reflection to get the filename from the model using getDeclaredField. This method however returns a list of files for that class and if I need to get a specific field I will have to pass the right index. Eg. fields[8].getName(). So if the positioning of the fields changes I will have an issue.

I am wondering if there is any other simpler way I can pass a specific fieldname to the rejectValue ? would a custom annotation work? Like

@firstName private String firstName;

then use getDeclaredAnnotations to get my fieldname?

Here is how I am doing it now.

private String firstName; private String lastName;

errors.rejectValue("lastName ", ValidationConstants.INVALID_NULL_OR_BLANK_CODE);

if I using reflection errors.rejectValue(fields[2].getName(), ValidationConstants.INVALID_NULL_OR_BLANK_CODE);

Thanks.





Why use PrivateObject when we can do the same with pure reflection

I read this thread and I wonder why anyone should use PrivateObject. I can´t see any value that cannot be achieved by pure reflection in as many steps. However it adds a further dependency to my project. Furthermore PrivateObject also uses reflection.

Are there any usings for that class in favour over Reflection? Consider this:

var myProp = typeof(MyClass).GetProperty("Name", BindingFlags.Instance | BindingFlags.NonPublic);

over

var myProp = new PrivateObject(typeof(MyClass)).GetFieldOrProperty("Name");

I notice there is a pretty small difference in that I won´t need to know the actual access-modifier, but I can´t see any further advantage on one over the other? Do you?





Add annotation to all the controllers in play framework using global class or java reflection

In an existing project we want to introduce swagger for rest api documentation. We cant modify each and every controller and method. so , looking for a decorator which will automatically add the annotation to all the controller class and also which will add annotation for methods depending on the request type. Tried with java reflections but couldnt find any option to add annotation .

public <A> A getControllerInstance(Class<A> clazz) {
    Annotation[] annotations = clazz.getAnnotations();
    // This check is used to suppress any annotation if it is not injected
    // using spring DI. Example Security.Authenticated.
    if (clazz.isAnnotationPresent(Component.class))
        return ctx.getBean(clazz);
    else
        return null;
}

public Action onRequest(Request request, Method actionMethod) {
    System.out.println("before each request..." + request.toString());
    Object[] obj = actionMethod.getAnnotations();

    return super.onRequest(request, actionMethod);
}





Scala dynamically access a field in a class

Consider a class with lots of values

class Test {
    val a1 = "test1"
    val a2 = "test2"
    ..
    ..
    val a25 = "test25"
}

Can a function like this be written to access the nth variable.

def getVar(n: Int, test: Test) = {
    test.("test"+n) //something like this to access the nth variable
}

I know this can be done with a collection but my question is can this type of reflection be done.





How can i return reflected object from AppDomain Assembly.LoadFrom

I need return objects, from 2 versions of dlls in one process. I'm doing this incompatible with each other, and i want to connect to 2 types of MS WHQL Servers in one process. I'm trying use this:

namespace AppDomainTester
{
    public class Program
    {
        [STAThread]
        public static void Main(string[] args)
        {
            string pathToDll = Assembly.GetExecutingAssembly().Location;
            string HCKpath = Path.Combine(Path.GetDirectoryName(pathToDll), @"WhqlDlls\HCK",
                @"microsoft.windows.kits.hardware.objectmodel.dbconnection.dll");
            string HLKpath = Path.Combine(Path.GetDirectoryName(pathToDll), @"WhqlDlls\HLK",
                @"microsoft.windows.kits.hardware.objectmodel.dbconnection.dll");
            try
            {
                object hck;
                object hlk;
                // HCK 
                AppDomainSetup domainSetupHck = new AppDomainSetup
                {
                    PrivateBinPath = pathToDll
                };
                AppDomain domainHck = AppDomain.CreateDomain("HCK", null, domainSetupHck);
                InstanceProxy proxyHck =
                    domainHck.CreateInstanceFromAndUnwrap(pathToDll, typeof (InstanceProxy).FullName) as InstanceProxy;
                if (proxyHck != null)
                {
                    object obj = new object();
                    hck = proxyHck.LoadLibrary(HCKpath, "tfs13-com-hck1");
                }
                //HLK
                AppDomainSetup domainSetupHlk = new AppDomainSetup
                {
                    PrivateBinPath = pathToDll
                };
                AppDomain domainHlk = AppDomain.CreateDomain("HLK", null, domainSetupHlk);
                InstanceProxy proxyHlk =
                    domainHck.CreateInstanceFromAndUnwrap(pathToDll, typeof (InstanceProxy).FullName) as InstanceProxy;

                if (proxyHlk != null)
                {
                    object obj = new object();
                    hlk = proxyHlk.LoadLibrary(HCKpath, "tfs13-com-hck1");
                }
                //var some = domainHck.GetAssemblies();

                AppDomain.Unload(domainHck);
                AppDomain.Unload(domainHlk);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
            }

        }
    }

    internal class InstanceProxy : MarshalByRefObject
    {

        private object obj;

        public object LoadLibrary(string path, string controller)
        {
            Assembly asm = Assembly.LoadFrom(path);
            Type[] types = asm.GetExportedTypes();
            Type type =
                types.FirstOrDefault(
                    t =>
                        (t.FullName == "Microsoft.Windows.Kits.Hardware.ObjectModel.DBConnection.DatabaseProjectManager"));
            if (type != null)
            {
                var constructor = type.GetConstructors().Single(x => x.GetParameters().Length == 1);
                obj = constructor.Invoke(new[] {controller});
            }
            return null;
        }
    }
}

I want to return obj from LoadLibrary method, but if i try return obj;, i recieve an exception :( What am I doing wrong?





jeudi 26 novembre 2015

How to convert slice of map to slice of struct in go?

I am trying to convert to map to struct, I am almost done, finally I got a problem, I can not convert slice to struct:

func readDocTo(in bson.M, out reflect.Value) {
    outt := out.Type()
    outk := outt.Kind()

    for {
        if outk == reflect.Ptr && out.IsNil() {
            out.Set(reflect.New(outt.Elem()))
        }
        if outk == reflect.Ptr {
            out = out.Elem()
            outt = out.Type()
            outk = out.Kind()
            continue
        }
        break
    }

    st := out.Type()
    n := st.NumField()
    for i := 0; i < n; i++ {
        field := st.Field(i)
        if field.PkgPath != "" {
            continue // Private field
        }
        tag := field.Tag.Get("bson")
        if tag == "" && strings.Index(string(field.Tag), ":") < 0 {
            tag = string(field.Tag)
        }
        if tag == "-" {
            continue
        }

        // XXX Drop this after a few releases.
        if s := strings.Index(tag, "/"); s >= 0 {
            recommend := tag[:s]
            for _, c := range tag[s+1:] {
                switch c {
                case 'c':
                    recommend += ",omitempty"
                case 's':
                    recommend += ",minsize"
                default:
                    msg := fmt.Sprintf("Unsupported flag %q in tag %q of type %s", string([]byte{uint8(c)}), tag, st)
                    panic(externalPanic(msg))
                }
            }
            msg := fmt.Sprintf("Replace tag %q in field %s of type %s by %q", tag, field.Name, st, recommend)
            panic(externalPanic(msg))
        }

        if tag == "" {
            tag = strings.ToLower(field.Name)
        }

        fieldt := field.Type
        val, ok := in[tag]
        switch fieldt.Kind() {
        case reflect.Ptr:
            if !ok {
                out.Field(i).Set(reflect.New(fieldt.Elem()))
            } else {
                readDocTo(val.(bson.M), out.Field(i))
            }
        case reflect.String:
            if ok {
                out.Field(i).Set(reflect.ValueOf(val))
            }
        case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
            out.Field(i).SetInt(reflect.ValueOf(val).Int())
        case reflect.Slice:
            if ok {
                s := reflect.ValueOf(val)
                for j := 0; j < s.Len(); j++ {
                    item := s.Index(j)
                    fmt.Println(item.Interface().(bson.M))
                    fmt.Println(out.Field(i))
                    // TODO
                    // readDocTo(item.Interface().(bson.M), out.Field(i).Elem())
                }
            }
        }

    }
}





Getting implemented interfaces from the proxy

You normally crate a proxy using

val proxy = Proxy.newProxyInstance(ClassLoader, Class<?>[] interfaces, handler) 

I am interested in the second parameter because I save created proxies in a list and I want to recreate the proxy with the same interfaces later on. Should I memorize interface classes along with the proxy list or there is a way to map proxy to its implementing interfaces, likewise Proxy.getInvocationHandler(proxy) does for handlers?





AppDomain dependency resolving order

I have a .Net multi-appdomain application that resembles a scheduler. Default app domain has a timer and a list of jobs that are contained each in it's own assembly and ran on separate appdomains. Assemblies containing jobs are kept each in it's separate directory under the application root.

(root)\Library\AssemblyName\

Each assembly directory contains the assembly and its dependencies. Some of those dependencies(e.g. log4net) are contained in the root directory as well because the default domain has it's separate log. I want to load the job assembly and its dependencies from the assembly directory if they exist there, and if not i want to load them from the application root directory. Both main appdomain and child domains use the same library with Interfaces similar to Quartz's IJob interface, so this assembly needs to be loaded from the same file.

The reason for this rather odd requirement is that application jobs should have automatic update ability. So a specially designed class would download the job from an API, unload the appdomain the job is on, delete the job assembly with all the dependencies and reload the appdomain and restart the job, without interfering with the other jobs operation. I've tried using AppdomainSetup to set the Assembly directory before the root directory,

domainSetup.PrivateBinPath = @"\\Library\\AssemblyName\\" 

however my dependencies get resolved from the root directory every time.

So basically i want my dependency to be resolved from the 1. Assembly folder if possible 2. Root directory





How to solve Swift memory leaks when type casting/checking values from reflection?

I created a Serializable Protocol that turns a object in a [String:AnyObject] object (JSON format) using reflection, but I'm getting a leak warning when type casting/checking in Swift 2.1.

I already knows that Swift has some memory leaks problems, as related in the SwifityJSON project (link: http://ift.tt/1MF3ksh), but I couldn't get my code to work without the leaks.

I'm using Xcode 7.1.1 (7B1005) and Swift 2.1, my deployment target is 8.0 and the app is running in the Iphone 5 simulator.

Someone knows any workaround or solution to this? Maybe I'm doing something wrong. My code: (just add the code to a project and call test function with leaks profile):

public class testB: Serializable {

    let a:Int
    let b:Int?

    public init() {
        a = 1
        b = nil
    }

}

public class testA : Serializable {

    let a:String
    let b:Double
    var c:[String:Serializable]
    var d:[Double]
    var e:[String:String]

    public init() {
        a = "teste"
        b = 1.2
        c = [String:Serializable]()
        c["teste"] = testB()
        d = [Double()]
        d[0] = 3.5
        e = [String:String]()
        e["teste"] = "teste"
    }    
}


public func test() {
    testA().toDictionary()
}

public protocol Serializable {

}

extension Serializable {

    func getValue(unknownValue:Any) -> Any? {

        let mi = Mirror(reflecting: unknownValue)
        if mi.displayStyle != .Optional {
            return unknownValue
        }

        if mi.children.count == 0 {
            return nil
        }

        let (_, some) = mi.children.first!
        return some
    }

    //Memory Leak happens here.
    func toDictionary() -> [String:AnyObject] {

        var result = [String:AnyObject]()

        let serializableMirror = Mirror(reflecting: self)

            for childMirror in serializableMirror.children {

                let label = childMirror.label

                if let value = self.getValue(childMirror.value) {

                    if let x = value as? NSData {
                        result[label!] = x.base64EncodedDataWithOptions(.Encoding64CharacterLineLength)

                    } else if let x = value as? NSDate {
                        result[label!] = x.timeIntervalSince1970

                    } else if let x = value as? Serializable {
                        result[label!] = x.toDictionary()

                    } else if let x = value as? [NSData] {
                        var newArray = [NSData]()
                        for xItem in x {
                            newArray.append(xItem.base64EncodedDataWithOptions(.Encoding64CharacterLineLength))
                        }
                        result[label!] = newArray

                    } else if let x = value as? [NSDate] {
                        var newArray = [NSTimeInterval]()
                        for xItem in x {
                            newArray.append(xItem.timeIntervalSince1970)
                        }
                        result[label!] = newArray

                    } else if let x = value as? [Serializable] {
                        var newArray = [[String:AnyObject]]()
                        for xItem in x {
                            newArray.append(xItem.toDictionary())
                        }
                        result[label!] = newArray

                    } else if let x = value as? [String:NSData] {
                        var newDictionary = [String:NSData]()
                        for (y,z) in x {
                            newDictionary[y] = z.base64EncodedDataWithOptions(.Encoding64CharacterLineLength)
                        }
                        result[label!] = newDictionary

                    } else if let x = value as? [String:NSDate] {
                        var newDictionary = [String:NSTimeInterval]()
                        for (y,z) in x {
                            newDictionary[y] = z.timeIntervalSince1970
                        }
                        result[label!] = newDictionary

                    } else if let x = value as? [String:Serializable] {
                        var newDictionary = [String:[String:AnyObject]]()
                        for (y,z) in x {
                            newDictionary[y] = z.toDictionary()
                        }
                        result[label!] = newDictionary

                    } else if value is NSNumber || value is String
                        || value is [Bool] || value is [Int] || value is [Double] || value is [Float] || value is [String]
                        || value is [String:Bool] || value is [String:Int] || value is [String:Double] || value is [String:Float] || value is [String:String] {
                        if let x = value as? AnyObject {
                            result[label!] = x
                        }
                    }
            }
        }
        return result
    }
}

The leaks message.

enter image description here





Silverlight - Reflection - dynamic class - Inject code in the setter

In Silverlight, I use a Dynamic class. I want to call boolean function before set property, for example :

Private _MyVar as Object
Public Property MyVar as Object
    Get
        return _MyVar
    End Get
    Set(value as Object)
        If IsUpdateProp(value,"MyVar") Then _myVar = value
    End Set
End Property

Private Function IsUpdateProp(value as Object, key as string) as Boolean
     If value Is Nothing AndAlso GetValueProperty(key) Is Nothing
                OrElse (value IsNot Nothing AndAlso 
                   GetValueProperty(key) IsNot Nothing AndAlso 
                          value.Equals(GetValueProperty(key))) Then
         Return False
     End If

     RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(key))
     Return True`
End Function

I want to make this with reflection, my code :

Dim dp As DynamicProperty = properties(i)
Dim fb As FieldBuilder = tb.DefineField("_" & dp.Name, dp.Type,
            FieldAttributes.Private)
Dim pb As PropertyBuilder = tb.DefineProperty(dp.Name, 
             PropertyAttributes.HasDefault, dp.Type, Nothing)
Dim isModify = GetType(Dynamic.DynamicClass).GetMethod("SetModifyField",
                  New Type() {GetType(Object), GetType(String)})
Dim mbSet As MethodBuilder = tb.DefineMethod("set_" & dp.Name, 
                    MethodAttributes.Public Or 
                        MethodAttributes.SpecialName Or 
                           MethodAttributes.HideBySig, 
                                Nothing, New Type() {dp.Type})
Dim genSet As ILGenerator = mbSet.GetILGenerator()
Dim mLabel = genSet.DefineLabel

genSet.Emit(OpCodes.Nop)
genSet.Emit(OpCodes.Ldarg_0)
genSet.Emit(OpCodes.Ldarg_1)
genSet.Emit(OpCodes.Box, dp.Type)
genSet.Emit(OpCodes.Ldstr, dp.Name)
genSet.Emit(OpCodes.Call, isModify)
genSet.Emit(OpCodes.Call, GetType(Convert).GetMethod("ToBoolean", 
                                    New   Type() {GetType(Object)}))
genSet.Emit(OpCodes.Stloc_0)
genSet.Emit(OpCodes.Ldloc_0)
genSet.Emit(OpCodes.Brfalse_S, mLabel)
genSet.Emit(OpCodes.Ldarg_0)
genSet.Emit(OpCodes.Ldarg_1)
genSet.Emit(OpCodes.Stfld, fb)
genSet.MarkLabel(mLabel)
genSet.Emit(OpCodes.Nop)
genSet.Emit(OpCodes.Nop)
genSet.Emit(OpCodes.Ret)

At runtime, when I call setvalue on my property I get this error message:

System.Security.VerificationException: Cette opération pourrait déstabiliser le runtime." & vbCrLf & " à DynamicClass1.set_MyVar(Nullable`1 )

Thanks





Java - At least one field is not null

Here is my use case: I have a set of beans that are generated by a third-party library and I need to check if each bean has at least one field that is not null.





Reference for function defined inside an object

How do I get reference for a def defined inside a object.

object SomeObject {
  def someMethod(x: String): String = s"Hello $x"
}

I want reference for someMethod function.

What I tried so far:

val method = SomeObject.getClass.getDeclaredMethods.head
val function = method _

But this returns () => java.lang.reflect.Method = <function0> instead of (String) => (String) = <function1>.

TIA





C# Reflection - To find stored procedures used within the method

Is it possible to read an assembly and get the stored procedure names used in it?





mercredi 25 novembre 2015

How can you access static properties dynamically from an object of type 'Type'?

In one of our assemblies, we have a namespace which is full of MarkupExtension subclasses, each which expose a static property called Geometry, like so...

public class SomeClass : MarkupExtension
{
    public static Geometry Geometry = Geometry.Parse("<bla>");

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return Geometry;
    }
}

In code, we're using Assembly.GetTypes() to find them (they're all in a particular namespace) and I'm trying to retrieve that static variable. That's where I'm hitting a wall.

We can't get it from creating an instance (stored in a dynamic) since you can't access static's that way. You also can't simply cast the type to dynamic and try to call ((dynamic)type).Geometry.

What would be the most effective way to retrieve that static?

Note: It is assumed all such classes will have a static property called 'Geometry'. If it weren't in a static, we would have exposed it via a base property.





.NET Native compiled UWP app throws exception

I have an UWP (Windows 10) app which runs perfectly on debug mode (.NET Native disabled).

When I am running it on release mode, (or in debug mode with .NET Native compilation on I receive error on return context.Set().ToList(); line.

    public IEnumerable<TMobileEntity> ReadAll()
    {
        using (var context = new DataContext(database.DatabasePath))
        {
            return context.Set<TMobileEntity>().ToList();
        }
    }

here is an exception details

{System.TypeInitializationException: A type initializer threw an exception. To determine which type, inspect the InnerException's StackTrace property. ---> System.PlatformNotSupportedException: TypeHandles are not supported for types that return true for ContainsGenericParameters. at Internal.Reflection.Core.NonPortable.RuntimeType.get_TypeHandle() in f:\dd\ndp\fxcore\src\System.Private.CoreLib\Internal\Reflection\Core\NonPortable\RuntimeType.cs:line 262 at System.Reflection.Runtime.TypeInfos.RuntimeTypeInfo.IsAssignableFrom(TypeInfo typeInfo) in f:\dd\ndp\fxcore\src\System.Private.Reflection.Core\System\Reflection\Runtime\TypeInfos\RuntimeTypeInfo.cs:line 398 at Remotion.Linq.Parsing.Structure.IntermediateModel.SupportedMethodSpecifications.HasIndexSelectorParameter(MethodInfo methodInfo, Int32 parameterPosition) at Remotion.Linq.Parsing.Structure.IntermediateModel.SupportedMethodSpecifications.<>c__DisplayClass14.b__13(MethodInfo mi) at System.Func2.Invoke(T arg) at System.Linq.Enumerable.<>c__DisplayClass01.b__1(TSource x) in f:\dd\ndp\fxcore\Open\src\System.Linq\src\System\Linq\Enumerable.cs:line 69 at System.Func2.Invoke(T arg) at System.Linq.Enumerable.WhereEnumerableIterator1.MoveNext() in f:\dd\ndp\fxcore\Open\src\System.Linq\src\System\Linq\Enumerable.cs:line 199 at Remotion.Linq.Parsing.Structure.NodeTypeProviders.MethodInfoBasedNodeTypeRegistry.Register(IEnumerable1 methods, Type nodeType) at Remotion.Linq.Parsing.Structure.NodeTypeProviders.MethodInfoBasedNodeTypeRegistry.CreateFromRelinqAssembly() at Microsoft.Data.Entity.Query.QueryCompiler.CreateNodeTypeProvider() at Microsoft.Data.Entity.Query.QueryCompiler..cctor() at System.Runtime.CompilerServices.ClassConstructorRunner.Call[T](IntPtr pfn) at System.Runtime.CompilerServices.ClassConstructorRunner.EnsureClassConstructorRun(Void* returnValue, StaticClassConstructionContext* pContext) in f:\dd\ndp\fxcore\src\System.Private.CoreLib\System\Runtime\CompilerServices\ClassConstructorRunner.cs:line 69 Exception_EndOfInnerExceptionStack at System.Runtime.CompilerServices.ClassConstructorRunner.EnsureClassConstructorRun(Void* returnValue, StaticClassConstructionContext* pContext) in f:\dd\ndp\fxcore\src\System.Private.CoreLib\System\Runtime\CompilerServices\ClassConstructorRunner.cs:line 86 at Microsoft.Data.Entity.Query.QueryCompiler.Preprocess(Expression query, QueryContext queryContext) at Microsoft.Data.Entity.Query.QueryCompiler.Execute[TResult](Expression query) at Microsoft.Data.Entity.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression) at Remotion.Linq.QueryableBase1.GetEnumerator() at Microsoft.Data.Entity.Internal.InternalDbSet1.System.Collections.Generic.IEnumerable<TEntity>.GetEnumerator() at System.Collections.Generic.List1..ctor(IEnumerable1 collection) in f:\dd\ndp\fxcore\src\System.Collections\System\Collections\Generic\List.cs:line 88 at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source) at TIKSN.GroceryChecklist.ModernMobile.Data.RepositoryBase1.ReadAll() in E:\Visual Studio Online\tiksn\Grocery Checklist\Develop\ModernMobile.Data.UWP\RepositoryBase.cs:line 42
at TIKSN.GroceryChecklist.MobileDataService.ChecklistItemsManagementService.<GetCurrentChecklistItems>d__5.MoveNext() in E:\Visual Studio Online\tiksn\Grocery Checklist\Develop\MobileDataService\ChecklistItemsManagementService.cs:line 62 at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() in f:\dd\ndp\fxcore\src\System.Private.CoreLib\System\Runtime\ExceptionServices\ExceptionDispatchInfo.cs:line 66 at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) in f:\dd\ndp\fxcore\src\System.Private.Threading\System\Runtime\CompilerServices\TaskAwaiter.cs:line 186 at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) in f:\dd\ndp\fxcore\src\System.Private.Threading\System\Runtime\CompilerServices\TaskAwaiter.cs:line 155 at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) in f:\dd\ndp\fxcore\src\System.Private.Threading\System\Runtime\CompilerServices\TaskAwaiter.cs:line 127 at System.Runtime.CompilerServices.TaskAwaiter
1.GetResult() in f:\dd\ndp\fxcore\src\System.Private.Threading\System\Runtime\CompilerServices\TaskAwaiter.cs:line 320 at TIKSN.GroceryChecklist.ModernMobile.ViewModels.ChecklistPageViewModel.d__15.MoveNext() in E:\Visual Studio Online\tiksn\Grocery Checklist\Develop\ModernMobile.UWP\ViewModels\ChecklistPageViewModel.cs:line 82 at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() in f:\dd\ndp\fxcore\src\System.Private.CoreLib\System\Runtime\ExceptionServices\ExceptionDispatchInfo.cs:line 66 at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) in f:\dd\ndp\fxcore\src\System.Private.Threading\System\Runtime\CompilerServices\TaskAwaiter.cs:line 186 at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) in f:\dd\ndp\fxcore\src\System.Private.Threading\System\Runtime\CompilerServices\TaskAwaiter.cs:line 155 at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) in f:\dd\ndp\fxcore\src\System.Private.Threading\System\Runtime\CompilerServices\TaskAwaiter.cs:line 127 at System.Runtime.CompilerServices.TaskAwaiter.GetResult() in f:\dd\ndp\fxcore\src\System.Private.Threading\System\Runtime\CompilerServices\TaskAwaiter.cs:line 112 at TIKSN.GroceryChecklist.ModernMobile.ViewModels.PageViewModelBase.d__46.MoveNext() in E:\Visual Studio Online\tiksn\Grocery Checklist\Develop\ModernMobile.UWP\ViewModels\PageViewModelBase.cs:line 102} System.Exception {System.TypeInitializationException}





Load/compile code from string in Mono.Cecil

I'm writing a patch using Mono.Cecil for a third-party dll to add some functionality (I see you shaking your head in disappointment at me--I am too). Right now I've got it working using an array of Instructions which I insert in the proper place and then recompile and output the dll.

This works, but right now my array is a bunch of assembly instructions. I'd rather load a .cs file as a string (or array of strings), compile it in-memory, either with Mono or .NET Reflection, load it with Mono, and replace the original method in my patched dll.

How can I do this?





Serialization of Dynamic Attribute Content to XML

I have seen from other questions, e.g. How to add an attribute to a property at runtime, that it is possible to add an Attribute to a Property dynamically. Suppose I have a property to which I have added an attribute, as shown:

[MyCustomAttribute("MyCustomAttributeValue")]
public bool PropertyName { get; set; }

If my class were serialized, this would probably appear as follows, without MyCustomAttribute/MyCustomAttributeValue:

<q1:Object>
  <PropertyName xmlns="namespace">Value</PropertyName>
</q1:Object>

XmlAttribute allows the user to set a custom Namespace or DataType, which then appears within the PropertyName element, but what can be done so that the custom attribute is serialized and saved to the XML, as something like:

<q1:Object>
  <PropertyName xmlns="namespace" MyCustomAttribute="MyCustomAttributeValue">Value</PropertyName>
</q1:Object>

Is this possible without writing a custom XML Serializer?





Java reflection for mono android

I was facing WRAP_CONTENT not work on a RecyclerView , so I googled it and found the workaround. When I tried to implement the workaround in c#, I was stuck at this line:

insetsDirtyField = RecyclerView.LayoutParams.class.getDeclaredField("mInsetsDirty");

Here I tried to port the original java code,and ported code avilable in gist





Is it possible to use TypeTag to instanciate a mixin type?

Reusing http://ift.tt/1SjMrVA, I wrote:

def newInstance[T: TypeTag]: T = {
  val tpe = typeOf[T]

  def fail = throw new IllegalArgumentException(s"Cannot instantiate $tpe")

  val noArgConstructor = tpe.member(termNames.CONSTRUCTOR) match {
    case symbol: TermSymbol =>
      symbol.alternatives.collectFirst {
        case constr: MethodSymbol if constr.paramLists == Nil || constr.paramLists == List(Nil) => constr
      } getOrElse fail

    case NoSymbol => fail
  }
  val classMirror = typeTag[T].mirror.reflectClass(tpe.typeSymbol.asClass)
  classMirror.reflectConstructor(noArgConstructor).apply().asInstanceOf[T]
}

But, it does not seem to work correctly with mixin types. Indeed, the following code:

class B { def m = 0 }

trait A extends B { override def m = super.m + 1 }

val x = newInstance[B with A]

produces (with code compiled using scala 2.11.7)

java.lang.IllegalArgumentException: Cannot instantiate B with A

Are mixin types not a part of the Scala type algebra?





Attach in-memory assembly in custom AppDomain

I have created a sandbox AppDomain:

public AppDomain CreateSandbox()
{
    var setup = new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase };
    var permissionSet = new PermissionSet(PermissionState.None);
    permissionSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.NoFlags));
    permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
    permissionSet.AddPermission(new FileIOPermission(PermissionState.Unrestricted)); // TODO: Restrict IO
    var appDomain = AppDomain.CreateDomain("Sandbox", null, setup, permissionSet);
    return appDomain;
}

I also have an assembly loaded from a byte[] fileData:

var assembly = Assembly.Load(fileData);
var appDomain = CreateSandBox();

How can I load this assembly or the fileData bytes into the appDomain and then use it?





Java reflection CAP#1 casting error

I'm working on a java project, this is my code:

Class<? extends Component> componentClass = componentField.getType();
Component tempComponent = entity.get(componentClass);

This is my error:

incompatible types: Class<CAP#1> cannot be converted to Class<? extends Component> where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?

componentField is a field from which I know that it extends Component, when I try to get the type it returns me a fresh-type CAP#1, is it possible to cast it to a class extending from component? the entity.get() is a generic method that takes a <T extends Component> as argument.





reflection vector on a sphere ?

Hello I've an exercice in mathematics (actually I study openGl (the light and reflection on objects) but this one is pure mathematics) and I'm stuck here all day ... I don't know how to solve it. I would like at least any explanation. the exercice says : ( I translated it from french to english so please if there's anything wrong just correct me)

    we have the cartesian equation of a sphere  :

    (x − h)^2 + (y − k)^2 + (z − l)^2 = r^2

    where ( h, k , l) is its center and its radius r

    A light ray direction (vector) v = (a, b, c) strikes a sphere 
    at the point ( x0, y0 , z0 ) and is reflected at the same angle as that it 
    forms with the normal vector to the sphere at the point (x0, y0, z0 ) 
    in the direction of a vector v'

    Give a formula for the vector v' as a function of (h, k, l) , r, (a, b, c) 
    and (x0, y0, z0 )

the vector v' is the reflected ray??

I'm sorry for the tags I don't know what to put. anyway I really can't solve it that,s why I didn't put here any solution :( I'Ll appreciate any help. thank you.





mardi 24 novembre 2015

Get Entity By TYpe in Entity Framework

I Have a Type witch that contain a Entity Table .

I want Get All Record By Type .

My method like this :

public void read(Type tablename)
{

// read data in context by type
}

I use this code but dont work :

var test=  new CmsContext().Set(_tableName);





Kotlin: How to do reflection on packages?

How can I use reflection on package-level functions, members, etc.? Trying to access javaClass or class doesn't work, neither does package.





Reflection Optimization

I've recently implemented reflection to replace the more tedious aspects of our data retrieval from a SQL database. The old code would look something like this:

_dr = _cmd.ExecuteReader (_dr is the SQLDataReader)
        While _dr.Read (_row is a class object with public properties)
                _row.Property1 = Convert.ToInt16(_dr("Prop1"))
                _row.Property2 = Convert.ToInt16(_dr("Prop2"))
                _row.Property3 = Convert.ToInt16(_dr("Prop3"))
                If IsDBNull(_dr("Prop4")) = False Then _row.Prop4 = _dr("Prop4")
...

Since my code base has a lot of functionality like this, reflection seemed like a good bet to simplify it and make future coding easier. How to assign datareader data into generic List ( of T ) has a great answer that was practically like magic for my needs and easily translated into VB. For easy reference:

Public Shared Function GenericGet(Of T As {Class, New})(ByVal reader As SqlDataReader, ByVal typeString As String)
    'Dim results As New List(Of T)()
    Dim results As Object

    If typeString = "List" Then
        results = New List(Of T)()
    End If

    Dim type As Type = GetType(T)

    Try
        If reader.Read() Then
            ' at least one row: resolve the properties
            Dim props As PropertyInfo() = New PropertyInfo(reader.FieldCount - 1) {}
            For i As Integer = 0 To props.Length - 1
                Dim prop = type.GetProperty(reader.GetName(i), BindingFlags.Instance Or BindingFlags.[Public])
                If prop IsNot Nothing AndAlso prop.CanWrite Then
                    props(i) = prop
                End If
            Next

            Do
                Dim obj = New T()
                For i As Integer = 0 To props.Length - 1
                    Dim prop = props(i)
                    If prop Is Nothing Then
                        Continue For
                    End If
                    ' not mapped
                    Dim val As Object = If(reader.IsDBNull(i), Nothing, reader(i))
                    If val IsNot Nothing Then SetValue(obj, prop, val)
                Next

                If typeString = "List" Then
                    results.Add(obj)
                Else
                    results = obj
                End If

            Loop While reader.Read()
        End If

    Catch ex As Exception
        Helpers.LogMessage("Error: " + ex.Message + ". Stacktrace: " + ex.StackTrace)
    End Try
    Return results
End Function

The only caveat with this is that it is somewhat slower.

My question is how to optimize. Sample code I find online is all in C# and does not convert neatly into VB. Scenario 4 here seems like exactly what I want, but converting it to VB gives all kinds of errors (Using CodeFusion or converter.Telerik.com).

Has anyone done this in VB before? Or can anyone translate what's in that last link?

Any help's appreciated.





How to run a Haskell code by its name?

First of all, I'm new in Haskell and I'm curious how can I implement something that I have working in Java.

A bit of prehistory:

I have a Java-based project with workers. Workers can be started periodically and do some work. A worker - is just a Java-class with some functionality implemented. New workers can be added and configured. Workers' names and parameters are stored in a data base. Periodically, the application gathers workers' details (names, params) from DB and starts them. In Java, to start worker by its name, I do the following:

Class<?> myClass = Class.forName("com.mycompany.superworker");
Constructor<?> constructor = myClass.getConstructor();
MyClass myInstance = (MyClass) constructor.newInstance();
myInstance.run("param1", "param2");

Hence, the application gets worker's name (the actual class name) from DB, gets class and constructor, creates new instance of the class and then just runs it.

Now, the question: how I could implement something similar in Haskell? I mean, if I have some function/module/class whatever implemented in Haskell and I have its name stored in plain text, - then how can I run this code by its name (from the main Haskell-based application, of course)?

Thanks





Where did System.Reflection.MemberTypes go in DNX 5.0?

.net 4.5 had it. Where is it in DNXCore v5?

My specific error message is: DNXCore,Version=v5.0 error CS0103: The name 'MemberTypes' does not exist in the current context.

In previous .nets, it was an Enum on System.Reflection and would be the result of obj.GetType().GetMember(memberName).MemberType (Field, Property, etc)





Cannot retrieve MethodInfo from rhino mocked interface during testing

I'm presently working on a project that includes tests with RhinoMocks mocked objects. Since upgrading to RhinoMocks 3.6.1 from 3.6.0 previously working project code is failing during testing. The issue seems to be caused by changed behavior of mock objects between versions. Previously it was possible to gather MethodInfo from a mocked object via reflection, but that no longer seems to be the case. Should I be setting up my mocks in a different way?

A greatly simplified example follows:

Given an interface to be mocked

public interface IValidator<in T>
{
    bool Validate(T obj);
}

in testing code the mock is created with an expectation:

var validator = MockRepository.GenerateMock<IValidator<string>>();
validator.Expect(v => v.Validate(Arg<string>.Is.Equal("input")))
    .Return(true);
...
// the validator object is then passed into a consumer and assertions 
// are checked to be sure the consumer and validator appropriately 
// behave (outside scope of question)

Within the consumer class reflection is done to get the "Result" method from the interface in order to be invoked during standard execution:

var method = validator.GetType()
    .GetMethod("Result", BindingFlags.Public | BindingFlags.Instance);

The problem is method is now null when using the update version of RhinoMocks.





How can I pass an integer array to a method: Reflection C#

I am currently learning about Reflection in C#. I am calling 2 methods from a class using late binding. The first method (SumNumbers) works. The second method (SumArray) throws an exception saying "Parameter count mismatch". Can anyone kindly tell me how to pass an integer array to this method?

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

namespace ReflectionWithLateBinding
{
    public class Program
    {
        static void Main()
        {
            //load the current executing assembly
            Assembly executingAssembly = Assembly.GetExecutingAssembly();

            //load and instantiate the class dynamically at runtime - "Calculator class"
            Type calculatorType = executingAssembly.GetType("ReflectionWithLateBinding.Calculator");


            //Create an instance of the type --"Calculator class"
            object calculatorInstance = Activator.CreateInstance(calculatorType);

            //Get the info of the method to be executed in the class
            MethodInfo sumArrayMethod = calculatorType.GetMethod("SumNumbers");

            object[] arrayParams = new object[2];

            arrayParams[0] = 5;
            arrayParams[1] = 8;
            int sum;
            //Call "SumNumbers" Method
            sum = (int)sumArrayMethod.Invoke(calculatorInstance, arrayParams);

            Console.WriteLine("Sum = {0}",  sum);



            //load the current executing assembly
            Assembly executingAssembly1 = Assembly.GetExecutingAssembly();

            //load and instantiate the class dynamically at runtime - "Calculator class"
            Type calculatorType1 = executingAssembly1.GetType("ReflectionWithLateBinding.Calculator");


            //Create an instance of the type --"Calculator class"
            object calculatorInstance1 = Activator.CreateInstance(calculatorType1);

            //Get the info of the method to be executed in the class
            MethodInfo sumArrayMethod1 = calculatorType1.GetMethod("SumArray");

            object[] arrayParams1 = new object[4];

            arrayParams1[0] = 5;
            arrayParams1[1] = 8;
            arrayParams1[2] = 2;
            arrayParams1[3] = 1;
            int sum1;
            //Call "SumArray" Method
            sum1 = (int)sumArrayMethod.Invoke(calculatorInstance, arrayParams1);


            Console.WriteLine("Sum = {0}", sum1);

            Console.ReadLine();

        }



    }
}

Class containing the 2 methods

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

namespace ReflectionWithLateBinding
{
    public class Calculator
    {
        public int SumNumbers(int input1, int input2)
        {
            return input1 + input2;
        }


        public int SumArray(int[] input)
        {
            int sum = 0;
            for (int i = 0; i < input.Length; i++)
            {
                sum += i;
            }
            return sum;
        }        
    }


}





Custom Runtime Parameterisation of Variables in C#

I have written a .NET/C# application with a simple action structure, which allows developers to write custom actions, each of which are derived from an IAction interface as shown, simplified for clarity:

interface IAction
{
    bool Start();
}

Each action class derived from the interface above then has various custom properties as appropriate, e.g. an action might have the option to "Compress During Processing" in its action classes (derived from IAction as shown above), e.g.:

[DisplayName("Compress During Processing")]
public bool Compress { get; set; }

These values are then editable in a WinForms PropertyGrid control in the application UI, so that the users of the application can select whether to, in this instance, "Compress During Processing" when running the action.

The application allows the user to create a list of instances of these actions, and will then run them sequentially. I now have some slightly more complex requirements for the properties:

  1. To allow the values of these properties to be set based on something like environment level variables.
  2. To allow the values of these properties to be set based on the outputs of previous Actions, or the properties of previous actions.

For example, with a List { Action1, Action2, Action3, Action4 }, where the first Action is of one type derived from IAction, with the Boolean property "Compress" and the other three are of a different type derived from IAction, which has two properties, a Boolean "Archive" property and a String "Path" property, the user of the application might need to set the values of the properties as follows:

List<Action> :
  Action1 { Compress = true }
  Action2 { Archive = false, Path = "C:\tmp" }
  Action3 { Archive = [[[Action1.Compress]]], Path = [[[EnvironmentVariableSystemPath]]] }
  Action4 { Archive = true, Path = [[[ScriptVariableUserPath]]] }

During processing, when reaching Action3 and Action4, the application should check the values of the properties and set them as appropriate at runtime.

The first two Actions are already possible with the current structure, the user can easily pick the values for each property (Action1.Compress, Action2.Archive and Action2.Path) in the property grid control. However, the new requirements are that the user may also require the ability to set the value of Action3.Archive as a reference to the post processing value of in Action1.Compress, or the value of Action3.Path to an Environment Variable, Script Variable or something similar, which would allow the actions to be run with something like input variables, for instance.

I have been thinking about various approaches to this, but I don't want to introduce some kind of custom generic type that replaces the use of the standard .NET types (above, just bool and string, e.g. I don't want to have to implement some ActionProperty type, accessing its values via .Value or something similar, as this will spoil the current setup of the property grid, where, for instance, if the user wants to just set a boolean value or string path (e.g., to false or "C:\tmp" above), this can be done cleanly.

I assume that once I've found a way to store these things, the processor will just, at the start of each Action, set its values based on these references.

As you may guess from the use of the bool types, I can't just store a reference in the form of "[[[Action1.Compress]]]" or "[[[EnvironmentVariableSystemPath]]]" in the property itself, as you can't place the string "[[[Action1.Compress]]]" into a boolean variable, or any given type. I then considered the idea of adding a .NET Attribute at runtime to the values, e.g. the application would add:

[Reference("Action1.Compress")]

to

public bool Archive { get; set; }

on the Action3 class at runtime, but am not sure if this is possible, and do not now how to design this correctly. Additionally, I'd like the references, however they are stored, to be serialisable for future saving of the objects.

Can anyone advise on how to implement this?





Reflection C# Activator returning a null value

Please I don't know what I am doing wrong, when I run this code, I get an exception: Value cannot be null.... When I run it in debug mode, I see that "calculatorInstance" variable is null. Please help me out.

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

namespace ReflectionWithLateBinding
{
    public class Program
    {
        static void Main()
        {
            //load the current executing assembly
            Assembly executingAssembly = Assembly.GetExecutingAssembly();

            //load and instantiate the class dynamically at runtime - "Calculator class"
            Type calculatorType = executingAssembly.GetType("ReflectionWithLateBinding.Calculator");


            //Create an instance of the type --"Calculator class"
            object calculatorInstance = Activator.CreateInstance(calculatorType);

            //Get the info of the method to be executed in the class
            MethodInfo sumArrayMethod = calculatorType.GetMethod("SumNumbers");

            object[] arrayParams = new object[2];

            arrayParams[0] = 5;
            arrayParams[1] = 8;
            int sum;
            sum = (int)sumArrayMethod.Invoke(calculatorInstance, arrayParams);

            Console.WriteLine("Sum = {0}",  sum);

            Console.ReadLine();

        }



        public class Calculator
        {
            public int SumNumbers(int input1, int input2)
            {
                return input1 + input2;
            }
        }
    }
}





System.Reflection multiple assemblies error after update

After updating .NET Framework NuGet packages that my solution references to last prerelease version. I've got a building error:

Multiple assemblies with equivalent identity have been imported: 'C:\Projects\RP\packages\System.Reflection.4.1.0-beta-23516\lib\net46\System.Reflection.dll' and 'C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.6\Facades\System.Reflection.dll'. Remove one of the duplicate references.

I can't figure out how resolve this issue. If I remove System.Reflection using NuGet it throws reference error exception, it wants System.Reflection v.4.1.0.0.

Could not load file or assembly 'System.Reflection, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

How can I remove a duplicate?





Getting and setting the value of nested properties

I have these classes

 public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public virtual Address Address { get; set; }
    }

    public class Address
    {
        public string Line1 { get; set; }
        public string Line2 { get; set; }
    }

 public class Flat
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public virtual Address Address { get; set; }
    }

This is the code I am using to set the values on Flat class

var employee = new Employee() { ID = 1, Name = "Test",  Address = new Address() {Line1 = "1", Line2 = "2" } };
            Flat flat = new Flat();

            Map(employee, flat);

static void Map<TI, VI>(TI source, VI result)
        {
            foreach (PropertyInfo item source.GetType().GetRuntimeProperties())
            {
              if (item.GetValue(source) != null)
                {
                  if (result.GetType().GetRuntimeProperty(item.Name) != null)
                        {
                            Type type = result.GetType().GetRuntimeProperty(item.Name).PropertyType;

                            var innerObj = FormatterServices.GetUninitializedObject(type);
                            result.GetType().GetRuntimeProperty(item.Name).SetValue(result, innerObj);
                            Map(item.GetValue(source), innerObj);
                        }
                        else
                        {
                            Map(item.GetValue(source), result);
                        }
                }   
            }              
        }
    }

I would really appreciate if you could advise me if this is the right approach to map the nested properties. If this is not the case please provide alternatives.





lundi 23 novembre 2015

NoClassDefFoundError: scala/collection/Seq

I'm calling a method in a Java class from JRuby via reflection

fact = Factory.factory('aString')

calls this method in java

public static Service factory(String url) throws IllegalArgumentException { return new _Service(url); };

and I'm getting

Java::JavaLang::NoClassDefFoundError: scala/collection/Seq





C# request to plugin

I'm trying implement simple plugin system to my app, but i have problem with communication with my plugin.

I made interface to my plugin:

public interface IAlgorithm
{
    /// <summary>
    /// New request in current simulation tick - all logic should be run after request
    /// </summary>
    /// <param name="pTime">Simulation time in [ms] from simulation start</param>
    /// <param name="pObject">Manipulating object</param>
    /// <param name="pWorld">Current world</param>
    void Request(int pTime, PhysicalObject pObject, World pWorld);
}

and next I create my plugin to hook keyboard:

 public class Main : IAlgorithm
{
    private int m_Direction;
    private readonly GlobalKeyboardHook m_Hook = new GlobalKeyboardHook();

    public Main()
    {
        m_Hook.HookedKeys.Add(Keys.Up);
        m_Hook.HookedKeys.Add(Keys.Down);
        m_Hook.HookedKeys.Add(Keys.Right);
        m_Hook.HookedKeys.Add(Keys.Left);
        m_Hook.KeyDown += KeyClicked;
    }

    private void KeyClicked(object sender, KeyEventArgs e)
    {
        switch (e.KeyCode)
        {
            case Keys.Down:
                m_Direction = 180;
                break;
            case Keys.Up:
                m_Direction = 0;
                break;
            case Keys.Left:
                m_Direction = 90;
                break;
            case Keys.Right:
                m_Direction = 270;
                break;
        }
    }

    public void Request(int pTime, PhysicalObject pObject, World pWorld)
    {
        pObject.Movement.Power = 100;
        pObject.Movement.Direction = m_Direction;
    }
}

Next in my main program I try to use my plugin like this:

var myAssembly = Assembly.LoadFile(myPath).GetTypes().First(x => x.Name == "Main");
IAlgorithm myAlgorithm = ((IAlgorithm)Activator.CreateInstance(myAssembly ));

and it's working, but if I want make some request to plugin

myAlgorithm.Request(pSimulationTime, myPhysicalObject, pWorld);

after that I don't have any changes in myPhysicalObject

but if I use MessageBox:

myAlgorithm.Request(pSimulationTime, myPhysicalObject, pWorld); 
MessageBox.Show(myPhysicalObject.Movement.Direction)

I can see correct value in MB.

I don't know what is incorrect in my logic and I don't understand why it's working after some pause. Have you some ideas??





How can I get a Class object form primitive? [duplicate]

This question already has an answer here:

Obviously this is possible (as Class has isPrimitive() method) but how I can do this directly? E.g. reflection api able to cast a primitive type to Class:

import java.lang.reflect.Method;


public class TestClass {

        public static void m(){}
        public static void m(Object o){}
        public static void m(int i){}
        public static void m(Integer i){}

        public static void main(String[] args){

                TestClass tc=new TestClass();
                Method[] mtds=tc.getClass().getDeclaredMethods();

                for (int i = 0; i < mtds.length; i++) {
                        System.out.print(mtds[i].getName());
                        Class[] prms=mtds[i].getParameterTypes();
                        for (int j = 0; j < prms.length; j++) {
                                System.out.print("-"+prms[j].getCanonicalName());

                        }
                        System.out.println();
                }        
        }
}

output is:

m

m-java.lang.Object

m-int

m-java.lang.Integer

main-java.lang.String[]

Integer and int are different so it is not autoboxing. Anything (except creating an utility class with reflection and getParameterTypes() ) do not come at my mind (everything else I've tried failed).





Listing all `dynamic` variables for a class in Swift2

I'm writing a base class that implements KVO, and I would like to infer the names of the dynamic attributes of the class. For example:

class BaseClass {
  func beginObserving() {
    // What are the dynamic attributes to observe?
    // In the case of "SubClass" below, it should be ["name"]
    let attributes = ???
    for attribute in attributes {
      self.addObserver(self, forKeyPath: attribute, options: [.New, .Old], context: &KVOContext)
    }
  }
}

class SubClass : BaseClass {
  dynamic var name: String!
}

List of class's properties in swift explains how to do this with Mirror (reflection), but it does not appear to work for dynamic vars (i.e., if I removed the dynamic keyword the linked code would work for this case).





swift reflection causes impossible nil value for any

I'm trying to use swift reflection to check for changes in objects so I can send only changed properties up to the server. Some of my properties are optional. To compare those values, I need to unwrap them but, of course, you can ONLY unwrap actual values, not nil values. So, I need to check if one of the values is nil before I compare them.

In my playground, I tried the following:

import UIKit

class myClass
{

    var fieldOne:String?
    var fieldTwo:Int?
    var fieldThree:Float?

}

var oneMyClass = myClass()
oneMyClass.fieldOne = "blah"
oneMyClass.fieldThree = 3.5

var oneOtherClass = myClass()
oneOtherClass.fieldOne = "stuff"
oneOtherClass.fieldTwo = 3

let aMirror = Mirror(reflecting: oneMyClass)
let bMirror = Mirror(reflecting: oneOtherClass)

for thing in aMirror.children
{
    for thing2 in bMirror.children
    {
        if thing.label! == thing2.label!
        {
            print("property: \(thing.label!)")

            print("before: \(thing.value)")
            print("after: \(thing2.value)")
            print("")

            //let myTest = thing.value == nil ? "nil" : "not nil"
        }
    }
}

And it generates the following output:

property: fieldOne
before: Optional("blah")
after: Optional("stuff")

property: fieldTwo
before: nil
after: Optional(3)

property: fieldThree
before: Optional(3.5)
after: nil

As you can see, the expected properties are displayed as "nil". However, if you uncomment the let statement, you get an error stating:

playground52.swift:37:38: error: value of type 'Any' (aka 'protocol<>') can never be nil, comparison isn't allowed

And yet, we know from the output that it IS nil. How can this be and what can I do about it?





What is the difference between Type.IsPublic and Type.IsVisible

In C# the Type class instances have a lot of properties. Two of them are IsPublic and IsVisible:

  • Type.IsPublic - Gets a value indicating whether the Type is declared public.
  • Type.IsVisible - Gets a value indicating whether the Type can be accessed by code outside the assembly.

As far as I know all public members can be accessed outside of the assembly and all others cannot. Two exceptions I can think of are the [InternalsVisibleTo:] assembly attribute and protected modifier for members.

But anyway what is the difference between these two properties?





How to tell the compiler that a property is only accessed if it exists?

I can use HasProperty to check if a property exists. Only if the property exists a method should be executed.

How can the compiler successfully compile even if the property doesn't exist? E.g.

if (UIApplication.SharedApplication.Delegate.HasProperty("Instance"))
{
    AppDelegate customAppDelegate = UIApplication.SharedApplication.Delegate as AppDelegate;
    customAppDelegate.Instance.SomeMethod(true); // can't be compiled because Instance doesn't exist
}

The thing is this: First, I check if the propery exists. If yes I execute my method. So normally the code is never executed (except the property exists), but the compiler isn't able to differentiate this. It only checks if the property exists and doesn't take the if clause into account.

Is there a solution for this?





reflect public fields of anonymous class from outer package [duplicate]

This question already has an answer here:

I want to access public fields of an anonymous class. Lets say for printing all definied public strings. Have a look at this code.

public class Test {         
    public <T> Test(T obj){     
        // print all public Strings
        Class<?> clazz = obj.getClass();
        for ( Field field : clazz.getFields() ) {
            if(field.getType().isAssignableFrom(String.class)){
                try {
                    String s = (String) field.get(obj);
                    System.out.println(s);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }   
    public static void main(String[] args){
        new Test(new Object(){
            public String s = "hello";
        });
    }
}

It prints "hello", no problem so far.
BUT if I separate the class Test from the main method into a package I get the following runtime exception:

java.lang.IllegalAccessException: Class foo.Test can not access a member of class TestMain$1 with modifiers "public" 

If I don't use an anonymous class it works again.
How can I access public fields of anonymous class from outer package?





Check if method/property in AppDelegate exists

I try to find out if the AppDelegate contains a certain property/method. For this I found Check if a property exist in a class and How to check whether an object has certain method/property?, but the AppDelegate seems to be different.

The following will not compile

if(AppDelegate.HasMethod("SomeMethod"))

because

AppDelegate does not contain a defintion for HasMethod.

I also tried other variations but I didn't get it managed to successfully check if the method/property exists or not. Furthermore respondsToSelector seems not to be applicable here. GetType() is also not available for AppDelegate.

What is the correct way for checking if a property/method in AppDelegate exists?





Why are generic type definitions in C# not equatable to those they inherite from

I had expected the following test to pass, but it doesn't.

var iCollectionType = typeof(ICollection<>);
var listSuper = typeof(List<>).GetInterfaces().First(i => i.GUID == iCollectionType.GUID);
Assert.That(listSuper, Is.EqualTo(iCollectionType));

I know that the same type loaded in 2 different app domains aren't considered equal. I don't see how that could be happening in the above code, but I checked the AssemblyQualifiedName of each type, and sure enough they're different.

iCollectionType.AssemblyQualifiedName.Dump();
//System.Collections.Generic.ICollection`1, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

listSuper.AssemblyQualifiedName.Dump();
//null

When I tested further I found that this is the case for all generic interfaces in the list of interfaces for a generic type definition, and also for generic base types; but not for non-generic interfaces and base types, nor for constructed generic types.

I'd like to know why generic type definitions I get using typeof seem to be incompatible with those in their inheritance and base type list. It seems less than awesome.

The closest I've come to finding an answer was on the Type.AssemblyQualifiedName page of MSDN where I found the following quote.

If the current Type object represents a generic parameter, this property returns null.

I'm fairly sure that doesn't apply here since I don't think these are generic parameters, but I could be wrong.

The above was running in LinqPad v5.02.03 if that makes a difference.





getDeclaredFields with actual runtime type, Java reflection

getDeclaredFields[0].getType() is returning only the compile time class info. I have following code, where java.lang.reflect.Field's type is expected with actual type.

public class Wrapper {
     final private Object field1;
      //getters and setters for field1 and constructor
}
class SomeClass {

}
Wrapper wrapper = new Wrapper();
wrapper.field1 = new SomeClass();
System.out.println(wrapper.getType().getDeclaredFields[0].getType());

I am asking this weird requirement, because the serliaztion library I am integrating expects java.lang.reflect.Field





Get physical file name of inherited class

I'm sorry to have to ask a similar question to one I've already asked and has been answered but I'm stuck here and was hoping that someone could set me on the right path again. (Original question here: Get DLL's file name of inherited class)

I have an abstract class called PluginBase.dll from which various other classes inherit. These are all compiled as different plugins for a server application. Let's look at one of these plugins, called PluginMessaging.dll which has a config file called PluginMessaging.dll.config

The method that reads the config settings is in the base class and looks something as follows:

private void ReadConfig()
{
    _runningDir = System.IO.Path.GetDirectoryName(GetType().Assembly.Location);
    _pluginFile = System.IO.Path.GetFileName(GetType().Assembly.Location);
    _configFile = _pluginFile + ".config";

    // Do stuff here that reads from _configFile
}

The line of code that assigns a value to _pluginFile is what I got from the first time I asked the question (answered by Damien_The_Unbeliever) and it works fine, as long as there is only one instance of the PluginMessaging file and its config file.

What I'm trying to do now is to make two copies of the compiled plugin, let's call them PluginMessaging_A.dll and PluginMessaging_B.dll, each with its own corresponding config file, PluginMessaging_A.dll.config and PluginMessaging_B.dll.config respectively.

The problem I'm having is that, the server application iterates through all *.dll files in its Plugins folder, instantiates each one and calls the above ReadConfig() method for each. When the function is called for PluginMessaging_A.dll everything works as expected and the value of _pluginFile is PluginMessaging_A.dll but when the ReadConfig() function for the second copy of the DLL, PluginMessaging_B.dll is called, for some reason, _pluginFile again resolves to PluginMessaging_A.dll

It would seem as if there is some table in memory that remembers the GetType().Assembly information for PluginMessaging.dll the first time it is instantiated, regardless of what physical name it has on disk and retains that for any subsequent instances of the same DLL, albeit with a different name on disk.





C# Reflection on loaded assembly and subscribe to it's event

I'm trying to figure out why this code does not raise a custom event when subscribing to loaded assembly's events by reflection:

public interface ISignalR
{        
    event EventHandler<SignalR_EventArgs> ProgressChanged; 
}    
 public class Test : ISignalR
{               
    public event EventHandler<SignalR_EventArgs> ProgressChanged = delegate { };

    protected virtual void OnProgressChanged(SignalR_EventArgs e)
    {            
        EventHandler<SignalR_EventArgs> handler = ProgressChanged;            
        if (handler != null)
        {                
            handler(this, e);
        }
    }


    static Test()
    {


    }

    public string CallMe(string output)
    {

        OnProgressChanged(new SignalR_EventArgs { MethodName = "MethodName", HubConnectionId = "", Response = "This is A response" });          


        return "yay";
    }
}

And For my reflection:

MethodInfo mi = this.GetType().GetMethod("OnProgressChanged", BindingFlags.Instance |
                                                                                  BindingFlags.Static |
                                                                                  BindingFlags.Public |
                                                                                  BindingFlags.FlattenHierarchy);

                    EventInfo eInfo = type.GetEvent("ProgressChanged", BindingFlags.Instance |
                                                                       BindingFlags.Static |
                                                                       BindingFlags.Public |
                                                                       BindingFlags.FlattenHierarchy);


                    Type eInfoHandlerType = eInfo.EventHandlerType;



                    Delegate del = Delegate.CreateDelegate(eInfoHandlerType, this, mi);
                    eInfo.AddEventHandler(Activator.CreateInstance(type), del);


                    var x = eInfo.GetAddMethod();


public void OnProgressChanged(object sender, SignalR_EventArgs e)
    {

    }

    public void add_ProgressChanged(EventHandler<WGM.SignalR.Common.SignalR_EventArgs> e)
    {

    }

But none of the OnProgressChanged \ add_ProgressChanged seem to be raised when the assembly's event (ProgressChanged is raised).





How to check if a field was initialized or contains the default value in Java

I'm mapping a json string to a class using jackson mapper. The class looks like this:

class MyClass{      
    @JsonProperty("my_boolean")
    private boolean myBoolean;

    @JsonProperty("my_int")
    private int myInt;

    //Getters and setters
}

I want to check if the fields myBoolean and myInt were actually set or contain their default values (false and 0). I tried using reflection and checking if the field was null, but I guess that won't work for primitive types. This is what I have now:

Field[] fields = myClass.getClass().getDeclaredFields();
        for (Field field : fields) {
            try {            
                field.setAccessible(true);
                Object myObject = field.get(myClass);
                if(myObject != null) {
                  //Thought this would work, but it doesn't
                }
            }
         }

How else can I check this?

Thanks.





dimanche 22 novembre 2015

I there any way to get/change the parameter values just before a method is invoked?

I have Class , in which there are 50+ methods. Now I want to do some process to all the parameters in this 50+ methods when the method is called. One way to do is call your process method in each of the methods.

My Question is like, I have a class A

with methods

b c d and e

if c is called from somewhere ,

is there any way to get the parameter values before it reaches c.

Eg:

class A{

public void hello(String message){
// code
}

public void superMethod(Method method){
//this method is invoked before any method call in class A
//you can manipulate parameters and its values.
}
}

}

is there anything like the above given superMethod ?

I am sorry if this is a foolish Question.