vendredi 31 juillet 2015

I'm currently working on an extension on the Moq framework to be also to mock the implementation of non virtual methods. I currently already have this working by obtaining the Method Handle of the original Method and swapping this with the pointer of a user defined Func.

One issue I'm still running into is that when I create the Func in the Moq internal code (inside a class that uses Generics) I run into an issue with RuntimeHelpers.PrepareMethod. (The Func needs to be prepared before we can execute the pointer swap).

When I create exactly the same Func in a normal class (e.g. Program) everything works fine.

Further investigating the issue traced this back to wether the call class had generic arguments or not.

Exception being thrown:

An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll

Additional information: The given generic instantiation was invalid.

I have isolated the problem in the following codeblock:

class Program
{
    static void Main(string[] args)
    {
        new WithoutGeneric().GoExecute();
        new WithGeneric<string>().GoExecute();
    }
}

public class WithoutGeneric
{
    public void GoExecute()
    {
        //Works fine
        StaticMethods.PrepareThisFunc(() => "Test");
    }
}

public class WithGeneric<T>
{
    public void GoExecute()
    {
        //Breaks
        StaticMethods.PrepareThisFunc(() => "Test");
    }
}

public static class StaticMethods
{
    public static void PrepareThisFunc(Func<string> theFunc)
    {
        RuntimeHelpers.PrepareMethod(theFunc.Method.MethodHandle);
    }
}

I have also looked at the current open source CoreCLR code but have not been able to find out what the issue might be.

CoreCLR: http://ift.tt/1MCwuu6

The exception is thrown on the lines: 2435, 2444, 2447

Does anyone have an idea on how to resolve this exception?





standard output stream of void method.invoke()

How can I get the standard output stream of a void method that I invoked as a string?

This is what I have at the moment:

if(method.getGenericReturnType().toString().equals("void"))
       method.invoke(instance, param);
else{
       Object obj = method.invoke(instance, param);
       System.out.println(obj.toString());
}

If i try to do the same to a void method, i get a null exception.





Reflections on tomcat server from the outside

As part of a challenge, I would like to use reflections to get information about the code running on a tomcat server as *.jsp. (Assuming that the server is not configured very secure and allows this).

Google shows absolutely no answer regarding tomcat and reflections from the outside.

I guess I might have to combine it with Remote Procedure Calls or sth like that. Any ideas?





Can you reflect geometry (not textures) in three.js?

I have found many examples of three.js reflecting images, but is at all possible to reflect lines, triangles and shapes? I want to create a mirror pyramid that reflects lines.

For example: http://ift.tt/1M16Sak >This page has lots of lines.

I want to reflect them onto a 3d shape that sits in the middle.

For example: http://ift.tt/1fOvvJq > This page has a mirror ball.

These are the sort of lines of code I am looking at. Not sure if it's even possible.

var textureCube = THREE.ImageUtils.loadTextureCube( urls );
var material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } ) 
shader.uniforms[ "tCube" ].value = textureCube;

At the moment that code above is taking in a bunch of images "urls", but as you probably know by now I want to reflect the geometry in the first link I provided.





How to access all child attributes of type ActionForm defined within a Parent class Object

Please share your thoughts to resolve following problem statement.

Objective: I am trying to develop an Utility in Java 1.6 using reflection. This Utility will access each attribute, non-nullable attribute(s) will be passed through a specific validation routine.

Problem Statement: I am able to access attributes of class ParentBean, ClassB and ClassC. But I am unable to access attributes of ClassD, ClassE. My code goes here.

public class ParentBean extends ActionForm {
private String fullName;
private ClassB classB;
private ClassC classC;
// getters and setters
}
public class ClassB extends ActionForm {  
private long classBid;
private Collection hobby;
private ClassD classD;
private ClassE classE;
// getters and setters
}
public class ClassC extends ActionForm {
private long classCid;
// getters and setters
}
public class ClassD extends ActionForm {
private long classDid;
private String addr1;
// getters and setters
}
public class ClassE extends ActionForm {
private long classEid;
private String contactVal;
private ClassF classF;
// getters and setters
}
public class ClassF extends ActionForm {
private long classFid;
private String attribute;
// getters and setters
}
public class Validate {
public static void main(String[] args) {
ParentBean objParentBean = new ParentBean();
objParentBean.setFullName("MALCOM ANDRWES");
ClassB objClassB = new ClassB();
Collection hobby = new ArrayList();
hobby.add("CRICKET");
objClassB.addHobby(hobby);
ClassD objClassD = new ClassD();
objClassD.setAddr1("123 MAIN STREET");
objClassB.setClassD(objClassD);
ClassE objClassE = new ClassE();
objClassE.setContactVal("97862082202");
ClassF objClassF = new ClassF();
objClassF.setAttribute("XXX"); 
objClassE.setClassF(objClassF);
objClassB.setClassE(objClassE);
// Call Validation Routine
performValidation(actionFormObj);
}
private static void performValidation(ActionForm form) {
Object formObj = form;
List<Field> formFields = getAllFields(formObj.getClass());
List<Field> childFormAttributeLst = validateForm(formObj, formFields);
if (!childFormAttributeLst.isEmpty()) {
validateChildForm(childFormAttributeLst, formObj, form);
}
}
private static List<Field> validateForm(Object formObj,List<Field> formFields) {
List<Field> childFormAttributeLst = new ArrayList<Field>();
for (Field field : formFields) {
if (isPrimitive(field.getType())) {
validate(formObj, field);
} else if (isCollection(field.getType())) {
isCollectionNotNull(formObj, field);
} else {
childFormAttributeLst.add(field);
}
}
return childFormAttributeLst;
}
private static void validateChildForm(List<Field> childFormAttributeLst,Object formObj, ActionForm form) {
List<Field> childFormLst = new ArrayList<Field>();
Method m = null;
Object chldFormObj = null;
for (Field field : childFormAttributeLst) {
try {
StringBuffer fieldName = getFieldName(field);
m = formObj.getClass().getMethod(fieldName.toString(),
new Class<?>[] {});
try {
chldFormObj = m.invoke(formObj, null);
List<Field> formFields = getAllFields(chldFormObj.getClass());
childFormLst = validateForm(chldFormObj, formFields);
// Accessing inner Form bean attributes defined
if(!childFormLst.isEmpty()){
for (Field field2 : childFormLst) {
try{
StringBuffer fieldName1 = getFieldName(field2);
m = field.getType().getMethod(fieldName1.toString(),
new Class<?>[] {});
try{
String invokingClass = field.getType().getName();
// Below line throws error: java.lang.IllegalArgumentException: object is not an instance of declaring class
Object formObj2 = m.invoke(formObj, null); 
} catch (NullPointerException npe) {
npe.printStackTrace();
}
} catch(Exception e){
e.printStackTrace();
}
}
}
} catch (NullPointerException npe) {
npe.printStackTrace();
}
} // catch Blocks
}
}
private static StringBuffer getFieldName(Field field) {
StringBuffer fieldName = new StringBuffer("get"
+ field.getName().substring(0, 1).toUpperCase()
+ field.getName().substring(1, field.getName().length()));
return fieldName;
}
private static List<Field> getAllFields(Class<?> type) {
List<Field> fields = new ArrayList<Field>();
for (Class<?> c = type; c != null; c = c.getSuperclass()) {
if (!(Object.class == c || ActionForm.class == c)) {
fields.addAll(Arrays.asList(c.getDeclaredFields()));
}
}
return fields;
}
private static boolean isPrimitive(Class<?> typeClass) {
if (typeClass == String.class
|| (typeClass == Integer.class || typeClass == Integer.TYPE)
|| typeClass == Timestamp.class
|| (typeClass == Boolean.class || typeClass == Boolean.TYPE)
|| (typeClass == Double.class || typeClass == double.class)
|| (typeClass == Long.class || typeClass == long.class)
|| (typeClass == Float.class || typeClass == float.class)
|| typeClass == java.util.Date.class
|| (typeClass == Character.class || typeClass == char.class)
|| (typeClass == Byte.class || typeClass == byte.class)) {
return true;
} else {
return false;
}
}
private static void validate(Object formObj, Field field) {
try {
field.setAccessible(true);
Object obj = field.get(formObj);
if (null != obj) {
// Perform validation
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private static boolean isCollection(Class<?> typeClass) {
if (Collection.class.isAssignableFrom(typeClass)
|| Map.class.isAssignableFrom(typeClass)) {
return true;
} else {
return false;
}
}
private static void isCollectionNotNull(Object formObj, Field field) {
field.setAccessible(true);
try {
if (Collection.class.isAssignableFrom(field.getType())) {
validateCollection(formObj, field);
} else if (Map.class.isAssignableFrom(field.getType())) {
validateMap(formObj, field);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@SuppressWarnings("rawtypes")
private static void validateMap(Object formObj, Field field)
throws IllegalAccessException {
Map map = (Map) field.get(formObj);
if (!(null == map || map.isEmpty())) {
Set setOfKeys = map.keySet();
for (Object object : setOfKeys) {
// perform validation
}
}
}
@SuppressWarnings("rawtypes")
private static void validateCollection(Object formObj, Field field)
throws IllegalAccessException {
Collection coll = (Collection) field.get(formObj);
if (!(null == coll || coll.isEmpty())) {
for (Object object : coll) {
// perform validation
}
}
}
}





System.out is declared as static final and initialized with null?

When I was going through the System.class I found something which seemed strange to me. When you look at declaration of System.in, System.out, System.err these are decalred as final static but also initialized with null

public final static InputStream in = null;  
public final static PrintStream out = null;  
public final static PrintStream err = null;

Since final can be initialized only once then how these are getting managed ?
When we use System.out.print("..."); It is obvious that out is not null but being a final static how it is not null ?

So can any one explain that how out is initialized which is already declared final ?





Access to internal object fields in Js

Having this code

var a = {date : 12};
for(var t in a){
    alert(t);
}

I have one alert with date property.

But everywhere (i.e. here) i see that it is needed to write :

for (var property in object) {
    if (object.hasOwnProperty(property)) {
        // do stuff
    }
}

So why i don't see internal properties of object?





Building a dynamic classloading framework in Java 8

I want to build a framework which does the following:
1. Loads jar files from specific directories.
2. Discovers information about the jar files.
3. Calls a specific method on a class present in this jar file based on some condition.

I am looking at ClassLoader, specifically getResource / getResources / loadClass methods, and the Method Handles API from Java.

Are there better libraries or techniques for the purpose in Java 8?
How do I ensure that the classes are loaded correctly with all their dependencies?





find out a class variable's defined scope (from within the class)

Given:

class myClass extends \Phalcon\Mvc\Model
{
    public $a;
    protected $b;
    private $c;
}

How can I test that $a is public, $b is protected, and $c is private from within myClass?





jeudi 30 juillet 2015

Mono Cecil get delegate method argument

I have a very simple assembly below. I'm trying to use Mono.Cecil to reflect over it to find the parameter passed to all calls to CallApiAsync. When I isolate the MethodReference for the call I cannot seem to get the parameter x.GetResponse(new SomeRequestType()), I just get the delegate definition ApiMethodAsync<T, TResult>. I've drawn a blank on this, any help appreciated.

public class ApiWrapper
{
 public delegate Task<TResult> ApiMethodAsync<T, TResult>(T api);

 public virtual async Task<SomeResponseType> MakeSomeRequestToApi() 
 {
    return await CallApiAsync<ISomeApi, SomeResponseType>(x => x.GetResponse(new SomeRequestType()));
 }

 public virtual async Task<TResult> CallApiAsync<T, TResult>(ApiMethodAsync<T, TResult> apiMethod) where TResult : new()
 {
    return await Task.FromResult(new TResult());
 }
}

public interface ISomeApi
{
    Task<SomeResponseType> GetResponse(SomeRequestType request);
}

public class SomeResponseType { }
public class SomeRequestType { }

Below is the Mono Cecil code I am using to identify calls to CallApiAsync

var moduleDefinition = ModuleDefinition.ReadModule("SimpleAssembly.dll");

var targetClass = moduleDefinition.Types.Where(t => t.FullName.Contains("ApiWrapper")).Single();

            var nestedMethodInstructions = targetClass.NestedTypes
                                                      .SelectMany(p => p.Methods)
                                                      .Where(m => m.HasBody)
                                                      .SelectMany(t => t.Body.Instructions).ToList();

            foreach (var instr in nestedMethodInstructions)
            {
                if (instr.Operand != null)
                {
                    var methodRef = instr.Operand as MethodReference;

                    if (methodRef != null && methodRef.FullName.Contains("CallApiAsync"))
                    {
                        // Get the full delegate parameter, ie  GetResponse(new SomeRequestType())
                    }
                }
            }





(PHP Reflection?) Create a new instance of a type hint given as parameter

Take a moment and look at these two simple classes:

use ValueObjects\Address;

class Person {

    private $address;

    public function setAddress(Address $address){
        $this->address = $address;
    }
}

class Address {
    private $line1 = "";
    private $line2 = "";
    private $city = "";
    private $state = "";
    private $zip = "";

    public function __construct($line1, $line2, $city, $state, $zip){
        $this->line1 = $line1;
        $this->line2 = $line2;
        $this->city = $city;
        $this->state = $state;
        $this->zip = $zip;
    }

    public function getLine1(){ ... }
    public function getLine2(){ ... }
    // ...
}

Here's what I'm trying to do:

// I have the class instance
$person = new Person();  

// I have the setter method name
$setter = "setAddress";  

// I have these parameters
$line1 = "123 Main St.";  
$line2 = "";
$city = "New York";
$state = "NY";
$zip = "10000";

// I only have the information you see above, how do I use that to set
// these values into $person? 
?????

I suppose I need to use some form of Reflection? (Also, I hear Reflection can have slow performance, so feel free to recommend any better performing approach if you know of one.)





Get instance of class from which was method called

i need to get instance of class from where was method called. If it is possible. Example:

class Class1{
String n = "1";
  Class1{
    new Class2.someMethod();
  }
}
class Class2{
  void someMethod(){
  //Class1 cl = (Get instance of Class1);
  //System.out.println(cl.n);
  }
}

So output will be "1"





Getting the type of the object inside List inside ItemsSource

I have a DataGrid that is given a List, which can be either of type Foo, Bar, or Baz. Later on, I need to extract that data to save it, and to do so I need to know the type of the object inside the List that was set as ItemsSource. I have tried to use GetType, didn't work, trying to do if(GridType is List<Foo>) for example produces the following warning:

The given expression is never of the provided ('System.Collections.Generic.List<Foo>') type

And I couldn't find anything on this error. Searched SO too, couldn't find anything. Is there a way to do what I am trying to do? Or even, a better way than simply getting the type directly?





How to use org.reflections to scan test-classes in Maven plugin (Mojo)

Disclaimer: I know it's possible to do this without the reflections library, but it seems that by using it I could focus on the core functionality of the plugin, not recursively loading and scanning classes for annotations and methods.

I'm in the process of creating a Maven Mojo that needs to access test classes of a maven project with multiple modules. I've successfully POC-ed this and I'm able to retrieve the URL's for all the target/test-classes folders using mavenProject.getTestClasspathElements(), using these URL's I am able to create a "custom" URLClassLoader, and I can manually load any class I name using that class loader.

No errors occur when I use the URL's from that class loader in my ConfigurationBuilder, but it does not find any of my test classes either.

List<ClassLoader> classLoadersList = new LinkedList<>();
classLoadersList.add(getMavenTestClassLoader());
Reflections reflections = new Reflections(new ConfigurationBuilder()
  .setScanners(new SubTypesScanner(false  /*don't exclude Object.class */), new ResourcesScanner())
  .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0])))
  .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("no.company"))));

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

The above setup worked fine when run in the context of a jUnit test using the following class loaders:

ClasspathHelper.contextClassLoader();
ClasspathHelper.staticClassLoader();

Does anyone have any ideas on why this doesn't work?





Setting Bean's properties with a loop

I have a class called Bean which has 3 fields

public class Bean {

private Object field0;
private Object field1;
private Object field2;

public Object getField0() {
    return field0;
}

public void setField0(Object field0) {
    this.field0 = field0;
}

public Object getField1() {
    return field1;
}

public void setField1(Object field1) {
    this.field1 = field1;
}

public Object getField2() {
    return field2;
}

public void setField2(Object field2) {
    this.field2 = field2;
}

I want to set each one of the fields with data to do so

    int j, i;

    for (j = 0; j < body.size(); j++) {
        line = new Bean();
        List row = body.get(j);

        HashMap map = new HashMap(headers.length);

        for (i = 0; i < headers.length; i++) {

            line.choosefield2(i, headers, row);
        }
        list.add(line);
    }

and choosefield2 is in the bean:

public void choosefield2(int i, String[] headers, List row) {

    switch (i) {

    case 0:
        this.setField0(row.get(0));
        break;

    case 1:
        this.setField1(row.get(1));
        break;

    case 2:
        this.setField2(row.get(2));
        break;

Can I do this in a for cycle instead of doing a case switch? I have way more than 3 fields so it's not really practical. I heard reflections might be an option. I wanted something like

for (i = 0; i < headers.length; i++) {
        line.setField[i]=row.get(i);
        }
        list.add(line);
    }

is this possible? Using JDK 1.6





ASP.NET: CreateDomain(...).CreateInstanceAndUnwrap(...) OR Assembly.LoadFrom( ... ).GetExportedTypes() throws FileNotFoundException

Intro

I am trying to load some assemblies and get the types out of them... Paths of the assemblies are

bin/Plugin1

I am also trying to create an app domain for them and load them there. Basic steps are:

1. Create a domain:

domain = AppDomain.CreateDomain( "Plugins" )

2. Create a worker

worker = (Scan)domain.CreateInstanceAndUnwrap(
                           Assembly.GetExecutingAssembly().FullName, typeof(Scan ).FullName );

3. Load assemblies

worker.Scan( [PATH_TO_DLL] )

4. Load Types

 Assembly.LoadFrom( [PATH_TO_DLL] ).GetExportedTypes()

I tried anything i could think of, but i always get a FileNotFoundException somewhere in steps 2 or 4..

What I tried

1. ApplicationBase path:

AppDomain.CurrentDomain.SetData( "APPBASE", "C:\\...\\Project\\bin\\Plugin1" );
AppDomain.CreateDomain("Plugins").CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, ... );

Throws FileNotFoundException

2. new domain with AppDomainSetup

AppDomain.CurrentDomain.SetData( "APPBASE", "C:\\...\\Project\\bin\\Plugin1" );
AppDomain.CreateDomain( "Plugins", null, AppDomain.CurrentDomain.SetupInformation).CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, ... );

Throws FileNotFoundException

3. Used CreateInstanceFromAndUnwrap

var assembly = Path.Combine( AppDomain.CurrentDomain.BaseDirectory, "Plugin1", Path.GetFileName( Assembly.GetExecutingAssembly().Location ) );
AppDomain....CreateInstanceFromAndUnwrap(assembly, ... );

Worked but...

4. Used Assembly.LoadFrom

var asm = Assembly.LoadFrom( [PATH_TO_ASSEMBLY] );//works
var types = asm.GetExportedTypes();

Throws FileNotFoundException

5. Web.Config probing

<probing privatePath="bin;bin/Plugin1;" />

Didn't helped anywhere...

That led me to believe that forcing to load an assembly from a path while not fixing the actual problem (assemblies seems to be loaded to iis paths) is not fixing anything, i am not on the right path towards solution...

Exceptions I got

1. Exception From CreateInstance

System.IO.FileNotFoundException was unhandled by user code
  HResult=-2147024894
  Message=Could not load file or assembly 'Plugin.Libs.Base, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
  Source=mscorlib
  FileName=Plugin.Libs.Base, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
  FusionLog== == Pre-bind state information == =
LOG: DisplayName = Plugin.Libs.Base, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
 (Fully-specified)
LOG: Appbase = file:///C:/.../Web/PluginWeb.heTest/PluginWeb.heTest/PluginWeb.heTest/bin/Plugin/
LOG: Initial PrivatePath = C:\...\Web\PluginWeb.heTest\PluginWeb.heTest\PluginWeb.heTest\bin
Calling assembly : (Unknown).
== =
LOG: This bind starts in default load context.
LOG: Configuration file C:\...\Web\PluginWeb.heTest\PluginWeb.heTest\PluginWeb.heTest\bin\Plugin\web.config does not exist.
LOG: No application configuration file found.
LOG: Using host configuration file: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary ASP.NET Files/root/993f86a2/2dca2916/Plugin.Libs.Base.DLL.
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary ASP.NET Files/root/993f86a2/2dca2916/http://ift.tt/1IaPDNw.
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary ASP.NET Files/root/993f86a2/2dca2916/Plugin.Libs.Base.EXE.
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary ASP.NET Files/root/993f86a2/2dca2916/http://ift.tt/1DcTi0c.
StackTrace:
       at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
       at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
       at System.Activator.CreateInstance(String assemblyString, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo, StackCrawlMark& stackMark)
       at System.Activator.CreateInstance(String assemblyName, String typeName)
       at System.AppDomain.CreateInstance(String assemblyName, String typeName)
       at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName)
       at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName)
       at Plugin.Libs.Base.Schema.mySchemaManager.<>c__DisplayClass6.<Scan>b__3() in c:\...\Plugin.Libs.Base\Plugin.Libs.Base\Schema\Manager.cs:line 202
       at Plugin.Libs.Base.mySys.WriteLog(poSysLogScale scale, Action method, String message, Object[] args) in c:\...\Plugin.Libs.Base\Plugin.Libs.Base\Sys.cs:line 514
       at Plugin.Libs.Base.Schema.mySchemaManager.Scan(Action'1 processView) in c:\...\Plugin.Libs.Base\Plugin.Libs.Base\Schema\Manager.cs:line 184
       at Plugin.Libs.Base.Schema.mySchemaManager.<>c__DisplayClass1.<Load>b__0() in c:\...\Plugin.Libs.Base\Plugin.Libs.Base\Schema\Manager.cs:line 176
       at Plugin.Libs.Base.mySys.WriteLog(poSysLogScale scale, Action method, String message, Object[] args) in c:\...\Plugin.Libs.Base\Plugin.Libs.Base\Sys.cs:line 514
       at Plugin.Libs.Base.Schema.mySchemaManager.Load(Action'1 processView) in c:\...\Plugin.Libs.Base\Plugin.Libs.Base\Schema\Manager.cs:line 175
       at Plugin.Libs.Base.myApplication.Load(Action'1 processView) in c:\...\Plugin.Libs.Base\Plugin.Libs.Base\Application.cs:line 141
       at Plugin.Web.Forms.Fakes.FakeAppContext.Get(String aliasFileName, String userName, String password) in c:\...\PluginWeb.heTest\PluginWeb.heTest\Plugin.Web.Forms\Fakes\AppContext.cs:line 25
       at Plugin.Web.Forms.Controllers.BaseController..ctor() in c:\...\PluginWeb.heTest\PluginWeb.heTest\Plugin.Web.Forms\Controllers\BaseController.cs:line 30
       at PluginWeb.heTest.Classes.BaseController..ctor()
       at PluginWeb.heTest.Controllers.HomeController..ctor()
  InnerException:

2. Exception from .GetExportedTypes()

System.IO.FileNotFoundException was caught
  HResult=-2147024894
  Message=Could not load file or assembly 'PluginChild.Libs.Base, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
  Source=mscorlib
  FileName=PluginChild.Libs.Base, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
  FusionLog== == Pre-bind state information == =
LOG: DisplayName = PluginChild.Libs.Base, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
 (Fully-specified)
LOG: Appbase = file:///c:/windows/system32/inetsrv/
LOG: Initial PrivatePath = NULL
Calling assembly : PluginChild.Obj.MGM.DataObjects, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
== =
LOG: This bind starts in LoadFrom load context.
WRN: Native image will not be probed in LoadFrom context. Native image will only be probed in default load context, like with Assembly.Load().
LOG: No application configuration file found.
LOG: Using host configuration file: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///c:/windows/system32/inetsrv/PluginChild.Libs.Base.DLL.
LOG: Attempting download of new URL file:///c:/windows/system32/inetsrv/PluginChild.Libs.Base/PluginChild.Libs.Base.DLL.
LOG: Attempting download of new URL file:///c:/windows/system32/inetsrv/PluginChild.Libs.Base.EXE.
LOG: Attempting download of new URL file:///c:/windows/system32/inetsrv/PluginChild.Libs.Base/PluginChild.Libs.Base.EXE.
LOG: Attempting download of new URL file:///C:/.../PluginWeb.heTest/PluginWeb.heTest/bin/Apps/Obj/PluginChild.Libs.Base.DLL.
LOG: Attempting download of new URL file:///C:/.../PluginWeb.heTest/PluginWeb.heTest/bin/Apps/Obj/PluginChild.Libs.Base/PluginChild.Libs.Base.DLL.
LOG: Attempting download of new URL file:///C:/.../PluginWeb.heTest/PluginWeb.heTest/bin/Apps/Obj/PluginChild.Libs.Base.EXE.
LOG: Attempting download of new URL file:///C:/.../PluginWeb.heTest/PluginWeb.heTest/bin/Apps/Obj/PluginChild.Libs.Base/PluginChild.Libs.Base.EXE.

  StackTrace:
       at System.Reflection.RuntimeAssembly.GetExportedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes)
       at System.Reflection.RuntimeAssembly.GetExportedTypes()
       at Plugin.Libs.Base.Schema.SchemaManager.MarsalScan.ScanAssembly(ScanResult res, String item) in c:\...\Plugin.Libs.Base\Plugin.Libs.Base\Schema\Manager.cs:line 81
  InnerException: 

Any help will be really appreciated!





Is it possible to call last called method in java?

So I have bunch of classes with there methods.classes don't have common parent.Is it possible for me to find out last called method(along with its parameter)





Loop through all the properties of an entity object and get the corresponding value?

I'm using Entity framework 6 DBContext , Database First.

Let's say that I have an object , myobj1 from one of entity.

Is there any way to loop through all the properties of this object and to get current value of each of them ?

Of course I need a general code that should work for any object from any entity.





Infering the type of the arguments in method for aspectj

In AOP(using Aspectj) to intercept a method call and acess its parameters we can use

Object[] args=joinPoint.getArgs();

But does the JoinPoint class gives us any feature to infer the type of the parameters? For instance:

public void setApples(List<Apple>){..}

All I get is an Object instance. Is there some way to infer the type of that parameter using the joinpoint properties or reflection or Guava TypeToken?





Java 8 : Invoke Interface's static method using reflection

I want to invoke static method of Java 8 interface using reflection API.

public interface TimeClient {
    static void testStatic() {
        System.out.println("In the Static");
    }
}

I am able to invoke default method of Interface but unable to invoke static method.





Setting Property using only string name

Is there a way I can set a property by identifying it using a string?

For example, I have a Visibility property that looks something like this:

public Visibility ModifyFilesIconVisibility
        {
            get { return modifyFilesIconVisibility; }
            set
            {
                SetProperty(ref modifyFilesIconVisibility, value, () => modifyFilesIconVisibility);
            }
        }

which is bound to an icon in XAML. Since each icon's visibility is set during runtime based on user authority to access each APIs, I have a Dictionary mapping:

public static Dictionary<string, List<string>> Views = new Dictionary<string, List<string>> {
                        {
    "ModifyFiles", 
            new List<string>{"/editFile", "/deleteFile", "/cutFile", "/copyFile"}
        }, 
                        {
    "CRUDLogs", 
            new List<string>{"/writeLog", "/deleteLog", "/viewLog", "/searchLog"}
        },       
                        };    

and if any of the APIs in the List is available in the authority (which I receive from an external API as well), I will modify the visibility of each icon. So for example, if /editFile is available to the user, the ModifyFilesIconVisibility will be set:

foreach (string api in APIMappings.Views["ModifyFiles"])
{
  if (URLs.Contains(api)) 
  {
   this.ModifyFilesIconVisibility = Visibility.Visible;
   break;
  }
}

Otherwise they are left as Visibility.Collapsed.

Since this is tedious, I was wondering if I can somehow use the name of the property itself in the mapping

public static Dictionary<string, List<string>> Views = new Dictionary<string, List<string>> {
                        {
    "ModifyFilesIconVisibility", 
            new List<string>{"/editFile", "/deleteFile", "/cutFile", "/copyFile"}
        }, 
                        {
    "CRUDLogsIconVisibility", 
            new List<string>{"/writeLog", "/deleteLog", "/viewLog", "/searchLog"}
        },       
                        };    

or something like that, and then use the Dictionary key to set it to visible using reflection or anything else. Is this possible?





mercredi 29 juillet 2015

Find all packages in the project

I'm trying to know the packages I created in my project, and then goes deeply throw each package to know the classes.

Thus, is there a way to do that?





Implementing Interface using Reflection c#

I have a requirement where i need to implement an interface in my project which is present in a third part dll.This dll i am loading using reflection Is it Possible?

class MyClass : I3rdPartyInterface

{ //implementing interface

}

Here the I3rdPartyInterface is the interface present in my 3rd Party dll.





Dynamically call a function in Swift

I’m trying to implement a router pattern in Swift and can’t figure out how to dynamically call a method.

For example, there’s an array of arguments:

let arguments: [Any] = [100, 0.5, "Test"]

And a handler which needs to be called:

public class MyClass {
    public func handler(value1: Int, value2: Double, text: String) {
        print("int=\(value1), double=\(value2), string=\(text)")
    }
}
let myClass = MyClass()

The router has an untyped function reference which it will use as a callback:

let callback: Any = myClass.handler

How do I map the arguments from the array above to the function parameters?

I’ve found that handler’s argument types can be obtained via reflection:

reflect(myClass.handler).valueType
is
(Swift.Int, Swift.Double, Swift.String) -> ()

I don’t know how to iterate argument types though or even get their count. Probably I can parse this as a string then use NSInvocation to call the method. As NSInvocation is not available in Swift, this will require using an Objective C helper function. Another downside is that it won’t work with global functions and closures.

Any other ideas are very welcome.





Comparing two objects and setting them equal without breaking entity reference

So, here's one you may have done thought experiments with but never tried. Back Story: We are using entity framework with a repository that utilizes a few generic classes. We have our entity table classes and model classes that are very similar to the table classes. I had always done each table object individually until a co-worker started a project and used the navigation properties. Naturally he wondered why he couldn't update his objects. The short is that the navigation properties were being directly set to the model's properties and therefore the link was being broken. It MAY be beneficial to have one generic class to run the comparison as we have 14 tables in this project alone... Here is my second attempt (which took over 6 hours) to remedy the situation:

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

namespace Domain
{
public static class Compare2
{
    /// <summary>
    /// Takes two objects and without breaking the reference sets the second     object equal to the first, including lists within that object.
    /// It does this using reflection and an attribute called PKey which is placed on the property that is the identity.
    /// I don't think that it will propperly pull the properties from the objects in the lists because it sees them as objects. 
    /// It will likely be slow because it uses reflection.
    /// </summary>
    /// <typeparam name="Model">The type of the modified object</typeparam>
    /// <typeparam name="Table">The type of the object to be modified</typeparam>
    /// <param name="model">The modified object</param>
    /// <param name="table">The object to be modified</param>
    public static void obj2obj<Model, Table>(Model model, ref Table table)
    {
        var m = model.GetType();
        var t = table.GetType();
        var propList = m.GetProperties().AsEnumerable().ToList();
        foreach (var prop in propList)
        {
            //if property exists in both
            if (t.GetProperty(prop.Name) != null)
            {
                //if this property isn't a collection
                if (!typeof(ICollection<>).IsAssignableFrom(prop.GetType()))//.GetGenericTypeDefinition()))
                {

                    //if it's not a seperate object
                    if (!t.GetProperty(prop.Name).GetType().IsValueType && t.GetProperty(prop.Name).GetType() != typeof(string))
                    {
                        //set the corresponding property in the table version to the value of that in the model
                        t.GetProperty(prop.Name).SetValue(table, m.GetProperty(prop.Name).GetValue(model, null));
                    }
                    else //if it IS another object
                    {
                        //send it off (won't work because we're breaking the reference)
                        object o2 = t.GetProperty(prop.Name).GetValue(table);
                        obj2obj<object, object>(m.GetProperty(prop.Name).GetValue(model), ref o2);
                    }
                }
                else //if it IS a collection
                {
                    //for every object in the collection
                    foreach (var o in (System.Collections.Generic.IEnumerable<object>)m.GetProperty(prop.Name).GetValue(model, null))
                    {
                        //match up objects with the same Primary keys and send them off to be compared 
                        //(won't work because we're breaking the reference)
                        object o2 = ((List<object>)t.GetProperty(prop.Name).GetValue(table, null))
                            .Where(i => i.GetType().GetProperties().Where(pi => Attribute.IsDefined(pi, typeof(AuthSVC.Data.PKey))).First().GetValue(i)
                                == o.GetType().GetProperties().Where(pi => Attribute.IsDefined(pi, typeof(AuthSVC.Data.PKey))).First().GetValue(o)).First();
                        //i would like to have a catch to simply add new objects... this doesn't account for that
                        obj2obj<object, object>(o, ref o2);
                    }
                }
            }
        }
    }
}
}

I'm sure you can see my dilemma. I can't pass properties by ref and getting their values as objects is breaking my reference to entity... 1. Is there an easy (built-in) way to do this? 2. If not, should I try for an overloaded version which accepts the get and set functions as delegates?





How to get buildnumber / revision from Assembly? (4th digit)

Our build process updates the forth digit (buildnumber or revision) of the version number on every build.

enter image description here

I'm using the following code to try and get the version so that it can be displayed on the splash screen and about page.

var version = Assembly.GetEntryAssembly().GetName().Version;
var programName = "Version: " + version;

How come the 4th digit in the version number is always zero, and what can I change to get it to property reflect the build number?

enter image description here





Hold a type in a Golang struct field

I'm looking for a way to hold a type (maybe reflection.Type?) as a field in a custom struct. The reasoning behind this is that I'm decoding JSON arrays into structs from which I later build SQL queries, but ints, floats and timestamps are identical in the JSON array, though they are different when querrying a database. This means I need to convert each value to its correct type before querrying. I think the answer lies somewhere in the reflect package, but I haven't worked out exactly how to utilize it. What I'm hoping for is something like this:

type Column struct {
    name string
    dataType type
}
someColumn := Column {name: "somecol", dataType: int}
convertedVal := SomeConversionFunc("5", someColumn.dataType)

Alternatively, this sort of thing could work as well:

type Column struct {
    name string
    dataType func()
}
someColumn := Column {name: "somecol", dataType: ConvertToInt}
convertedVal := someColumn.dataType("5")

Any ideas?





Python reflection and function decorator

If I have a reference to a decorated function, can I inspect its decorator? I want to get the name of the decorator and possibly the list of its arguments.





WPF change another application textbox

I am looking at some application with snoop.

I can see the text of some textbox, I also can edit it.

Now I want to do the same thing but programmatically. I want to write some text in this textbox programmatically. (Text box from another application)

I think this is possible because snoop can do it (May be using reflection in some way)

What is the best way to do this? Thank you,





How to extract the type argument from a Java bean property?

I have an arbitrary Java bean like the following:

class SomeBean {

    public Map<String, SomeOtherBean> getOtherBeans() { ... }
    public void setOtherBeans(Map<String, SomeOtherBean> otherBeans) { ... }

}

and I would like to extract the type SomeOtherBean with a generic method. In the presence of Java's type erasure, is this even possible?





Error using Reflection "Class.forName" in Eclipse

I am trying to compile a reflection example with the help of a sample taken from book in Eclipse IDE:

public class Reflection_Test {

    public static void main(String[] args) {

        // In both cases below, "ClassNotFoundException" occurs
        Class c1 = Class.forName("java.util.Date");
        Class c2 = Class.forName("Foo");
    }

}

class Foo {
    // ...
}

I copied the line exactly but this is raising two exceptions. I googled other questions and they suggested to use a correct package name. But in my case I am compiling it under default package. What is it missing?





getMethods Reflection API result is ambiguous with Interface

Please have a look on the scenario and suggest how can I remove the following issue.

  1. We have an interface BaseRepository which is already build in having a method commitData(), retrieveData(), sortByLength().

     public interface BaseRepository{
           public void commitData();
           public Object retrieveData();
           public Object sortByLength();
        }
    
  2. Interface FileRepository which extends BaseRepository having methods commitData(), fileNames() i.e.

    public interface FileRepository extends BaseRepository{
                public void commitData();
                public List fileNames();
            }
    
  3. Interface ObjectRepository which extends both BaseRepository and FileRepository with no methods in it.

  4. Using Java Reflection API I try to get the methods define in the Interfaces for further processing, but getting method commitData 2 times i.e. following piece of code will give me 2 time commitData in the console

    for(Method method : ObjectRepository.class.getMethods()){
                System.out.println(method.getName());
            }
    

output is:

commitData retrieveData sortByLength commitData fileNames

I am using Java 1.6.





Android: how to parameterize which resource to use at runtime?

Think about a list of parameters and their respective intervals of discrete integer values:

a[1-N], b[1-M], c[1-K], d[1-J]

a, b, c, d are the variables while between square brackets there are intervals of their possible values.

At runtime if they are

a=1, b=2, c=3, d=5 

then I'd like to get the resource with

name = R.string.string_1_2_3_5

Is it possible? I wouldn't want to make a series of cascade switches for each variable to finally pick a resource. I know this could work but is there another way?





Get DLL's file name of inherited class

I have an abstract class compiled into a DLL (let's call it BaseClass.dll) which serves as a base for other classes to inherit from. These other classes are also compiled into DLL's (let's call one of them InheritedClass.dll) which can be used as plugins for my main application which can call the same methods in each plugin as the abstract class forces them to implement.

However, there's some functionality which will be common to all the plugins and so I would prefer if I could implement those in the base class. This cuts down on redundancy and also eliminates the possibility of whoever writes the plugin to make mistakes when implementing that functionality.

One such example is a piece of code that requires the name of the compiled DLL file. A method that would've worked could look like this:

public string GetName()
{
    return System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
}

The problem is that GetExecutingAssembly() returns the assembly for the code that is currently running, not the assembly into which it has been compiled. So, if I put the above function in BaseClass, it returns (BaseClass.cs), regardless of the name of the DLL that it is compiled into. This means that I have to put it in InheritedClass and can't put it in BaseClass. As explained above, I'd like to avoid that as I don't want to labour the developer of the plugins with this bit of common code and I don't want to rely on these third party developers to get it right.

Is this even possible? Is there a way I can get the name of the DLL which inherited from this base class through code that sits in the base class?





Swift reflection returning 0 on UITableViewCell

I have written a Binding Framework for automated binding between View and ViewModel based on name convention.

First I'm getting all the properties of the View and ViewModel by reflection:

  class func bind<T : IBoundableView , E : IBoundableViewModel>(view : T, viewModel : E) {
        var viewPropertyNameForValue = getPropertyValueForName(view)
        var viewModelPropertyNameForValue = getPropertyValueForName(viewModel)
        bindViewPropertiesToViewModel(viewPropertyNameForValue, viewModelPropertiesValueForName: viewModelPropertyNameForValue)
        viewModel.setBondableView(view)
    }


class func getPropertyValueForName<T>(viewModel : T)-> [String : Any] {

    let obj = viewModel
    let reflected = reflect(obj)
    var properties = [String : Any]()
    for index in 0..<reflected.count {
        properties[reflect(viewModel)[index].0] = reflected[index].1.value
    }
    return properties
}

Is works great on NSObject objects, and UIViewControllers, but when using UITableViewCell "getPropertyValueForName" returns 0.

So basically I'm looking for a way to use Reflection on UITableViewCell





Can we do reflection on debugee from debugger in .Net

I want to get the native(x86) code of a debugee function from the debugger using ICorDebug APIs. After getting an ICorDebugFunction, I can call GetNativeCode on it but it returns the native code only if it has been Jited. So I need to forcefully JIt it. The RuntimeHelpers.PrepareMethod can do that but it needs a methodhandle( not a method token).From the debugger I have the Method Token but not the method handle. So can we get the real MethodInfo object(which can get me the handle) of a debugee function from the debugger? In other words, is it possible to do reflection on debugee from debugger? Thanks again in advance....





mardi 28 juillet 2015

avoid stackoverflow exceptions when populating relations

I'm building a library that populates an entity with random values to be used on tests, but when I try populate an relation like the following, I see StackOverflowException

Author

@Entity
public class Author implements Serializable {

private static final long serialVersionUID = 1L;

@Id
private Long id;

private String name;

@OneToMany
private List<Book> books = new ArrayList<Book>();

and Book

@Entity
public class Book implements Serializable {


@ManyToOne
private Author author;

this is the code that populates the relations

public <T> T fakeIt(Class<T> clazz) throws FakerException {
if(clazz.getAnnotation(Entity.class) == null){
    throw new FakerException("The class "+ clazz.getName()+ "is not an entity");
}
try {
    T faked  = clazz.newInstance();
    for(Field f : clazz.getDeclaredFields()){
    if(f.getName().equals("serialVersionUID"))
        continue;

    System.out.println("Genearting value for "+f.getName() + " on " + f.getDeclaringClass());

    f.setAccessible(true);
    f.set(faked, getValueForField(f));
    }
    return faked;
} catch(Exception e){
    throw new FakerException(e);
}
}

private Object getValueForField(Field f) throws Exception {
if(f.isAnnotationPresent(UseGenerator.class)){
    Generator<?> gen = (Generator<?>) f.getAnnotation(UseGenerator.class).generator().newInstance();
    return gen.genearte();

} else if(f.isAnnotationPresent(ManyToOne.class)){
    return fakeIt(f.getType());

} else if(f.isAnnotationPresent(OneToMany.class)){
    Class<?> toFake = extractTypeFromList(f);

    List<Object> fakedObjects = new ArrayList<Object>();
    for(int i = 0; i < 6; i++){
    fakedObjects.add(fakeIt(toFake));
    }

    return fakedObjects;
}
// Other types
String clazzType = f.getType().getSimpleName();
Generator<?> generator = defaultGenerators.get(clazzType.toLowerCase());

if(generator != null)
    return generator.genearte();

return null;
}

private Class<?> extractTypeFromList(Field f) {
ParameterizedType parameterizedType = (ParameterizedType) f.getGenericType();
Class<?> type = (Class<?>) parameterizedType.getActualTypeArguments()[0];

return type;
}

in this case, fakeIt is the function that generate random values based on the Field type of the class. at that point, when I'm populating author, it tries to populate the books which has a relation to author that has books that...you got it.. stackoverflow exception. what is the best way to avoid this?





Reflect: setting a field of a pointer

I'm trying to do something like this:

Define structs with tags named env:

type Env struct {
     Port string `env:"PORT"`
}

Call some function which will get the environment variable names using os.Getenv and put set it in the struct.

Right now, I have this: http://ift.tt/1MTVytx

But, as you can see, I have to pass both the reference and the pointer to my function.

While this works, it is very ugly (at least I think it is).

If I try to pass the pointer only, I can't get the type right (because it will be an *interface{}) and, if I pass only the reference, I can't set the values using reflect (even if I could, it would not work).

Is there a sane way of doing this?





Map an object to a KeyValuePair

I want to take one object and using reflection, map the class properties to a KeyValuePair of string, string. But it is not that simple, because the class has some subclasses, and the subclass could have a subclass too..

My idea is end with a List of KeyValuePair that map the object with the subclasses.

Something like this: List{ KeyValuePair -> (ObjectThing.FirstPropName, "4"), KeyValuePair -> (ObjectThing.SecondPropName, "lol"), KeyValuePair -> (ObjectThing.FirstPropName.FirstSubPropertyName, "3"), KeyValuePair -> (ObjectThing.FirstPropName.SecondSubPropName, "10") }





Getting type from class

I've been working on a project that stores case classes in a database and can take them back out again, storing them works fine but I am having trouble with getting them back out.

For items like Strings, Ints, Floats, etc, are being stored as they are but other types are converted to a JSON string using json4s like so

  private def convertToString(obj: AnyRef, objType: Class[_]): String = {
    implicit val formats = Serialization.formats(NoTypeHints)

    objType match {
      case t if t == classOf[String]      => obj.asInstanceOf[String]
      case t if t == classOf[Int]         => obj.toString
      case t if t == classOf[Integer]     => obj.toString
      case t if t == classOf[Boolean]     => if (obj.asInstanceOf[Boolean]) "true" else "false"
      case t if t == classOf[Short]       => obj.toString
      case t if t == classOf[Double]      => obj.toString
      case t if t == classOf[Long]        => obj.toString
      case t if t == classOf[Float]       => obj.toString
      case t if t == classOf[Byte]        => obj.toString
      case _                              => write(obj)(formats)
    }
  }

This is working fine and store items just like I would expect it to, but the problem is converting the items back from JSON.

Lets say I have the case class Test(testInt: Int, testString: String, testMap: Map[String, _]) and I get the data back as 3,'blablabla','{"Test": "Map"}'

I can put all values into a new instance of the class expect for the map, here is the code I am using

private def restoreTypes(objClass: Class[_], argList: Array[Object]): Array[_ <: Object] = {
    var correctTypes = Array.empty[Object]
    val fields = objClass.getDeclaredFields

    for(i <- 0 until fields.length) {
      val giveType = argList(i).getClass
      val wantedType = fields(i).getType

      if(giveType != wantedType && giveType == classOf[String])
        read[/*HERE*/](argList(i).asInstanceOf[String])
      else
        correctTypes = correctTypes :+ argList(i)
    }

    correctTypes
}

And this method is called list so

objClass.getConstructors()(0).newInstance(restoreTypes(objClass, args): _*)

I am getting stuck on how to pass the wanted type to the read method





When to use generics and type checking?

Assume A through Z to be 26 classes I defined. In the following example:

  private List<A> _listA;
  private List<B> _listB;
  // private List<C>, and so on, through...
  private List<Z> _listZ;

  private void setLabelA()
  {
      LabelA.Text = _listA.Count;
  }

  // private void setLabelB() exists
  // and so does setLabelC()
  // and so on, all the way through to...

  private void setLabelZ()
  {
      LabelA.Text = _listZ.Count;
  }

It seems to me that there is no way to shorten this other than the following:

  private void setLabel<genericType>(List<genericType> list)
  {
      if(list is List<A>)      LabelA.Text = _listA.Count;
      else if(list is List<B>) LabelB.Text = _listB.Count;
      else if(list is List<C>) LabelC.Text = _listC.Count;
      //  and so on...
      else if(list is List<Z>) LabelZ.Text = _listZ.Count;
  }

Overloading the function name doesn't reduce the number of lines of code:

  private void setLabel(List<A> list)
  {
      LabelA.Text = _listA.Count;
  }

  private void setLabel(List<B> list)
  {
      LabelB.Text = _listB.Count;
  }

I prefer to use the is operator to determine which Label to set, because it preserves space (in this scenario, 50 lines of meaningless brackets and 25 lines of slightly-different function names). However, a Stack Overflow user recommended that I not use generics, and instead use separate functions, one for each Label. Although this solution will work, I prefer to not do so.

Is there any benefit towards NOT using the is operator, and towards explicitly typing my functions?





What does it mean to resolve a type in Java?

What does it mean to resolve a type in Java?

Here are some usage examples with my attempts at making sense of them:

From Field#getGenericType():

If the type of the underlying field is a type variable or a parameterized type, it is created. Otherwise, it is resolved.

  • Type variables or parameterized types need to be created for this form of reflection to work because they can't be loaded, because they don't really "exist" at runtime?
  • So if something exists at runtime, it can be "resolved"? By the classloader?

From TypeToken#resolveType():

Resolves the given type against the type context represented by this type. For example:

new TypeToken<List<String>>() {}.resolveType(
    List.class.getMethod("get", int.class).getGenericReturnType())
=> String.class

  • This I don't really get at all. Not sure what this code is doing.




Reflection and Generics in C#

If I want to find the type of a parameter using the is keyword (like in this example):

private bool DoSomething<T>(HashSet<T> set)
{
    if(set is HashSet<int>) addSomeIntsTo(set);
    else if(set is HashSet<double>) addSomeDubsTo(set);

    return elementsAddToFortyTwo(set);
}

private bool elementsAddToFortyTwo<T>(HashSet<T> set)
{
    if(set is HashSet<int>) // return (sum of each number == 42);
    else if(set is HashSet<double>) // return (sum of each number == 42);
    else throw new Exception("you didn't add this type to the function");
}

...then the is keyword will return true if a strongly-typed parameter is passed in, like with:

  HashSet<int> hashset = new HashSet<int>();
  elementsAddToFortyTwo(hashset); // returns true

...but returns false if you're using a reflected type.

  HashSet<int> hashset = new HashSet<int>();
  DoSomething(hashset); // throws new Exception(), because of elementsAddToFrtyTwo(hashset)

Why is this? And, how do I make elementsAddToFortyTwo() return true when invoked in DoSomething()?





Is incorrect this use of Reflection

I have various methods to validate an object. For now i run the validation like this:

boolean error = false;
if(!methodOneValidade(myObject)) error = true;
if(!methodTwoValidade(myObject)) error = true;
if(!methodTreeValidade(myObject)) error = true;
.
.
.
if(!method23Validade(myObject)) error = true;
return error;

Instead, if i annotate the methods with an specific annotation (@MyRule e.g.) and execute them using reflection, is it a good practice? For me will be smart and practical, but is it acceptable way use of reflection in java?





What is the purpose of MethodInfo.MetadataToken

What is the token normally used for? More importantly, if I have a MetadataToken, can I get back the MethodInfo object?





how to read method body and identify expressions in c# reflection?

I want to know if is possible to get the method body via c# reflection and identify expressions, conditions, loops etc.

For example, assume I have a class,

class Employee
{
private int Number1{get;set;}
private int Number2{get;set;}

public int GetNumber()
{
  if(Number1>0)
  {
     return Number1;
  }
  else if(Number2>0)
  {
     return Number2;
  }
  return Number1 + Number2;
  }
}

So here if you see the above class is having a method with some conditions. In reflection I want to read the method body and identify these conditions. Like,

var methodBody = methodInfo.GetMethodBody();
methodBody.Condition?????





Design Approach and Using Reflection to run methods in Java

I have a question. I have multiple classes in a package: Let's say package is

com.myPackage.first

And this package has the following classes:

firstGood
secondGood
thirdBad
fourthGood

Each of these classes have a method with the same name but different implementation. So say each have a one particular function called:

public void runMe(){

}

For now I want to come up with a way to given a class name, it'll go inside the class and run that particular method.

So conceptually, my method will look like those:

ArrayList<Class> classList ; // where classList is a list of classes I want to run 

public void execute(){
for(Class c : classList){
// Go inside that class, (maybe create an intance of that class) and run     the method called run me
 }

}

or

public void execute(Class c, String methodToRun){
for(Class c : classList){
// Go inside that class, (maybe create an intance of that class) and    run     the method called run me
 }
}

For now. what I have been able to do is get the name of the classes I want to run the

runMe() 

method. So I have been able to come with a way to get the arraylist of classes I want to run. So what I need help with is coming up with a method such that it takes a class name and run the method I want it to. Any help is appreciated. Thanks





I have this helper method that is designed to transfer collection items from one collection object instance to another. It works, but I have recently ran into an issue where a particular collection implements at different points IEnumerable. At one level as IEnumerable> and at another IEnumerable. In my code below, the declaration of secondaryCollection causes it to use the IEnumerable instance type versus the collectionType declaration finds it as the base ICollection> type so that I can invoke the Add() and Remove(). With this type mismatch though the Add() and Remove() method invocations fail. I think if I can figure out how to declare secondaryCollection as type IEnumerable where 'object' is of type KeyValuePair and not of just the type TValue that this should work without the type mismatch exception (it's actually an argument exception for the Add(), Remove() methods). The problem is this is all done in reflection and the types are unknown. How can I do this?

Here's the current method code:

public void MergeCollection(FieldInfo primaryMember, object primaryObject, FieldInfo secondaryMember, object secondaryObject)
    {
        if (primaryMember == null)
            throw new ArgumentNullException("primaryMember");

        if (primaryObject == null)
            throw new ArgumentNullException("primaryObject");

        if (secondaryMember == null)
            throw new ArgumentNullException("secondaryMember");

        if (secondaryObject == null)
            throw new ArgumentNullException("secondaryObject");

        //Get the collection type and validate
        Type genericType = typeof(ICollection<>);

        Type collectionType = primaryMember.FieldType.GetBaseTypes().FirstOrDefault(t => t.IsGenericType && t.GetGenericArguments().Length == 1 && t == genericType.MakeGenericType(t.GetGenericArguments()));

        if (!collectionType.IsAssignableFrom(secondaryMember.FieldType))
            throw new InvalidOperationException("Primary and secondary collection types do not match.");

        Type collectionParamType = collectionType.GetGenericArguments()[0];


        //Get the collection invocable methods
        MethodInfo add = collectionType.GetMethod("Add", new Type[] { collectionParamType });
        MethodInfo remove = collectionType.GetMethod("Remove", new Type[] { collectionParamType });

        //Declare the collections
        object primaryCollectionObject = primaryMember.GetValue(primaryObject);
        object secondaryCollectionObject = secondaryMember.GetValue(secondaryObject);

        Type genericEnumerableType = typeof(IEnumerable<>);
        Type enumerableType = primaryMember.FieldType.GetBaseTypes().FirstOrDefault(t => t.IsGenericType && t.GetGenericArguments().Length == 1 && t == genericEnumerableType.MakeGenericType(t.GetGenericArguments()));

        IEnumerable<object> secondaryCollection = ((IEnumerable)secondaryCollectionObject).Cast<object>();

        //Transfer the items
        int noItems = secondaryCollection.Count();
        // int noItems = (int)count.GetValue(secondaryCollectionObject);
        for (int i = 0; i < noItems; i++)
        {
            try
            {
                add.Invoke(primaryCollectionObject, new object[] { secondaryCollection.ElementAt(0) });
                remove.Invoke(secondaryCollectionObject, new object[] { secondaryCollection.ElementAt(0) });
            }
            catch (ArgumentException ex)
            {
                //The argument exception can be captured here
            }
        }
    }





Get MethodInfo object from token, or get Type object from token

I am trying to use the debugger APIs(ICorDebug etc ) to debug a .net application. The IMetadataImport always returns a token for anything. Be it a Type or a Method. But I want to do reflection on those items. So I need to get the Type object or the MethodInfo object from those tokens. Is there any way I can do this.

Also is there any way I can acquire the Type objects in a debugee other than how I am doing currently? Here is how I am doing currently. from the ICorDebugManagedCallback.LoadModule callback, I get the ICorDebugModule object and call GetMetaDataInterface to get the IMetadataImport object. But everything inside IMetadataImport deals with tokens. Is there any other way I can get Type and MethodInfo objects on the debugee.





.Net arbitratry runtime class instantion and method calling

I am looking for a way to do arbitrary class instantion as well as attribute assignement and possibly method calling in .Net and preferrably C#. Since arbitrary is too broad a word let me tell you what I am after.

Let's say I have a DLL (objects.dll) that contains:

public class Person
{
    // Field 
    public string name;

    // Constructor that takes no arguments. 
    public Person()
    {
        name = "unknown";
    }

    // Constructor that takes one argument. 
    public Person(string nm)
    {
        name = nm;
    }

    // Method 
    public void SetName(string newName)
    {
        name = newName;
    }

}

public class Table
{
    // Field 
    public int width;
    public int lenth;
    public int height;

    // Constructor that takes no arguments. 
    public Table()
    {
        width = 0;
        length = 0;
        height = 0
    }

    // Constructor that takes three arguments. 
    public Table(int w, int l, int h)
    {
        width = w;
        length = l;
        height = h;
    }

    // Method 
    public void SetWLH(int w, int l, int h)
    {
        width = w;
        length = l;
        height = h;
    }
}

public class Printer
{
    public Printer(){}

    public void printAPerson(Person p)
    {
        //do stuff with p
    }

    public void printATable(Table t)
    {
        // do stuff with t
    }
}

I want to be able to instantiate either of the classes above, set attribute values and call methods at runtime from a different program in the most generic possible. eg. lets say I hame a programm called myprog.exe, i want to be able to do the following

myprog.exe objects.dll Person name testname Printer printAPerson where:

  • objects.dll is the dll that contains all required classes

  • Person is the first I will instantiate name is its attribute

  • testname is the value I will assign to this attribute

  • Printer is the class I will use for printing

  • printAPerson is the method in the Printer class I need to call with the specified object as a parameter.

As you can see, in the best case for my use scenario, neither of the objects and classes are/will be known at compile time so I would like to be as non-casting as possible. If that is not possible I will take what I can.

I have seen this, How to use reflection to call a method and pass parameters whose types are unknown at compile time?, which to my limited knowledge kind of does what I want minus the casting bits or I could be mistaken.

Thanks a lot!





lundi 27 juillet 2015

GetCustomAttribute Equivalent in .NET 4.0

I am using a sample project for Entity Framework Audit Trail from here

The problem is we are already using .NET 4.0 in our project but this sample is using .NET 4.5.

Can somebody tell me what is the equivalent of:

    private static string ColumnNameFactory(this Type type, string propertyName)
    {
        string columnName = propertyName;
        Type entityType = type.GetEntityType();
        var columnAttribute = entityType.GetProperty(propertyName).GetCustomAttribute<ColumnAttribute>(false);
        if (columnAttribute != null && !string.IsNullOrEmpty(columnAttribute.Name))
        {
            columnName = columnAttribute.Name;
        }
        return columnName;
    }

In this code: GetCustomAttribute is not recognized.





How to get the assembly name(not qualified name) from type(only assembly name without version or culture or publickeyToken) in c#

How to get the assembly name (only name ) without namespace or culture or public key token;typeof (MyClass).AssemblyQualifiedName ---> give me the fully qualified name and i want only the assembly name not the qualified name





Dynamically create and compile a function in Java 8

I have a Java program that generates a mathematical equation based on user input. I'd like to evaluate the equation, but iterating over its syntax tree is rather slow. A faster solution is to put the equation in a Java file, compile it, and call the compiled code (during runtime). Here is what I am currently doing:

  • Create an Equation.java file with the function as a static member. For example, if the equation generated is 3*x + 2*y (the real equation is much more complicated), the program would create the file

    public class Equation {
        public static DoubleBinaryOperator equation = (x, y) -> 3*x + 2*y;
    }
    
    
  • Compile it into Equation.class using JavaCompiler
  • Dynamically import the class file and call the equation using reflection

This is an enormous amount of boilerplate for something that seems like it should be simple. Is there an easier way of turning this equation into a function and calling it at runtime?





The type or namespace name 'entityName' does not exist in the namespace. CodeDOM and EF trouble

I am using Entity Framework. I am generating both my entities and contexts dynamically with CodeDOM (one context for every entity type until I get into complex entity relationships). In order to make sure the entity I generate is part of the model of its corresponding context, I am using reflection to get the entity's type and I write this into the code that generates the context. To see this more concretely, I have this method in my class that generates the context:

public static CodeMemberProperty HardCodeDbSet(string contextName, Type entityType)
{
    string entityName = entityType.ToString();
    CodeMemberProperty prop = new CodeMemberProperty();
    prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
    prop.Name = entityName + "s";
    prop.Type = new CodeTypeReference(typeof(DbSet<>).MakeGenericType(entityType));
    return prop;
}

This methods generates the following line in the generated context class:

public System.Data.Entity.DbSet<Models.GeneratedEntities.Soap> Soaps
{
}

It says Soap and Soaps because in my test program I made the entity name Soap (just something random). But in general it will be whatever entity name I give it.

When I try to generate an instance of this class to use, however, I get the following error:

"c:\Users\MyUserAccount\Documents\ContextTest\bin\Debug\EFEntityTest_v1.cs(29,94) : error CS0234: The type or namespace name 'Soap' does not exist in the namespace 'Models.GeneratedEntities' (are you missing an assembly reference?)\n"

Line 29, column 94 is exactly where Soap starts in the line after GeneratedEntities.:

public System.Data.Entity.DbSet<Models.GeneratedEntities.Soap> Soaps
{
}

So clearly this line isn't working properly:

prop.Type = new CodeTypeReference(typeof(DbSet<>).MakeGenericType(entityType));

I know it has something to do with the fact that I'm calling MakeGenericType on something that's also generated dynamically with CodeDOM, but I feel like it should work. Does anyone have any ideas of what's going on? Also I do have the reference assembly passed in for the project where Models.GeneratedEntities is.





BluetoothHeadsetClient: Could not bind to Bluetooth Headset Client Service with Intent

I want to use the BluetoothHeadsetClient. in order to use this hidden SDK code I use reflection.

I want to call

mBluetoothAdapter.getProfileProxy(this, mHeadsetProfileListener, BluetoothProfile.HEADSET_CLIENT);

but BluetoothProfile.HEADSET_CLIENT is hidden in BluetoothProfile.java. in order to solve it I run the following code

protected BluetoothProfile.ServiceListener mHeadsetProfileListener = new  BluetoothProfile.ServiceListener()
{
    @Override
    public void onServiceDisconnected(int profile) {            

    }

    @Override
    public void onServiceConnected(int profile, BluetoothProfile proxy)
    {

        mlisten = mHeadsetProfileListener;
        mHeadSetCleintObj = proxy;

        // reflection for getting the HEADSET_CLIENT type
        try {

            Class classRef = Class.forName("android.bluetooth.BluetoothProfile");
            Field field = classRef.getField("HEADSET_CLIENT");                
            if(profile == BluetoothProfile.HEADSET ) {
                mBluetoothAdapter.getProfileProxy(getApplicationContext(), mHeadsetProfileListener, field.getInt(proxy));
            }

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

        mBluetoothHeadset.getConnectedDevices();

    }
};


@Override
public void onDestroy() {
    unregisterReceiver(mPairReceiver);

    super.onDestroy();
}

field.getInt(proxy) value == 16 --> BluetoothProfile.HEADSET_CLIENT as I wanted. but when I run the

mBluetoothAdapter.getProfileProxy(getApplicationContext(), mHeadsetProfileListener, field.getInt(proxy));

I see the following error

E/BluetoothHeadsetClient﹕ Could not bind to Bluetooth Headset Client Service with Intent { act=android.bluetooth.IBluetoothHeadsetClient }

do you know how to solve this type of error?

Thanks!





How to dynamically add new methods to a class in Java using reflection

I want to find a way to add dynamically a method to a class in java.

In this case I want to add the methods of a private object to the class and then if they are call, execute the method on this same object. Example :

public class A {
    private someType someObject;

    public A (someType someObject) {
        this.someObject = someObject;
        Method[] methods = someObject.getClass().getDeclaredMethods();

        for (Method method:methods) {
            //do something here to add the object method to the class like this
            Method newMethod;
            newMethod.setName("A."+method.getName());
            newMethod.setToDo("this.someObject."+method.getName());
            newMethod.create();
        }
    }
}

How to do something like this ? I already searched on stackoverflow and I don't find what I want.





Could java reflection add method into class file that are not in java source file?

I'm digging into the source code of the deeplearning for java recently. There is such a class NeuralNetConfiguration in which there are tons of fields that all requires getters and setters. The NeuralNetConfiguration.java source code does not provide any, however.

When I open this project in IntelliJ, ctrl click on the usage of this class, which are methods mostly like, NeuralNetConfiguration.getNInput() or NeuralNetConfiguration.getKernelSize(), the IDE direct me to the compiled class file in which all the getters are defined for each of the field in this class.

Just wonder how this is done since I'm a new bee to java. Posts I found about java reflect suggest that reflect can not add method to a method to a class unless you wrote your own classloader. I check the deep learning for java project and I don't think they have done that.

What bothers me too from time to time is, IntelliJ starts to report errors that those getFields methods could not be resolved since they are not in the source file at all, especially after my building the project using IntelliJ instead of using mvn command line.





Class yii\debug\Module does not exist

I am trying to run my Yii2 application on Vagran virtual machine. As provison I use Ansible. Here is my ansible playbook file:

---
- hosts: vagrant
  sudo: true
  tasks:
- name: 1. install Apache
  apt: name=apache2 state=present

- name: 1.1 Delete temporary file
  file: path=/var/www/web/index.html state=absent

- name: 2. install PHP module for Apache
  apt: name=php5 state=latest update_cache=yes

- name: 3. Install PHP GD library
  apt: name=php5-cli state=latest

- name: 4. Start Apache
  service: name=apache2 state=running enabled=yes

- name: 5. Install MySQL
  apt: pkg=mysql-server state=present

- name: 6. Install python-mysqldb
  apt: pkg=python-mysqldb state=present

- name: 7. Install PHP MySQL bindings
  apt: pkg=php5-mysql state=present

- name: 8. Restart apache
  service: name=apache2 state=restarted

- name: 9. Set MySQL root password
  debconf: name='mysql-server' question='mysql-server/root_password' value='password' vtype='password'

- name: 10. Confirm MySQL root password before installing
  debconf: name='mysql-server' question='mysql-server/root_password_again' value='password' vtype='password'

- name: 11. Database creation with name gitSearch 
  mysql_db: name=gitSearch state=present

- name: 12.a Copy database dump
  copy: src=../gitSearch.sql.bz2 dest=/tmp/gitSearch.sql.bz2 

- name: 12.b Copy database dump
  mysql_db: name=gitSearch state=import target=/tmp/gitSearch.sql.bz2

- name: 13. Ensure curl is installed
  apt: pkg=curl state=installed
  when: ansible_os_family == 'Debian'

- name: 14. Install Composer into the current directory
  shell: >
    curl -sS http://ift.tt/SI3ujS | php
    creates=/usr/local/bin/composer

- name: 15. Install php5-curl
  apt: name=php5-curl state=latest update_cache=yes

- name: 16. Move Composer into globally-accessible location.
  shell: >
    mv composer.phar /usr/local/bin/composer
    creates=/usr/local/bin/composer

- name: 18. Update dependencies v2
  composer: command=install working_dir=/var/www

When I run my project I have an exception:

ReflectionException

Class yii\debug\Module does not exist
in /var/www/vendor/yiisoft/yii2/di/Container.php

I think the problem is with composer, because before provision gets to composer tasks everything is fine. On my local machine (not Vagrant box) everything was fine too. Debugger section in config:

$config['modules']['debug']['class'] = 'yii\debug\Module';
$config['modules']['debug']['allowedIPs'] = ['*']; 





dimanche 26 juillet 2015

C# - Dynamically create lambda search on IQueryable on nested objects

I'm trying to build a dynamic search on nested objects, which will later be sent to EF and SQL Server. So far, I'm able to search on all properties of the first object. Here's a very simplified version:

public class User
{
    public string Name { get; set; }
    public Address Address { get; set; }
}
public class Address
{
    public string City { get; set; }
}

public class MyClass<TEntity> where TEntity : class {
    public IQueryable<TEntity> applySearch(IQueryable<TEntity> originalList, string propName, string valueToSearch) {

        ParameterExpression parameterExpression = Expression.Parameter(typeof(TEntity), "p");
        PropertyInfo propertyInfo = typeof(TEntity).GetProperty(propName);
        MemberExpression member = Expression.MakeMemberAccess(parameterExpression, propertyInfo);
        lambda = Expression.Lambda<Func<TEntity, bool>>(Expression.Equal(member, Expression.Constant(valueToSearch)), parameterExpression);

        return originalList.Where(expression);
    }
}

When propName = "Name" everything is fine, but when propName = "Address.City", the propertyInfo is null, and I get this error on the member assignment line:

System.ArgumentNullException: Value cannot be null

I was able to obtain the propertyInfo of the nested property using the solution from this answer:

PropertyInfo propertyInfo = GetPropertyRecursive(typeof(TEntity), propName);
...

private PropertyInfo GetPropertyRecursive(Type baseType, string propertyName)
{
    string[] parts = propertyName.Split('.');

    return (parts.Length > 1)
        ? GetPropertyRecursive(baseType.GetProperty(parts[0]).PropertyType, parts.Skip(1).Aggregate((a, i) => a + "." + i))
        : baseType.GetProperty(propertyName);
}

But then I get this error on member assignment:

System.ArgumentException: Property 'System.String City' is not defined for type 'User'

I don't know if I'm on right track here. How can I make a dynamic search on nested objects, so that this can be turned into a lambda and later sent to SQL?





Mutating property by its name

With the help of Reflection API I'm getting the properties list for my types.

func inspectedProperties(ignored: [String] = []) -> [Property] {
    var properties = [String]()

    for child in self.children() {
        guard let label = child.label else {
            continue
        }

        properties += [label]
    }

    return properties.filter { !ignored.contains($0) }
}

This function returns me the names for all properties.

Now I want to mutate a certain property just by knowing its name.

class Fruit {
    private dynamic var name = "Apple"
}

If I call Fruit().inspectedProperties() I'll get the following array ["name"].

But is it possible to mutate the variable named "name"?





Get name of property with reflection

In Swift 2.0 I'm looking for a way to get a property by reflection, so I don't have to rely on string constants for various functionality, such as Cocoa Bindings.

However, the documentation for the Mirror class is unclear if it's possible to do something in the line of:

let myPropertyString = getName(myObject.myProperty) using Reflection.

Is this possible in Swift today? And if so, how would one go about doing it?





Get property-name of generic abstract class

Considering the following implementation of a generic, abstract class:

public abstract class BaseRequest<TGeneric> : BaseResponse where TRequest : IRequestFromResponse
{
    public TGeneric Request { get; set; }
}

Is there any chance to get the name of the property Request without having an instance inherited from it?

I need Request as string "Request" to avoid using hardcoded strings. Any ideas how to make this through reflection?





Convert a generic collection to a XML in C#

I want to write a generic method that returns a XML once a collection of type T is passed. I tried below code, but doesn't work as expected and getting {"Object does not match target type."} exception. Any advise on enhancing this to include element attributes is highly appreciated. Thanks

    public static XElement GetXElements<T>(IEnumerable<T> colelction) where T : class
    {
        XElement xml = new XElement(typeof(T).GetType().Name);
        foreach(var x in typeof(T).GetProperties())
        {
            var name = x.Name;
            var value = typeof(T).GetProperty(x.Name).GetValue(x);
            xml.Add(new XElement(name,value));
        }         
        return xml;
    }

For example, if I send a collection like below to above method,

        var col = new List<Employee>()
        {
            new Employee
            {
                FirstName = "John",
                Sex= "Male"
            },
            new Employee
            {
                FirstName = "Lisa",
                Sex= "Female"
            },
        };

and invoke the method as GetXElements<Employee>(col,"Employees")I am expecting to get a XML like below

<?xml version="1.0" encoding="utf-8"?>
<Employees>
  <Employee>
     <FirstName>John</FirstName>
     <Sex>Male</Sex>
  </Employee>
  <Employee>
     <FirstName>Lisa</FirstName>
     <Sex>Female</Sex>
  </Employee>
<Employees>





samedi 25 juillet 2015

Injecting beans to library which uses newInstance()

Today I want to ask question about spring and newInstance() method.

I'm using TyrusProject(generaly websockets in java). I created EndPoint bean and Server bean. Server depends on endpoint.

Its constructor looks like this:

Server(String path, int port, Class<?> endpoint)

And there is problem. EndPoint implements ApplicationContextAware, to get applicationContext. It is set at first, but then server creates it's own instance of endpoint and I get NullPointerException.

Is there any way I can do something about it?
Thanks in advance.





getConstructor throws NoSuchMethodException on Derived class [duplicate]

This question already has an answer here:

I recently have encountered a strange error which I can't get my head around. I'm trying to instantiate derived classes of a base class through reflection, however the getConstructor method can't find the clearly existing constructor. In code:

package com.test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Test {

    abstract class Base {
        protected abstract String doWork(String param);
    }

    final class Derived extends Base {
        private String pattern;
        public Derived(String pattern) {
            this.pattern = pattern;
        }
        @Override
        public String doWork(String param) {
            return param.matches(pattern) ? param.toUpperCase() : param.toLowerCase();
        }
    }

    public static void main(String... args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

        Constructor<? extends Base> ctor = Derived.class.getConstructor(String.class);
        Base b = ctor.newInstance(".*");
        System.out.println(b.doWork("Hello World!"));

    }

}

Clearly shows my intention, I'd love to see "HELLO WORLD!" as an output however when I execute the application all I can see is:

Exception in thread "main" java.lang.NoSuchMethodException: com.test.Test$Derived.<init>(java.lang.String)
    at java.lang.Class.getConstructor0(Class.java:3074)
    at java.lang.Class.getConstructor(Class.java:1817)
    at com.test.Test.main(Test.java:25)

Now, it's clear that it picks up the Derived.class which clearly has an method with java.lang.String parameter however the exception still rises and tries to tell me there's no such thing.

Edit:

I should have known that someone will mark the question as duplicate without even looking at it in details. So just for you Mr. Sotirios Delimanolis, I know. Yeah, believe me, I know that you can pass the enclosing type as the first parameter to the constructor. Allow me to ask you something: Di you try it? Because I did. Do you think it works? No. Do you know why? Well I don't. So let's put things simple. If I move the Base and Derived classes outside of class Test, the upper program runs and gives the perfect output. I move them in, and not even your precious search works. Please first read the actual question and then mark it...





How to get multi-signature caller method with reflection?

Suppose we have:

public void caller(Object obj){
      called();
}
public void caller(){
      called();
}

as you can see, caller has two signatures. In order to get the stack trace we can use:

StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();

But it only returns the name of the method. How can I find the actual true caller?





vendredi 24 juillet 2015

How I can transfer atrributes values from a Objects to another

I want tranfers attributes values from a object that came from my Entity manager to a new object.

The result Object is always null

 public class ReflectionUtil {

    public static Object copyAttributesFromTo(Object a, Object b) throws IllegalArgumentException, IllegalAccessException {
        Field[] fieldsFromFirstClass = a.getClass().getDeclaredFields();
        Field[] fieldsFromSecondClass = b.getClass().getDeclaredFields();

        for (Field currentFieldFromTheFirstClass : fieldsFromFirstClass) {
            for (Field currentFieldFromTheSecondClass : fieldsFromSecondClass) {
                String nameOfTheFirstField = currentFieldFromTheFirstClass.getName();
                String nameOfTheSecondField = currentFieldFromTheSecondClass.getName();

                if (!Modifier.isFinal(currentFieldFromTheFirstClass.getModifiers())) {//Dispensa os Final
                    if (!currentFieldFromTheFirstClass.isAnnotationPresent(Id.class)) {//Não sobescreve campo id
                        if (nameOfTheFirstField.equals(nameOfTheSecondField)) {
                            currentFieldFromTheFirstClass.setAccessible(true);
                            currentFieldFromTheSecondClass.setAccessible(true);
currentFieldFromTheSecondClass.get(b));
                            currentFieldFromTheFirstClass.set(a, currentFieldFromTheSecondClass.get(b));
                        }
                    }
                }
            }
        }

        return a;
    }
}





Get generic types of child in scala 2.10

class Parent[T: ClassTag] {
}

class Child[U: ClassTag, T: ClassTag] extends Parent[T] {
}

val o: Parent[_] = new Child[Int, String]

Is it possible to get the actual types of T and U given o (note its type Parent[_]), assuming you know o is of type Child?

I have tried a few things based on Runtime resolution of type arguments using scala 2.10 reflection but no luck so far.





c# Reflection MakeGenericMethod multiple generic types in method definition [duplicate]

This question already has an answer here:

I have the following generic method

 public static T2 MapCollection<T1, T2, T3, T4>(T1 source) 
            where T1 : ICollection<T3> 
            where T2 : ICollection<T4>
        {
          ...
        }

The goal here is to call this method using reflection so I need to MakeGenericMethod...

I do this like this :

Type type1 = prop1.PropertyType;
Type type2 = prop2.PropertyType;
Type type3 = prop3.PropertyType;
Type type4 = prop4.PropertyType;

MethodInfo mi = typeof (DynamicMapper).GetMethod("MapCollection");

Type[] typeArgs = { type1, type2, type3, type4 };

mi.MakeGenericMethod(typeArgs);

Then, I try to invoke the method..

object[] parametersArray = new object[] { value }; // value is set earlier in the code (PropertyInfo.GetValue(...))
object foo = mi.Invoke(null, parametersArray);

I get the following exception:

System.InvalidOperationException: Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.

I think this has something to do with the fact the the Generic Method has 4 generics arguments and only one parameter...

What am my missing on this?





Loading assembly at runtime, Autocad plugin example

After hours spent on this subject (and also dozens of pages visited) i am forced to ask for a help. I have seen a lot of posts on this subject, but i couldn't fix problem i get.

Basically, i want to do very simple thing: load assembly from my folder to application.


Here is question in short (all other details are explained in rest of text) I want to use Assembly.LoadFrom method to load my assembly (same assembly file is referenced with project, but with CopyLocal: false), but although assembly is loaded when method using it is invoked, program tries to load assembly from default locations. If it is found, then 2 same assemblies are loaded, and program uses last one, if it is not found then FileNotFoundException is raised. But, when i use same idea in Autocad plugin, everything works and exception is not raised, although files are not found.


I have test solution with 2 simple projects: TestExe (console application) and TestDll(dll library). I want to use types from TestDll in TestExe so i've added reference to TestDll(i am not referencing TestDll project, but file on specified location), but i want to load TestDll manually in the runtime. Why this is needed is explained at the end of text, with Autocad example.

As far as i understand, Assembly.LoadFrom method can be used for this purpose. So basic idea is: Load TestDll before method in TestExe is using it, so when method is called we have already loaded assembly. This way, whether referenced dll exists in default directories or not, we already have assembly loaded and it is going to be used.

From MSDN:

If an assembly with the same identity is already loaded, LoadFrom returns the loaded assembly even if a different path was specified.

So i understand that if i load dll once, every next load of same assembly (also from other location) will know that it is already added, so first one will be used.


Project: TestExe

//File: Program.cs
using System;
namespace TestExe
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(new ClassExe().ExeMethod());
        }
    }    
}
//File: ClassExe.cs
namespace TestExe
{
    class ClassExe
    {
        public string ExeMethod()
        {
            return new TestDll.ClassDll().DllMethod();
        }
    }
}

Project TestDll

using System.Reflection;

namespace TestDll
{
    public class ClassDll
    {
        public string DllMethod()
        {
            return Assembly.GetExecutingAssembly().Location;
        }
    }
}


As you can see, task is simple: display location of called assembly.

Lets say TestDll.dll is copied to application folder Extern\TestDll.dll.

If i set property CopyLocal: false of reference to TestDll in TestExe project, program fails with FileNotFoundException. (1) Is it because assembly is searched only in default directories (application dir and TestDll\TestDll.dll)?

Then i tried to load assembly manually, before using it:

static void Main(string[] args)
    {
        Assembly.LoadFrom(@"Extern\TestDll.dll");
        Console.WriteLine(new ClassExe().ExeMethod());
    }

But i get same FileNotFoundException, although TestDll has been loaded enter image description here

When i set attribute CopyLocal: true, then program works. But, it loads TestDll.dll again, from default location, and ignores assembly which is already loaded. enter image description here

The only way i managed program to work how i wanted (to be used assembly Extern\TestDll.dll) is with using AppDomain.AssemblyResolve event.


I have Autocad plugin which uses 10 different dlls, from different solutions. So i have plugin.dll which references 10 dll files across Documents folder, and set CopyLocal: true. But, when deployed to customer, i keep only plugin.dll in application folder, and all other dlls are in Libraries subdirectory. In static constructor of plugin class, i put Assembly.LoadFrom to be loaded from Libraries subdirectory, and everything works fine.

Sorry for long post but i wanted to explain it with details.

And thanks for any feedback :)